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)
Related
I am making a python script that lets you entire an imei number then checks if it is valid, I keep getting an error
Traceback (most recent call last):
File "program.py", line 28, in
if isValidEMEI(n):
File "program.py", line 19, in isValidEMEI
d = (int)(n % 10)
TypeError: not all arguments converted during string formatting
the code is
def sumDig( n ):
a = 0
while n > 0:
a = a + n % 10
n = int(n / 10)
return a
def isValidEMEI(n):
s = str(n)
l = len(s)
if l != 15:
return False
d = 0
sum = 0
for i in range(15, 0, -1):
d = (int)(n % 10)
if i % 2 == 0:
d = 2 * d
sum = sum + sumDig(d)
n = n / 10
return (sum % 10 == 0)
n = input("Enter number")
if isValidEMEI(n):
print("Valid IMEI Code")
else:
print("Invalid IMEI Code")
I have not really being sure what to try and do but I have looked up the error and nothing helpful/stuff I know to to interpret is showing up.
I am new to learning python so this will probalbly have a very simple sulution
I will update this with a "shortest replication of this error"
Thank you so much all help is welcome, this is for a challange I set myself so I am very determind to finish it
I have fixed it, replace n = input("enter number") with n = int(input("Enter number"))
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 am trying to implement Quicksort using Python.
This is my code:
import random
def quickSort(lst):
randomIndex = random.randint(0,len(lst)-1)
pivot = lst[randomIndex]
greater = []
less = []
equal = []
if len(lst) > 1:
for num in lst:
if num > pivot:
greater.append(num)
elif num == pivot:
equal.append(num)
else:
less.append(num)
return quickSort(less)+equal+quickSort(greater)
else:
return lst
def main():
lst = [1000000,100000,1000,10000,100,10]
sortedLst = quickSort(lst)
print("Quicksorted List: ", sortedLst)
main()
How come when I run my code, it says that it runs into this error:
ValueError: empty range for randrange() (0,0, 0)
The only problem is that you try to select randomIndex even, when lst is empty, just move your initializations into if condition where you are sure that they are non empty
import random
def quickSort(lst):
if len(lst) > 1:
randomIndex = random.randint(0,len(lst)-1)
pivot = lst[randomIndex]
greater = []
less = []
equal = []
for num in lst:
if num > pivot:
greater.append(num)
elif num == pivot:
equal.append(num)
else:
less.append(num)
return quickSort(less)+equal+quickSort(greater)
else:
return lst
def main():
lst = [1000000,100000,1000,10000,100,10]
sortedLst = quickSort(lst)
print("Quicksorted List: ", sortedLst)
main()
def makeArray(a):
a = []
for i in range(n):
a.append(i)
return a
print makeArray(a)
import random
def shuffleArray(a):
size = len(a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
print shuffleArray(makeArray(a))
if __name__ == '__main__':
a = raw_input("please enter size of array: ")
print ("you entered " + a)
makeArray(a)
shuffleArray(a)
how do I make this piece of code ask for input via terminal and take that input through both of the functions then returning a result? I'm asking the user for input storing that input in a variable printing the result and then shuffling by randominzing.
def makeArray(n):
a = [] #you were using 'a' for the size and the array itself at the same time
for i in range(n):
a.append(i)
return a
import random
def shuffleArray(a):
size = len (a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
if __name__ == '__main__':
n = int(raw_input("please enter size of array: ")) #'n' needs to be an integer because it's the size of the array
print ("you entered " + str(n))
anArray = makeArray(n)
print shuffleArray(anArray)
you can also replace:
def makeArray(n):
a = []
for i in range(n):
a.append(i)
return a
with:
def makeArray(n):
a = list(range(n))
return a
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()