My assignment is to chop apart sequences of numbers with dashes and add each piece together (ex: 1-1-1 = 3, 2-2 = 4). I don't know why my loop terminates after the first run through though. The output right now is
3
456
456
56-234
0
456
Here is the function:
def SSN(str):
total = 0
y = -1
dash = 0
while dash >= 0:
dash = str.find("-")
print(dash)
if dash > -1:
section = str[0:dash]
str = str[dash+1:]
section = int(section)
print(section)
total += section
print(total)
print(str)
else:
total = str
y+=1
print(y)
return total
print(SSN("456-56-234"))
Related
I don't understand why the function is returning 4 while it should return 3. Thank you very much.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += w/2
print(int(count))
From your description of what you said, of wanting to count pairs, then I believe you would want to round down the number being added to count instead of count overall, as 2 halves would end up making 1.
The following does return 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(count)
In Python, a single slash ”/“ does a regular divide that returns with decimals. A double slash “//“ returns a whole number rounded down. When you call int() on the number, it rounds it down to nearest whole number.
In your code, you get:
2+1.5+0.5+0.5=4.5
After calling int on 4.5, it becomes 4.
You are adding floats in the for loop, just change that to ints and it will add up to 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(int(count))
If i have a number 101, i want to multiply all the digits of the number (1*0*1) but this result will become Zero. Instead how to split the number into 10 and 1 and multiply(10*1).
Similar examples,
3003033 -> 300*30*3*3 or
2020049 -> 20*200*4*9
You could use a negative look behind to check its not the start of the list and a positive look ahead for nums that are not 0 as your split point.
REGEX: Essentially this says split where the next num is not a 0 and it not the start of the line
/
(?<!^)(?=[^0])
/
gm
Negative Lookbehind (?<!^)
Assert that the Regex below does not match
^ asserts position at start of a line
Positive Lookahead (?=[^0])
Assert that the Regex below matches
Match a single character not present in the list below [^0]
0 matches the character 0 literally (case sensitive)
CODE
import re
from functools import reduce
def sum_split_nums(num):
nums = re.split(r'(?<!^)(?=[^0])', str(num))
total = reduce((lambda x, y: int(x) * int(y)), nums)
return " * ".join(nums), total
nums = [3003033, 2020049, 101, 4040]
for num in nums:
expression, total = sum_split_nums(num)
print(f"{expression} = {total}")
OUTPUT
300 * 30 * 3 * 3 = 81000
20 * 200 * 4 * 9 = 144000
10 * 1 = 10
40 * 40 = 1600
Let a and b be two integer numbers. Let c be a new number made by putting n zeros in the right side of b. Then multiplying a and c is equal to multiplying a and b and 10^n.
Now you can simplify what you want to do to the following: Multiply digits of your number to each other with the agreement that instead of 0, you will put 10. So actually you don't need to split your number.
Here I defined two functions. In both of them the idea is to convert your number to a string, run a for-loop on its digits and by an if condition in the case
1) multiply the previous result to the new digit if it is not 0, otherwise multiply to 10.
def multio1(x):
s = str(x)
ans = 1
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
ans *= 10
return(ans)
2) multiply the previous result to the new digit if it is not 0, otherwise add one unit to the number of zeros. Then at the end put as many as number of zeros, zeros at the right side of your final result.
def multio2(x):
s = str(x)
ans = 1
number_of_zeros = 0
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
number_of_zeros += 1
if number_of_zeros != 0:
ans = str(ans)
for i in range(number_of_zeros):
ans += '0'
ans = int(ans)
return(ans)
Now the multio1(x) and multio2(x) for x=101,3003033,2020049, both gives equal results shown in below.
10,81000,144000
That's kind of odd, but this code will work:
a = '3003033'
num = ''
last_itr = 0
tot=1
for i in range(len(a)-1):
if a[i]=='0' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[last_itr:i+1])
last_itr=i+1
elif a[i]>'0' and a[i]<='9' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[i])
last_itr=i+1
tot*=int(a[last_itr:len(a)])
print(tot)
Just put your number at a
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()
I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.
This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.
Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)
while True:
try:
number = input('Enter') #Asks user to input 7 digit number
if len(str(number)) != 7:
print('Incorrect')
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
for index, digit in enumerate(list(str(number))):
total = total + int(digit)*multiplier[index%2]
times = times+str(int(digit)*multiplier[index%2])+', '
mof10 = total + (10 - total%10)
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print (times[:-1])
print(total)
print(mof10)
print(checkdigit)
print(final)
break
except ValueError:
print('Not a number')
My task is to 'Calculate the GTIN-8 product code from a seven digit number'
I need a line by line explanation of the code above, please.
Some info on enumerate by typing help(enumerate)
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list:
The % operator returns the remainder of x / y eg
10 / 5 = 2 r 0 | 10 % 5 = 0
7 / 2 = 3 r 1 | 7 % 2 = 1
Here is the code explained with comments
while True: # Loop will continue until break is called
try:
number = input('Enter') #Asks user to input 7 digit number
# Checks if the length of the input
# If not 7 characters long
# Will then ask for input again due to while loop
if len(str(number)) != 7:
print('Incorrect')
# If is 7 chacters long
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
# example input for number '1234567'
# list(str(number))
# '1234567' -> ['1', '2', '3', '4', '5', '6', '7']
for index, digit in enumerate(list(str(number))):
# index%2 returns either 0 or 1
# this is used to get 3 or 1 from multiplier
# depending on if the index is odd or even
# for first index and digit from example
# index = 0, digit = '1'
# total = total + 1 * 3
total = total + int(digit)*multiplier[index%2]
# adds the multiplier value from digit * multiplier[index%2]
# to times as a string. First value is
# times = times + str(1 * 3) which is 3
times = times+str(int(digit)*multiplier[index%2])+', '
# essentially rounds up to nearest 10
mof10 = total + (10 - total%10)
# gets the number it was rounded up by
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print(times[:-1]) # slice the string to return everything except the last value
print(total)
print(mof10)
print(checkdigit)
print(final)
break # exit while loop
# If the convertion from string to int returns an error
# meaning a non-number was entered into input eg. !##$
# print the following, while loop will continue and prompt again
except ValueError:
print('Not a number')