ValueError: invalid literal for int() with base 10: 'x' - python-3.x

when the the last index on string has "x" or "X" (It is represent as 10) so if I have something like "1x", which mean 11 (1 + 10)
def main():
s1 = "013162959x"
partial_sums(s1)
def partial_sums(s1):
lst =[]
sum = 0
for i in range(len(s1)):
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
else:
sum = sum + int(s1[i])
lst.append(sum)
print(lst)
main()
I got an ValueError: invalid literal for int() with base 10: 'x'
the output should be [0, 1, 4, 5, 11, 13, 22, 27, 36, 46]
When the string contain No "X" value it work fine.
def main():
s1 = "0131629592"
partial_sums(s1)
def partial_sums(s1):
lst1 =[]
sum = 0
for i in range(len(s1)):
sum = sum + int(s1[i])
lst1.append(sum)
print(lst1)
main()
How can I fix it?

This statement:
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
still calls int on s1[i] even though s1[i] is "x". You simply want sum += 10.
However, note that or doesn't work the way you're using it. To quote the docs, "The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned." IOW, "a" == "b" or "c" returns "c", not False, and "c" evaluates as True.
Also, since sum is a really useful builtin, it's probably a bad idea to shadow it with a variable of your own with the same name. total is often used instead.

Related

How to search for the index of the number from the last of list to first?

I was checking the documentation to find the index of the number from last to first.
I could use - list.index(number, start, end). In my example, if I omit the start and end I don't get any exception. However, I get an exception when I change the start to the last index and end to the first element index i.e. 0. I am sure I am doing something wrong but I am unable to think about what is going wrong here.
def nonConstructibleChange(coins):
# o(log n) - sorting
coins.sort() # O(log n)
max_amount = sum(coins)
print(max_amount)
# range is [start, end)
if len(coins) == 0:
return 1
for change in range(1, max_amount+1):
if change == 1:
if 1 not in coins:
return 1
else:
max_limit = change - 1
while max_limit not in coins and max_limit != -1:
max_limit -=1
print(coins.index(max_limit, len(coins)-1, 0)) # throws exception
print(coins.index(max_limit)) # this works
if __name__ == '__main__':
coins = [5, 7, 1, 1, 2, 3, 22]
nonConstructibleChange(coins)
You can find the index of the last occurrence of an element by applying index function on the reversed list. In your case this would be:
print(coins[::-1].index(max_limit))
def nonConstructibleChange(coins):
# o(log n) - sorting
coins.sort() # O(log n)
max_amount = sum(coins)
num = None
#print(coins)
#print(max_amount)
# range is [start, end)
if len(coins) == 0:
return 1
for change in range(1, max_amount+1):
if change == 1:
if 1 not in coins:
return 1
else:
max_limit = change
while max_limit not in coins and max_limit != -1:
max_limit -=1
right_index = coins.index(max_limit)
while 1:
try:
# the last index is not included therefore len(coins)
right_index = coins.index(max_limit, right_index +1 , len(coins))
except ValueError:
# print(f'final right_index = {right_index}')
break
print(f'right_index = {right_index}')
print(f'change = {change}')
print(f'max_limit = {max_limit}')
num = change
for idx in reversed(range(right_index + 1)):
if coins[idx] > num:
#print(f'coins[idx] = {coins[idx]} and num = {num}')
continue
#print(f'idx = {idx}')
num = num - coins[idx]
#print(f'num = {num}')
if (num in coins[0:idx-1] or num == 0) and idx != 0:
#print(f'Setting num = {num}')
num = 0
break
if num != 0:
return change
return max_amount + 1
if __name__ == '__main__':
coins = [5, 7, 1, 1, 2, 3, 22]
#coins = [1, 1, 1, 1, 1]
print(nonConstructibleChange(coins))

How can i sum co-prime numbers in a pair

I have this list
a = [1,2,3,4,5,6,7,8,9]
I want to find out that how many co-prime pair elements of the list add up to sum=9
Ex, (1+8) = 9 , (2+7) = 9 , (3+6)=9 , (4+5)=9, (5+4)=9 , (6+3)=9, (7+2)=9 , (8+1)=9
Note that i don't want (3+6) as they are prime numbers. And i also don't want (7+2)=9 as it has already occurred (means 2,7 has been already taken in account)
I tried this But it takes repeated values too.
a = [1,2,3,4,5,6,7,8,9]
count=0
for m in a:
for n in a:
total=m+n
if(total==9):
s=str(m) + '+'+ str(n) + "="
print(s , m+n)
count=count+1
print("Count =" ,count)
The result should have count=3
Your mistake is in the way of doing the loops, so you repeat values.
Try this:
#from math import gcd as bltin_gcd
a = [1,2,3,4,5,6,7,8,9]
count = 0
def __gcd(a, b):
# Everything divides 0
if (a == 0 or b == 0): return 0
# base case
if (a == b): return a
# a is greater
if (a > b):
return __gcd(a - b, b)
return __gcd(a, b - a)
# Only python 3
# def coprime(a, b):
# return bltin_gcd(a, b) == 1
for i in range(0,9):
for j in range(i+1,9):
if __gcd(a[i], a[j]) == 1 and a[i] + a[j] == 9:
count += 1
print str(a[i]) + ' ' + str(a[j])
print 'Count = ' + str(count)
In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime if the only positive integer that divides both of them is 1. Consequently, any prime number that divides one does not divide the other. This is equivalent to their greatest common divisor being 1.
for m in a:
for n in a:
You are not selecting pairs by using this loops, ie. you are picking the first element in both the outer and inner loop during your first iteration.
if(total==9):
You are not checking the condition if the selected pair of numbers are coprime. You are only verifying the sum.
A pythonic solution may be obtained with a one-liner:
from math import gcd
a = [1,2,3,4,5,6,7,8,9]
pairs = [(m,n) for m in a for n in a if n > m and m+n == 9 and gcd(m,n) == 1]
Result :
pairs --> [(1, 8), (2, 7), (4, 5)]
If you are sure to never, never need the pairs but only the number of pairs (as written in the OP), the most efficient solution may be:
count = len([1 for m in a for n in a if n > m and m+n == 9 and gcd(m,n) == 1])
EDIT : I inversed the three conditions in the if statement for improved benefit from lazy boolean evaluation
You can solve this if you have something that calculates your prime factorization in python:
from functools import lru_cache
# cached function results for pime factorization of identical nr
#lru_cache(maxsize=100)
def factors(nr):
# adapted from https://stackoverflow.com/a/43129243/7505395
i = 2
factors = []
while i <= nr:
if (nr % i) == 0:
factors.append(i)
nr = nr / i
else:
i = i + 1
return factors
start_at = 1
end_at = 9
total = 9
r = range(start_at, end_at+1)
# create the tuples we look for, smaller number first - set so no duplicates
tupls = set( (a,b) if a<b else (b,a) for a in r for b in r if a+b == total)
for n in tupls:
a,b = n
f_a = set(factors(a))
f_b = set(factors(b))
# if either set contains the same value, the f_a & f_b will be truthy
# so not coprime - hence skip it
if f_a & f_b:
continue
print(n)
Output:
(2, 7)
(1, 8)
(4, 5)

24 game using Python3

24 is a mental arithmetic game, first played using poker cards. Given four integers, the objective is to produce the number 24 using the standard arithmetic operators +, −, ∗ and /, while consuming all four numbers in the process.
For example, given the numbers { 2, 3, 5, 6 }, one could do . . .
2 * 3 = 6 , 5 * 6 = 30 , 30 - 6 = 24 and so on
Note: The given numbers can be used in any order to produce 24.
Write a program that takes in four integers, and determines whether it is possible to reach 24 from those numbers. You can assume the number 0 will not form part of the input.
I am not sure how to let the function run my 4 inputs
import itertools
ints = input('Enter 4 integers: ').split()
n1=int(ints[0])
n2=int(ints[1])
n3=int(ints[2])
n4=int(ints[4])
def with_brackets(lst, ops_lst):
for op in ops_lst: #calculate when no brackets
expr1 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+lst[2]+op[2]+lst[3]
expr2 = '('+lst[0]+op[0]+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
expr3 = lst[0]+op[0]+'('+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
expr4 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+'('+lst[2]+op[2]+lst[3]+')'
for expr in [expr1, expr2, expr3, expr4]:
try:
t=eval(expr)
except: #except zerodivision error
pass
if abs(t-24) < 0.001:
return expr
return 0
#return 4 numbers to calculate 24
def hasMethod(numbers, ops_lst):
for lst in itertools.permutations(numbers):
lst = list(map(lambda x:str(x), lst))
#without brackets
for op in ops_lst:
expr = lst[0]+op[0]+lst[1]+op[1]+lst[2]+op[2]+lst[3]
if abs(eval(expr)-24) < 0.001:
return expr
#with brackets
expr = with_brackets(lst, ops_lst)
if expr != 0:
return expr
return 0
#method of return 4 numbers to calculate 24,no way return"No Method"
def cal_24(numbers):
ops = ['+','-','*','/']
ops_lst = [[i,j,k] for i in ops for j in ops for k in ops]
expr = hasMethod(numbers, ops_lst)
if expr != 0:
return expr
else:
return 'No method!'
#ways to calculate 24 at all situaions
def main():
numbers_lst = [[i,j,k,l] for i in range(1,14) for j in range(1,14)\
for k in range(1,14) for l in range(1,14)]
for numbers in numbers_lst:
a = list(map(lambda x: str(x), numbers))
methodInfo = "[%s,%s,%s,%s]: %s\n"%(a[0],a[1],a[2],a[3],cal_24(numbers))
print(methodInfo)
main()
Expected results:
Example 1:
Enter 4 integers: 2 3 5 6
Yes! 24 is reachable from { 2, 3, 5, 6 }
Example 2:
Enter 4 integers: 1 1 1 1
Noooo :( 24 is unreachable from { 1, 1, 1, 1 }
Example 3:
Enter 4 integers: hello
Input must consist of 4 integers
This question is very interesting.
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()

how to make the print answer does not repeat the word everytime the answer come out?

I have this program:
a = []
num = input('Enter numbers *Separate by using commas:')
num = num.split(",")
for i in num:
a.append(i)
num = list(map(int,a))
print('~~Output~~')
for x in num:
if x >= 10:
print('Values >= 10 :',x,end = '~')
and it came out like this:
Enter numbers *Separate by using commas:12,1,10,5
~~Output~~
Values >= 10 : 12~Values >= 10 : 10~
>>>
how do I make it so that it print like this:
Enter numbers *Separate by using commas:12,1,10,5
~~Output~~
Values >= 10 : ~12~10~
>>>
thanks.
is it like this:
a = []
num = input('Enter numbers *Separate by using commas:')
for i in num:
if i >= 10:
a.append(i)
print('~' + '~'.join(a) + '~')
it will print:
if i >= 10:
TypeError: '>=' not supported between instances of 'str' and 'int'
>>>
I don't really understand....sorry...is there a simpler one using this for loop?
I assume you meant to print the label before the values? Not part of every value?
print('Values >= 10 :', end ='')
for x in num:
if x >= 10:
print(x,end = '~')
Your second error is that you are iterating over a string... You forgot to split the commas, and map the strings to integers
Add the numbers into a list and then print them.
numbersHigher = []
for x in num:
if x >= 10:
numbersHigher.append(x)
Zach King suggested list comprehension(Google it if you want to know more)
numbersHigher = [x for x in num if x >= 10]
Then you print it once after the loop.
It happens because there might be 2 numbers and you print twice because x is higher than 1- 2 times.
EDIT:
To make the last print like you want you can do:
import string
print('~' + '~'.join(numbersHigher) + '~')

How can I split an integer into its component digits, and place each digit into a list?

This is the latest version of what I've tried so far.
I have two input n and k and anytime i reaches a number with k in it, it needs to print "boomboom"
n_print = list(range(1,n+1))
i = 0
for i in n_print:
if i == k:
print("boom!")
####################### This part
elif i%k == 0 or k in list(str.split(repr(i))):
##################### ^^^^^^^^^^^^^^^^^^^^^^^^^
print("boom-boom!")
elif i != (n+1):
print(i)
else:
break
so if k = 2 and n = 23, it should print "boom-boom!" for 12, 20, 21, 22, etc.
I'm not sure what I'm doing wrong.
Convert to str and check for containment:
str(k) in str(i)
will test if the digits of k appear (consecutively, if more the one digit) in the digits of i.
So k=2 and i=23 will evaluate as true, as will k=23 and i=12345. But k=24 and i=234 won't, because there is no substring of 24 in "234".

Resources