Here is my code:
i=int(input("enter your number"))
j=int(input("enter your number"))
if i>j: #making x always greater than y
x=i
y=j
elif i<j:
x=j
y=i
else:
print("invalid")
k=y
cyclelength=[]
while k<=x:
list=[k]
while k!=1:
if(k%2==0):
k=i//2
else:
k=3*k+1
list.append(k)
cyclelength.append(len(list))
k+=1
print(y," ",x," ",max(cyclelength))
I get the following exception:
Traceback (most recent call last):
File "C:/Python32/uva100.py", line 21, in <module>
list.append(k)
MemoryError
You might mean k //= 2 instead of k=i//2
def cyclelength(k):
assert k > 0
count = 1
while k != 1:
k = k // 2 if k % 2 == 0 else 3 * k + 1
count += 1
return count
k_with_max_cyclelength = max(range(y, x+1), key=cyclelength)
Or to get both:
k, max_cyclelength = max(((k, cyclelength(k)) for k in range(y, x+1)),
key=lambda pair: pair[1])
Another problem in this block:
while k!=1:
if(k%2==0):
k //= 2
else:
k=3*k+1
k has the value 1 when you exit.
So you increment k to 2, reenter the while because k < x and reset k to 1
--> infinite loop
you have to define a new variable in you inner while or extract this block in another function
I think you're going for
n=y
cyclelength=[]
while n<=x:
k=n
list=[k]
while k!=1:
if(k%2==0):
k//=2
else:
k=3*k+1
list.append(k)
cyclelength.append(len(list))
n+=1
This looks like you're playing with the Collatz conjecture. Try
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def sequence_length(k):
length = 0
while k > 1:
k = 3*k+1 if k&1 else k//2
length += 1
return length
def max_sequence_length(lo, hi):
best_k, best_length = None, 0
for k in xrange(lo, hi+1):
length = sequence_length(k)
if length > best_length:
best_k, best_length = k, length
return best_k, best_length
def main():
lo = get_int("Enter the start number: ")
hi = get_int("Enter the finish number: ")
lo, hi = min(lo, hi), max(lo, hi)
best_k, best_length = max_sequence_length(lo, hi)
print("In {}..{}, max cycle length is {} at k = {}".format(lo, hi, best_length, best_k))
if __name__=="__main__":
main()
Related
Output screen:
enter the number of elements:3
1
23
3
Traceback (most recent call last):
File "<string>", line 18, in <module>
ValueError: invalid literal for int() with base 10: ''
>
Code :
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ +temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
ele =int(input())
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
I'm trying to solve sum of 1d array question from Leetcode, while I'm appending the list I'm getting the value error. Why am I getting this issue?
Just a SLIGHT modification
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ +temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
ele =int(input("")) # <<============= HERE
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
Your Code works fine.
The problem may come when you put input anything other than numbers. You may have pressed the "enter" button without any number in your error case. That's why the error said '' in the end.
To avoid such an error, you can write a try-block like the below.
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ +temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
while True:
user_input = input('Enter an int element: ')
try:
ele = int(user_input)
except ValueError:
print(f"Invalid integer '{user_input}', try again")
else:
break
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help
i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")
Basically my brain is not working right now can't figure out the best way to resolve this error. builtins.NameError: name 'numIters' is not defined
I know this problem is that numIters is not defined in its scope but don't know the best solution to fix that.
Here is the bulk of my code
import random
alg = int(input("Select the sorting algorithm \n 1 - linear search \n 2 - binary search \nEnter Choice: "))
n = int(input("Choose the size of the list: "))
def main():
createList(n,alg)
print(runTest(values,n,alg))
printResults(alg,n,numIters)
#print(linearSearch(values,2))
#print(binarySearch(values, 2))
def createList(n,alg):
global values
values = []
random.seed(1456)
for j in range(n):
values.append(random.randint(0, 2*n))
while len(values) == n:
if alg == 2:
values.sort()
print(values)
return values
elif alg == 1:
print(values)
return values
def linearSearch(values, target):
numIters = 0
for i in range(len(values)):
numIters = numIters + 1
if values[i] == target:
return numIters
return -1
def binarySearch(values, target):
numIters = 0
start = 0
high = len(values) - 1
while start <= high:
middle = (start + high)//2
if values[middle] == target:
numIters = numIters + 1
return numIters
elif values[middle] > target:
numIters = numIters + 1
high = middle - 1
else:
numIters = numIters + 1
start = middle + 1
return -1
def runTest(values,n,alg):
if alg == 2:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
binarySearch(values, tgt)
return count
elif alg == 1:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
linearSearch(values, tgt)
return count
def printResults(alg, n, numIters):
avgIter = n / numIters
if alg == 2:
algType = Binary
if alg == 1:
algType = Linear
print("Results \n n = %d \n %s = %f.2 " % (n,algtype,avgIter))
main()
Thank you in advance for any help given as I am still trying to learn and understand how python works as a whole.
You need to return numIters so that you can pass it to the next function. It looks like it currently gets returned from binarySearch and linearSearch to runTest, but it gets discarded there; just bubble it up like this (I'm going to add type annotations and comments to help me keep track of what's going on):
from typing import List, Tuple
def runTest(values: List[int], n: int, alg: int) -> Tuple[int, int]:
"""Returns count, numIters"""
numIters = 0 # default value in case n is so small we don't iterate
if alg == 2:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
numIters = binarySearch(values, tgt)
return count, numIters
elif alg == 1:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
numIters = linearSearch(values, tgt)
return count, numIters
raise ValueError("alg needs to be 1 or 2!")
Now in your main() you can do:
def main():
createList(n, alg)
count, numIters = runTest(values, n, alg)
print(count)
printResults(alg, n, numIters)
The question is this :
Write a Python function to find all the Strong numbers in a given list of numbers.
Write another function to find and return the factorial of a number. Use it to solve the problem.
Note: 0!=1
The code I tried so far :
def factorial(number):
sum1=0
temp=number
while(number):
i=1
f=1
r=number%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
number=number//10
return sum1
return temp
def find_strong_numbers(num_list):
for item in num_list:
for number in range(1,item+1):
if(sum1==temp):
print(number)
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
Expected output : [145, 2]
I am facing error which is :
NameError: name 'sum1' is not defined
import math
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
def find_strong_numbers(num_list):
strongNumbersList = []
for item in num_list:
currentNumber = item
digits = []
while currentNumber > 0:
digits.insert(0, currentNumber % 10)
currentNumber = currentNumber // 10
if sum(map(factorial, digits)) == item:
strongNumbersList.append(item)
return strongNumbersList
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
import math
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
def find_strong_numbers(num_list):
strongNumbersList = []
for item in num_list:
currentNumber = item
digits = []
while currentNumber > 0:
digits.insert(0, currentNumber % 10)
currentNumber = currentNumber // 10
if sum(map(factorial, digits)) == item:
if item==0:
break
strongNumbersList.append(item)
return strongNumbersList
num_list=[145,375,100,2,10,40585,0]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
List item
I keep getting a type error for this. I am experimenting with decorative functions. Any help is appreciated
def primer(func):
def primes(n):
print (n)
return None
#primer
def find_prime(n):
while True:
count = 2
if (count == n):
z = ("PRIME")
return z
elif (n % count == 0):
z = n / count
return z
else:
count += 1
continue
prime = find_prime()
prime(10)
def primer(func):
def primes(n):
print(n)
#return None: dont know why this is here, you could do without it
return primes
#The nontype error is occuring because your code is returning none
#so to fix that all you have to do is return the inner function
#primer
def find_prime(n):
while True:
count = 2
if (count == n):
z = ("PRIME")
return z
elif (n % count == 0):
z = n / count
return z
else:
count += 1
continue
prime = find_prime
# if you want to turn a function into a variable you have to make sure it's
# callable, which means no parantheses around it
prime(15) # then you can call it