How do I complete this recursive function at output_string += ? Output should be: 5! = 5 * 4 * 3 * 2 * 1 = 120
def print_factorial(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string +=
return output_string
user_val = 5
print('%d! = ' % user_val, end="")
print(print_factorial(user_val, user_val))
def factorial_str(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string += factorial_str(next_counter, next_value)
return output_string
user_val = int(input())
print('{}! = '.format(user_val), end="")
print(factorial_str(user_val, user_val))
Using the above answer I was able to work out the code. I have posted the answer that passed the case test for me.
def print_factorial(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1 #This line will never execute, no recursive call will ever be made with fact_counter = 0 and there shouldn't be anyways, so its harmless.
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string += print_factorial(next_counter, next_value)
return output_string
user_val = 5
print('%d! = ' % user_val, end="")
print(print_factorial(user_val, user_val))
You needed to compute the next number in the factorial then add it with "*" too. So a recursive call should be made at the concatenation statement.
Umm, if fact_counter == 0, will NEVER execute and I've written a comment to point this out inside the code.
Related
#Here I define the user and cpu function
cpu_num = random.randint(1,6)
user_selection = ["Odd", "Even"]
def cpu_choice():
choice = random.randint(1,6)
print("The computer's choice is",choice)
return choice
def user_choice():
while(True):
choice = input("Odd or Even? ")
if choice in user_selection:
print("Your choice is",choice)
return choice
else:
print("You did not write your answer correctly, please try again.")
#In this function I define the result of each round based on previous formulas and two new variables (num_rounds and user_lives) and everything works well
def round_result():
num_rounds = 0
user_lives = 10
while num_rounds < 8 and user_lives > 0:
user_pick = user_choice()
cpu_pick = cpu_choice()
if (cpu_pick % 2 == 0) and (user_pick == "Even"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
if (cpu_pick % 2 == 0) and (user_pick == "Odd"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Even"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Odd"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
#Everything works well until here, I don't know what am I doing wrong in the winner function
def winner():
user_won = user_lives > 0 and num_rounds == 8
cpu_won = user_lives < 0
game = round_result()
while game:
if user_won is True:
print ('You won')
if cpu_won is True:
print ('Cpu won')
I've been studying in Hackerrank. Question wants me to sort an given array. I know there is some library functions for those but since i don't know any yet, i've tried to write it manually.
Sample input:
15 43 3 2 150
Sample output:
150 2 3 43 15
I've wanted to write a code starts reading the string from the right and stops when it finds a blank. Than adds the string before the blank to the final result. Then keeps going untill it reaches to the [0].
Here's my code:
sortedResult = ""
tempNumbers = ""
tempCount = 0
numbers = input()
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in range(-1, 11):
tempCount += 1
continue
else:
for counter2 in range(counter, counter + tempCount + 1):
tempNumbers += numbers[counter2]
sortedResult += tempNumbers
tempNumbers = ""
tempCount = 0
else:
for counter3 in range(counter, counter + tempCount + 1):
sortedResult += numbers[counter3]
print(sortedResult)
You appear to be sorting a string, not a list of numbers. To fix this, change the input line to numbers = [int(x) for x in input().split(" ")]. In addition, you should change tempNumbers and sortedResult to lists and use .append() instead of +=.
Final code:
sortedResult = []
tempNumbers = []
tempCount = 0
numbers = [int(c) for c in input().split(" ")]
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in range(-1, 11):
tempCount += 1
continue
else:
for counter2 in range(counter, counter + tempCount + 1):
tempNumbers.append(numbers[counter2])
sortedResult += tempNumbers
tempNumbers = []
tempCount = 0
else:
for counter3 in range(counter, counter + tempCount + 1):
sortedResult.append(numbers[counter3])
print(sortedResult)
Here's my final code. It is working and it works as the way i intented it to.
sortedResult = ""
tempNumbers = ""
tempCount = 0
numbers = input()
firstTenNumbers= "0123456789"
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in firstTenNumbers:
tempCount += 1
continue
else:
sortedResult += numbers[slice(counter + 1, tempCount + counter + 1)] + " "
tempCount = 0
else:
sortedResult += numbers[slice(tempCount + 1)]
tempCount = 0
print(sortedResult)
Okay so I finished a code on hackerrank. It passes the test case but once I submit it fails the others. I have scanned through the code several times without a solution. Any thoughts on this? I have attached the screenshot of the question and my code as well as the test case scenarios that failed.
My code:
#!/bin/python3
import math
import os
import random
import re
import sys
def batting_stats(lst):
rgh,rgf,totr,totbf,totd,crat = 0,0,0,0,0,0 #rgh: runs greater than 100, rgf: runs greater 50
#totr:total runs, totbf:total balls faced, #totd: total
#dismissals, crat: conversion rate
results = []
for inning in lst:
runs_scored = inning[0]
balls_faced = inning[1]
dismissed = inning[-1]
totr += runs_scored
totbf += balls_faced
totd += dismissed
if runs_scored >= 100:
rgh += 1
elif runs_scored == 50:
rgf += 1
average = totr // max(totd, 1)
strikeRate = int((totr / totbf) * 100)
if rgf > 0:
crat = ( rgh // rgf ) * 100
results.append([average, strikeRate, crat])
return results
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
innings_count = int(input().strip())
innings = []
for _ in range(innings_count):
innings_item = list(map(int, input().rstrip().split()))
innings.append(innings_item)
result = batting_stats(innings)
for x in result or []:
fptr.write(' '.join(map(str, x)))
fptr.write('\n')
fptr.close()
I don't have access to your grader, but here are some obvious issues I see.
if runs_scored >= 100:
rgh += 1
elif runs_scored == 50:
rgf +=1
should be
if runs_scored >= 100:
rgh += 1
rgf +=1 (because a 100 plus score is also a 50 plus score)
elif runs_scored >= 50: (at least 50 is the condition not exactly 50)
rgf += 1
Next,
average = totr // max(totd, 1)
should be
if totd==0:
average=totr
else:
average=totr/totd
And,
crat = ( rgh // rgf ) * 100 should be
crat = ( rgh / rgf ) * 100
I have included these edits together with a few more, and have tested this code on the one available input and a few others. It returns, as expected, a list of lists with numbers that match the expected output. Please try this out in the grader.
import math
def batting_stats(lst):
rgh,rgf,totr,totbf,totd,crat = 0,0,0,0,0,0
results = []
for innings in lst:
totr += innings[0]
totbf += innings[1]
totd += innings[2]
if innings[0] >= 100:
rgh += 1
rgf +=1
elif innings[0] >= 50:
rgf+=1
if totd==0:
average=totr
else:
average=totr/totd
strikeRate = (totr / totbf) * 100
if rgf > 0:
crat = ( rgh / rgf ) * 100
else:
crat=0
results.append([math.floor(average), math.floor(strikeRate), math.floor(crat)])
return results
Why am i getting a syntax error on line 28? It seems like it should be just a normal line of code that prints the statement, but I keep getting a normal syntax error for it.
print('Welcome to the encryptor program.')
message = input('Enter the message you would like to encrypt.\n')
message = message.lower()
key = input('Enter the key you would like to use.\n')
def encrypt(k, m):
count = 0
keyCount = 0
fullCount = 0
newM = ''
while fullCount < len(m):
if (count) >= len(str(key)):
keyCount = 0
num = ord(m[count]) - 97
if m[count] != ' ':
add = int((str(k))[keyCount])
newNum = (num + add) % 26 + 97
new = chr(newNum)
newM += new
else:
newM += ' '
count += 1
fullCount += 1
keyCount += 1
print(newM)
encrypt(key, message)
def new_key(k):
newKey = int('1' + '0' * (((len(str(k))))-1) - key
The line after this
print('The new key to decrypt the message is', newKey)
new_key(key)
I've just started to learn python and I've decided to try and do a bubble sort. I've used the code below which works ok if the numbers to be sorted are 0 to 9. After that, it doesn't sort them correctly. I think, in my limited knowledge that this is because it is a 'list'.
I would like the user to be able to input the numbers but for the program to sort them regardless of the length of the number. Any help would be appreciated.
def bubble_sort(items):
changes=0
for i in range(len(items)):
for j in range(len(items)-1-i):#-i = optimised??
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j] # Swap
changes=changes+1
print(items)
print("Number of passes =",i)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers=input()
items=numbers.split()
Try this:
print('welcome to the automatic bubble sorter')
inputted_list = input('please enter a list of numbers seperated by commas: ')
list = inputted_list.split(',')
number_of_items = int(len(list))
sorting_method = input('if you would like your list to be sorted in ascending order, press 1, if you would like it to be sorted in descending order, press 2')
print(list)
if sorting_method == '1':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
counter2 = 0
permanent_numbers = []
while number_of_swaps > 0:
counter2 = counter2 + 1
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
permanent_numbers.append(list[number_of_items - counter2])
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
elif sorting_method == '2':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
while number_of_swaps > 0:
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
try map:
I suggested using map before, but I just remembered that map in python 3.x* yields a generator rather than a list, so that is why you cannot take the length of it. The updated answer is below
numbers = input("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
items = [int(num) for num in numbers.split()]
Modified existing code:
#!/usr/bin
def bubble_sort(items):
changes = passes = 0
last = len(items)
swapped = True
while swapped:
swapped = False
passes += 1
for j in range(1, last):
if items[j - 1] > items[j]:
items[j], items[j - 1] = items[j - 1], items[j] # Swap
changes += 1
swapped = True
last = j
print(items)
print("Number of passes =",passes)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers = input()
items = [int(num) for num in numbers.split() if num.isdigit()]
if items: bubble_sort(items)
def b_sort(list):
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx] > list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
str_input= input("Enter numbers: ")
list = [int(x) for x in str_input.split()]
b_sort(list)
print('sorted elements are: ')
print(list)
def sort():
try:
n = [1,8,6]
l = len(n)
print("Original list:", n)
for i in range(l - 1):
for j in range(0,l - i - 1):
if n[j] > n[j + 1]:
n[j], n[j + 1] = n[j + 1], n[j]
print("List after sorting is:", n)
except:
print("Error in inputing values")
sort()