Currently having difficulty figuring out this one. I know that I am very near but I cannot figure out where I am going wrong.
I would like the output to show a string, where an even number corresponds to '?--' and an odd number corresponds to '?-', and concatenate all of the strings together. Eg. star_wars_iteration(3) should return '?-?--?-'
However, mine does not add up, it only returns it once.
def star_wars_iteration(num_enemy_ships):
counter = 1
result = ''
while counter in range(1,num_enemy_ships + 1):
if counter % 2 == 0:
return '?--'
elif counter % 2 == 1:
return '?-'
result = result + counter
counter = counter + 1
return stops the function as soon as it is reached. Also you confuse while and for. What you want is:
def star_wars_iteration(num_enemy_ships):
result = ''
for counter in range(1,num_enemy_ships + 1):
if counter % 2 == 0:
result += '?--'
elif counter % 2 == 1:
result += '?-'
return result
Or if you want to use while then use while counter <= num_enemy_ships : (using in range(...) works too but is unnecessarily inefficient) and make sure the counter = counter + 1 line is inside the while block.
Note: more concise and pythonic:
def star_wars_iteration(num_enemy_ships):
return ''.join('?-' if counter % 2 else '?--' for counter in range(1,num_enemy_ships + 1))
Why don't you use the Pythonic iterators and range function for what they are meant to be you don’t need to increment starting and end values in the range:
def star_wars_iteration(num_enemy_ships):
return "".join('?-' if index % 2 else '?--' for index in range(num_enemy_ships))
Related
In this function, I want to return a value when the if statement is executed.
Since Python always returns something, it returns None.
def Persistence(number, counter):
numArr = [int(i) for i in str(number)]
result = 1
data = None
for j in numArr:
result *= j
if len(str(number)) == 1:
data = str(f'Done. {counter} steps taken')
print(data)
# return data
else:
counter = counter + 1
Persistence(result, counter)
# return data
print(Persistence(333,0))
Maybe I put the return keyword in the wrong place (I checked by putting it in two different places, marked as a comment) or something else, but I couldn't figure it out.
Please help me out. Also, if there is another way to count the recursion steps besides my technique, please let me know.
Maybe try this :
def Persistence(number, counter):
numArr = [int(i) for i in str(number)]
result = 1
for j in numArr:
result *= j
if len(str(number)) == 1:
return str(f'Done. {counter} steps taken')
counter = counter + 1
return Persistence(result, counter)
print(Persistence(333,0))
Hope it helps
The issue is that you're not setting the value from the else call to persistence to anything. The following code return the data value for me:
def Persistence(number, counter):
numArr = [int(i) for i in str(number)]
result = 1
data = None
for j in numArr:
result *= j
if len(str(number)) == 1:
data = str(f'Done. {counter} steps taken')
print(data)
return data
else:
counter = counter + 1
data = Persistence(result, counter)
return data
x = Persistence(333, 0)
Then if we print x:
print(x)
# Done. 3 steps taken
Your logic to count the recursion steps is basically correct, you just need to place the return statements for both the:
1)Base case
2)The recursive call itself
The following modification to your code will do the trick of what you are asking:
def Persistence(number, counter):
numArr = [int(i) for i in str(number)]
result = 1
data = None
for j in numArr:
result *= j
if len(str(number)) == 1:
data = str(counter)
return data
else:
counter = counter + 1
return Persistence(result, counter)
print(Persistence(333,0))
The above code will return the output of:
3
Please note that the reason you were getting "None" as the output in your original code is because you were not making a return at the actual recursive call itself: **return** Persistence(result, counter)
So when you ran print(Persistence(333,0)) it was returning nothing resulting in the None.
This question is better to learn about recursion than you may think. But we won't muddy the waters by mixing recursion (functional style) with statements and side effects (imperative style).
It looks like you're trying to calculate multiplicative root and persistence. Instead of putting all concerns of the computation into a single function, break it down into sensible parts -
def digits (n = 0):
if n < 10:
return [ n ]
else:
return digits (n // 10) + [ n % 10 ]
def product (n = 0, *more):
if not more:
return n
else:
return n * product (*more)
def mult_root (n = 0):
if n < 10:
return [ n ]
else:
return [ n ] + mult_root (product (*digits (n)))
def mult_persistence (n = 0):
return len (mult_root (n)) - 1
print (mult_persistence (333))
# 3
print (mult_root (333))
# [ 333, 27, 14, 4 ]
Below is a function which is supposed to return longest palindromic substring of a string. Though the function itself looks alright but for some strange reason It is not returning the string. Any Idea what I am missing here?
def largest(string, repeat=None):
if len(string) <= 1 and repeat:
return repeat[max(repeat.keys())]
elif len(string) <= 1:
return string
list_str = list(string)
repeat = repeat or {}
end_index = -1
while len(list_str)+end_index:
construct = list_str[0:len(list_str)+end_index+1]
reversed_construct = construct.copy()
reversed_construct.reverse()
if construct == reversed_construct:
repeat[len(construct)] = ''.join(construct)
end_index -= 1
string = string[1:]
largest(string, repeat=repeat)
In a order to return a value from a recursive function, one must put return recursive_function(x) so that when a value is returned it is placed in a position where the data can be accessed by the function 'above' it, so to speak.
def Factorial(total,counter):
if counter == 0: #tests whether the counter is at 0
return(total) #if it is at 0 return the product of the consectutive numbers between 0 and starting counter
total *= counter #set the total to itself times the current pass counter
return Recursion(total,(counter-1)) #return the value of this function passing the total and the counter -1
You see that in this example for me to hold the value that was passed previously I have to return it so that after all the recursions are completed they will all pass the data back up the chain of function.
I am learning python, and trying to use some ternary operators.
I am trying to make the function below using a ternary:
def array_count9(nums):
count = 0
for i in nums:
if i == 9:
count += 1
return count
I have tried:
def array_count9(nums):
count = 0
count += 1 if i == 9 for i in nums else pass
return count
which threw a SyntaxError, then after looking around I found this and changed my code for what I believed was better ordering:
def array_count9(nums):
count = 0
count += 1 if i == 9 else pass for i in nums
return count
Still receiving SyntaxError which is pointing at the for. I've tried using parentheses in different places too.
I have looked around and there are other related threads such as this and this, which resulted in me trying this:
def array_count9(nums):
count = 0
count += 1 if i == 9 else count == count for i in nums
return count
I've also tried other resources by searching Google, but I can't quite work it out. Please teach me.
Thanks
I think this is the most idiomatic way to write the code:
def array_count9(nums):
return sum(num == 9 for num in nums)
But you could also do this if you want to use the if/else construct:
def array_count9(nums):
return sum(1 if num == 9 else 0 for num in nums)
The blueprint for a ternary operator is:
condition_is_true if condition else condition_is_false
The statement where the syntax error occurs is at
count += 1 if i == 9 else pass for i in nums
ie count += 1 does not meet the blueprint specification, because condition_is_true should not need to be evaluated.
Okay so using your examples was a little tricky because a ternary operator can't include anything outside it's specific blueprint; that being the for loop you're trying to pass with it.
count += 1 if i == 9 for i in nums else pass
So after fiddling around with the code:
def array_count9(nums):
count = 0
count += 1 if i == 9 for i in nums else pass
return count
I was sure you were looking for something that works involving ternary operators and that for loop. So keeping your goal in mind, this is what I came up with.
numss = [3,6,9,10,35]
def count9(nums):
count = 0
a = count + 1
for i in nums:
count = (a if i == 9 else count) #This being the ternary operator
return count
print (count9(numss))
Hope this helps.
I am having trouble finish python code.
overlap('','hello') → 0.
I have managed to get the number back when the length of the strings match but if one of the strings has a smaller length than the other. I keep getting index out of range. Can someone help me finish this.
def overlap(string1,string2):
count = 0
for i in range(len(string1)):
for j in range(len(string2)):
if string1[i] == string2[j]:
count = count + 1
i+=1
else:
i+=1
return count
When running this with a function call. if both strings are equal it gives me the correct number, but if one is smaller or longer then its index out of range.
Thanks
Create one for loop which iterates through min(len(string1), len(string2)) and you would avoid problem when one string is smaller than another, see sample below:
def overlap(string1,string2):
count = 0
for i in range(min(len(string1), len(string2))):
if string1[i] == string2[i]:
count = count + 1
return count
print overlap('summer','winter') #2
print overlap('abcb','dbeb') #2
print overlap('summer','sum') #3
print overlap('','winter') #0
Good Luck!
Replace the nested loops and repeat only for the smaller length.
def overlap(string1, string2):
count=0;
len1= len(string1)
len2= len(string2)
smallLen= len1
if len2<len1:
smallLen= len2
for i in range(smallLen):
if string1[i]== string2[i]:
count+= 1
return count
Thinking about it in order of things that need to be done, you have to first figure out which of the two given strings have the shortest length because that will be your bound for the amount of loop iterations. In Python you can do a conditional assignment like:
maxloop = len(str1) if len(str1) <= len(str2) else len(str2)
You make the condition <= because it doesnt matter which is chosen if they're equal, so just pick the first.
Now that you have the amount of iterations you'll do, you can set up the loop and counter:
count = 0
for i in range(maxloop):
if str1[i] == str2[i]:
count += 1
The single if statement is checking the character at position i in both strings and seeing if they are equal, and if they are, then it'll add one to the overlap counter. Then simply return the count after the loop has terminated.
Try this:
count = 0
if len(string1) < len(string2):
for i in range(len(string1)):
if string1[i] == string2[i]:
count += 1
else:
for i in range(len(string2)):
if string1[i] == string2[i]:
count += 1
return count
I am trying to solve the 'Love-Letter' mystery problem of HackerRank using Python, but I am stuck at a place where in my loop a variable is not getting updated.
s = input()
first_char = s[0]
last_char = s[-1]
ascii_first_char = ord(first_char)
ascii_last_char = ord(last_char)
count = 0
i = 1
while ascii_first_char < ascii_last_char:
count += abs((ascii_last_char-ascii_first_char))
ascii_first_char = ord(s[i])
ascii_last_char = ord(s[-i])
i += 1
print(count)
If you try to run that, you would see that alc is not changing it's value according to ord(s[i]) where I keeps incrementing. Why is that happening?
You get the first letter with s[0] and the last with s[-1]. In your loop you take the next letters with the same index i.
I don't understand your condition in the while loop. Instead of "ascii_first_char < ascii_last_char" you should test if you have looked at every element of the string. For that we have to loop len(s)/2 times. Something like:
while i < len(s) - i:
or equivalent
while 2*i < len(s):
And this conditions only work for even length. I prefer for-loops when I know how many times I will loop
current_line = input()
# if length is even, we don't care about the letter in the middle
# abcde <-- just need to look for first and last 2 values
# 5 // 2 == 2
half_length = len(current_line) // 2
changes = 0
for i in range(index):
changes += abs(
ord(current_line[i]) - ord(current_line[-(i+1)])
)
print (changes)
s1 = ['abc','abcba','abcd','cba']
for s in s1:
count = 0
i = 0
j = -1
median = len(s)/2
if median == 1:
count += abs(ord(s[0])-ord(s[-1]))
else:
while i < len(s)/2:
count += abs(ord(s[j])-ord(s[i]))
i += 1
j -= 1
print(count)