Question

Prob. 3 Develop a function that meets the requirement in the document string of sumDigits: 1 def sumDigits (s): Inputsisastring.The returned value should be the sum of all numerical digits in s In addition if the first non-empty char ofs is a minus sign then the returned value should add a minus sign to the sum E.g., sumDigits(A33S%4C++D ) should return 10, sunn Digits(-+z33S%4-D) 6 and sunn Digits ( -A+3-3-4»D) should both return -10 That is minus sign matters only when it is the first non-empty char You may need to look up s.isdigitO,s.lstrip() from help (str) 10

I will post what I currently have and also the tests for it. Unfortunately it randomly fails some tests so I was wondering if anyone could help.

def sumDigits(s):
'''Input s is a string. The returned value should be the sum of all numerical
digits in s.
In addition, if the first non-empty char of s is a minus sign, then the
returned value should add a minus sign to the sum.
E.g., sumDigits('A33$%4C*+D') should return 10, sumDigits('-+z33$%4-D')
and sumDigits(' -A+3-3-4*D') should both return -10.
That is, minus sign matters only when it is the first non-empty char.
You may need to look up s.isdigit(), s.lstrip(' ') from help(str).  
'''
r = 0
f = 1
flag = 0
  
for i in s:
if i.isdigit():
r = r+ int(i)
if flag == 0:
if i =='-':
f = -1
flag = 1
sumofdigits= f*r
return sumofdigits
  

######################################################################
if __name__=='__main__':

import numpy as np
import string, random

nondigits = string.ascii_letters + ' ' + string.punctuation

DEBUG = True
#DEBUG = False #uncomment to show more screen output

repeat=200
#arvect=np.random.randn(repeat,1)
arvect=np.random.normal(10**16, 10**17, (repeat,1))
arrint=[int(x*10) for x in arvect]

TEST=[]; tsum={}; ysum={}
for i in range(len(arrint)):
if arrint[i] >= 0:
sloc=0
for j in str(arrint[i]):
sloc+=int(j) #end for j
tsum[i]=sloc
else:
sloc=0
for j in str(arrint[i])[1:]:
sloc+=int(j) #end for j
tsum[i]=-sloc #end if

s1=str(arrint[i])
s2=[s1[0]]   
for j in s1[1:]:
s2.append(j)
s2.append(random.choice(nondigits))
if i%2 == 0:
s = ' ' + ''.join(s2)
else:
s = ' -/ ' + ''.join(s2)
if tsum[i]>0: tsum[i]=-tsum[i]


if DEBUG: print('s=',s)

ysum[i]=sumDigits(s)
if tsum[i] == ysum[i]:
TEST.append(True)
else:
TEST.append(False) #end for i


if all(TEST):
print("\n Great, you passed {} tests for Problem 3!\n".format(repeat))
else:
print("\n *** {} tests failed for Problem 3. Need more debugging.\n".format(len([x for x in TEST if x==False])))

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please give the thumbs up, if it is helpful for you!!. Let me know if you have any doubts.

Your code will fail for sumDigits('A+3-3-4*D').

if should retrun 10 but your code is returing -10.

I have corrected the code, Please check and do let me know if it is passing all the cases.

def sumDigits(s):
r = 0
f = 1  
for i in s:
if i.isdigit():
r = r+ int(i)
if s[0] == '-':
f = -1
sumofdigits= f*r
return sumofdigits

sumDigits('A33$%4C*+D')  
sumDigits('-A+3-3-4*D')
sumDigits('A+3-3-4*D')  

Output:

Add a comment
Know the answer?
Add Answer to:
I will post what I currently have and also the tests for it. Unfortunately it randomly...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • C++ problem where should I do overflow part? in this code do not write a new...

    C++ problem where should I do overflow part? in this code do not write a new code for me please /////////////////// // this program read two number from the user // and display the sum of the number #include <iostream> #include <string> using namespace std; const int MAX_DIGITS = 10; //10 digits void input_number(char num[MAX_DIGITS]); void output_number(char num[MAX_DIGITS]); void add(char num1[MAX_DIGITS], char num2[MAX_DIGITS], char result[MAX_DIGITS], int &base); int main() { // declare the array = {'0'} char num1[MAX_DIGITS] ={'0'}; char...

  • The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also...

    The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...

  • C++ When running my tests for my char constructor the assertion is coming back false and...

    C++ When running my tests for my char constructor the assertion is coming back false and when printing the string garbage is printing that is different everytime but i dont know where it is wrong Requirements: You CANNOT use the C++ standard string or any other libraries for this assignment, except where specified. You must use your ADT string for the later parts of the assignment. using namespace std; is stricly forbiden. As are any global using statements. Name the...

  • Given the following C code. Develop a evaluate post fix function that calculates the converted post...

    Given the following C code. Develop a evaluate post fix function that calculates the converted post fix. #include <stdio.h> #include <ctype.h> #define max 10 char s[100]; int top=-1; void push(char); char pop(); int precede(char); main(){    char infix[100],postfix[100],ch;    int i=0,j=0;    // Read infix expression from user    printf("Enter infix expression:");    scanf("%s",infix);    // evaluate each char in infix expression    while((ch=infix[i++])!='\0'){        // if it is number, add it to postfix expression        if(isalnum(ch)){   ...

  • Can someone provide detailed comments on what this code is doing for each line? I posted...

    Can someone provide detailed comments on what this code is doing for each line? I posted the assignment below. I am having trouble learning and getting assistance because I keep getting answers provided w/ good information on how the problem was solved. I have spent too much on tutoring this month and I am relying heavily on assistance here. Can you please assist with helping me understand each line of code that was written here? Also- is there an easier...

  • Hello, I am having trouble with a problem in my C language class. I am trying...

    Hello, I am having trouble with a problem in my C language class. I am trying to make a program with the following requirements: 1. Use #define to define MAX_SIZE1 as 20, and MAX_SIZE2 as 10 2. Use typedef to define the following struct type: struct {     char name[MAX_SIZE1];     int scores[MAX_SIZE2]; } 3. The program accepts from the command line an integer n (<= 30) as the number of students in the class. You may assume that the...

  • CONVERT THE FOLLOWING C/C++ PROGRAM INTO JAVA: //LinkedString.h #pragma once #include<iostream> #include<string> using namespace std; //declare...

    CONVERT THE FOLLOWING C/C++ PROGRAM INTO JAVA: //LinkedString.h #pragma once #include<iostream> #include<string> using namespace std; //declare a node datastruct struct Node {    char c;    Node *next; }; class LinkedString {    Node *head; public:    LinkedString();    LinkedString(char[]);    LinkedString(string);    char charAt(int) const;    string concat(const LinkedString &obj) const;    bool isEmpty() const;    int length() const;    LinkedString substring(int, int) const;    //added helper function to add to linekd list private:    void add(char c); };...

  • I am having problems with the following assignment. It is done in the c language. The...

    I am having problems with the following assignment. It is done in the c language. The code is not reading the a.txt file. The instructions are in the picture below and so is my code. It should read the a.txt file and print. The red car hit the blue car and name how many times those words appeared. Can i please get some help. Thank you. MY CODE: #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char *str; int...

  • C Programming // Compile with: clang radio.c -o radio // Run with: ./radio #include <stdio.h> #include...

    C Programming // Compile with: clang radio.c -o radio // Run with: ./radio #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name    loadMusicFile // @Brief   Load the music database //          'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size; song++){       // Allocate memory for each individual character string       database[song] =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT