I'm trying to write a function that takes an 8-character binary string s and a positive number as an integer n, and prints a sequence of n binary numbers that increase according to my increment function.
How to I edit my function so that I can print these?
Assuming all of your other code is correct, there are five problems in your recursive code.
First, you're trying to use the value returned by the recursive call to count. But you have no return statements anywhere, so what could that value possibly be? So that inc*cnt is just going to try to multiply a string by None and raise a TypeError. If you look at your code, you have no need to return anything upward; count just takes some values, prints something, and calls itself again. So just ignore the None that it returns.
Next, you're trying to increment s[-1]. But s is a string, so that's just going to be the last character. You want to "increment" the whole string, right? So just pass s.
Next, you're trying to call yourself with s[:-1]. Again, s is a string; this is going to try to increment the first 7 digits of that string, then the first 6, and so on. Why would you want that? What you want to increment is the value you just incremented. That is, the same thing you just stored in inc. So just pass inc.
Next, you're doing the print after the recursive call. This means you're going to call the function that prints the second and later values, then print the first value. And so on. So they're going to show up in reverse order. If you want the first value first, print before the recursive call.
Finally, you clearly want the original value and the next 4 to get printed, not the next 5 without the original value. So you have to print out the pre-incremented value, not the post-incremented one.
So, the minimal change to your code is:
def count(s, n):
if n == 0:
return
else:
inc = increment(s)
print(s)
count(inc, n-1)
Related
I know there are already at least two topics that explain how map() works but I can't seem to understand its workings in a specific case I encountered.
I was working on the following Python exercise:
Write a program that computes the net amount of a bank account based a
transaction log from console input. The transaction log format is
shown as following:
D 100
W 200
D means deposit while W means withdrawal. Suppose the following input
is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
One of the answers offered for this exercise was the following:
total = 0
while True:
s = input().split()
if not s:
break
cm,num = map(str,s)
if cm=='D':
total+=int(num)
if cm=='W':
total-=int(num)
print(total)
Now, I understand that map applies a function (str) to an iterable (s), but what I'm failing to see is how the program identifies what is a number in the s string. I assume str converts each letter/number/etc in a string type, but then how does int(num) know what to pick as a whole number? In other words, how come this code doesn't produce some kind of TypeError or ValueError, because the way I see it, it would try and make an integer of (for example) "D 100"?
first
cm,num = map(str,s)
could be simplified as
cm,num = s
since s is already a list of strings made of 2 elements (if the input is correct). No need to convert strings that are already strings. s is just unpacked into 2 variables.
the way I see it, it would try and make an integer of (for example) "D 100"?
no it cannot, since num is the second parameter of the string.
if input is "D 100", then s is ['D','100'], then cm is 'D' and num is '100'
Then since num represents an integer int(num) is going to convert num to its integer value.
The above code is completely devoid of error checking (number of parameters, parameters "type") but with the correct parameters it works.
and map is completely useless in that particular example too.
The reason is the .split(), statement before in the s = input().split(). This creates a list of the values D and 100 (or ['D', '100']), because the default split character is a space ( ). Then the map function applies the str operation to both 'D' and '100'.
Now the map, function is not really required because both values upon input are automatically of the type str (strings).
The second question is how int(num) knows how to convert a string. This has to do with the second (implicit) argument base. Similar to how .split() has a default argument of the character to split on, so does num have a default argument to convert to.
The full code is similar to int(num, base=10). So as long as num has the values 0-9 and at most 1 ., int can convert it properly to the base 10. For more examples check out built in int.
I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?
According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate
Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())
If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())
Question:
Fill in the function body for the Python3 function longestWord (you should leave the function header as it appears).
The function takes a single input argument which we assume is a list of strings, with each string forming one English word. The output should be a word from the list which has the greatest number of letters.
You must use a for loop to write this function.
Answer:
def longestWord(listOfWords):
biggestWord = listOfWords[0]
biggestNum = len(biggestWord)
for word in listOfWords:
num = len(word)
if num>biggestNum:
biggestNum=num
biggestWord=word
return biggestWord
print(longestWord(["Hello", "Goodbye"]))
I understand the first three lines. It takes the first value in the list and saves the length of the word inputted. However i don't understand the rest of the code. How does it compare the two inputted words to output the longest one. What is num and word?. Thank you.
I'd like to inform you that this question is about Python3 and not C++. Anyways, what the code is doing is it's taking the first word and stores it in a variable called biggestWord. and storing the length of biggestWord in a variable called biggestNum. Then for each word in listOfWords, it stores the word in a variable called word and stroing the length of it in variable called num. Then it compares num and biggestNum. If the length of some word i.e. num is bigger than the biggest length up until now, i.e. biggestNum, then it puts num in biggestNum to indicate that that's the biggest number up until now. and puts word in biggestWord replacing the old word. Then it returns the word with the biggest length, i.e. biggestWord.
Homework Question I am struggling with
Specification:
The third function you will write should be called ‘excelPrep’. Your function should take one (1) argument:
a string that will contain the Excel formula. The function should return two (2) values: first, a string
containing the modified Excel formula; and second an integer containing the number of dollar signs
removed.
Example Test Case:
excelPrep(‘=SUM($A$4:$A$12)’)
returns
=sum(a4:a12)
and
4
I will not write the entire code since this is stackoverflow and not homework helper so I think you should complete with your own mind.
The function should be something like:
Remove the $ by checking every letter in the string with for loop, at the same time add a number counter so that you can know how many $s you’ve removed. Making the input from =SUM($A$4:$A$12) into =SUM(A4:A12).
You could return the value now however if the assignment specified to make the letters in to lowercase. Make a new string variable and append all the letters from the function returned variable =SUM(A4:A12) check if the letter is a number if not .lower(). Which leaves you with =sum(a4:a12).
To return two values, in the end of your function type return stringVariable, integerVariable. Just be careful when ever you are calling the function, you will need to variables to store the outputs. Like: a, b = excelPrep(“=SUM($A$4:$A$12) which for your information a = “=sum(a4:a12)”, b = 4.
Hope that helps.
So the program that I wanna write is about adding two strings S1 and S2 who are made of int.
example: S1='129782004977', S2='754022234930', SUM='883804239907'
So far I've done this but still it has a problem because it does not rive me the whole SUM.
def addS1S2(S1,S2):
N=abs(len(S2)-len(S1))
if len(S1)<len(S2):
S1=N*'0'+S1
if len(S2)<len(S1):
S2=N*'0'+S2
#the first part was to make the two strings with the same len.
S=''
r=0
for i in range(len(S1)-1,-1,-1):
s=int(S1[i])+int(S2[i])+r
if s>9:
r=1
S=str(10-s)+S
if s<9:
r=0
S=str(s)+S
print(S)
if r==1:
S=str(r)+S
return S
This appears to be homework, so I will not give full code but just a few pointers.
There are three problems with your algorithm. If you fix those, then it should work.
10-s will give you negative numbers, thus all those - signs in the sum. Change it to s-10
You are missing all the 9s. Change if s<9: to if s<=9:, or even better, just else:
You should not add r to the string in every iteration, but just at the very end, after the loop.
Also, instead of using those convoluted if statements to check r and substract 10 from s you can just use division and modulo instead: r = s/10 and s = s%10, or just r, s = divmod(s, 10).
If this is not homework: Just use int(S1) + int(S2).