multiplication function that multiplies given number with 1 to 10 - python

I am trying to write a function that will multiplicate the given number with 1 to 10 and print out the result.
Here is my code:
number = input('Enter a number please: ')
def multiplication(number):
for i in range(1, 10)
return print(number =* i)
multiplication(3)
and here is the error:
SyntaxError: invalid syntax erdoganpc#MacBook-Air-Denis pyShit %
/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
/Users/erdoganpc/Documents/dev/pyShit/main.py File
"/Users/erdoganpc/Documents/dev/pyShit/main.py", line 3
for i in range(1, 10)
can't understand how to solve this problem, please help me :(

Try this
def multiplication(number):
result = []
for i in range(1, 11):
result.append(str(i) + ' * ' + str(number) + ' = ' + str(number * i))
return result
Output:
['1 * 4 = 4', '2 * 4 = 8', '3 * 4 = 12', '4 * 4 = 16', '5 * 4 = 20', '6 * 4 = 24', '7 * 4 = 28', '8 * 4 = 32', '9 * 4 = 36', '10 * 4 = 40']

There is an error in your script, you wrote =* instead of *=, so the correct way is:
number = input('Enter a number please: ')
def multiplication(number):
for i in range(1, 10):
number *= i
return number
print(multiplication(3))

number = int(input('Enter a number please: '))
def multiplication(number):
for i in range(1, 10):
number *= i
print(number)
multiplication(number)
Enter a number please: 3
3
6
18
72
360
2160
15120
120960
1088640

Related

How to display a list of strings dynamically in python

I have a list of strings in python which are in form of an arithmetic problem. So:
p_list = ['32 + 5', '4 - 1', '345 + 2390']
I would love each of the list to be arranged in this manner
32 4 345
+ 5 - 1 + 2390
---- --- ------
So essentially i want the numbers to be right aligned and four spaces between each expression.
I tried doing something like this
final = f"{final} {problem_list[key]['operand1']}\n{problem_list[key]['operator']} {problem_list[key]['operand2']}"
but i got this instead
213
+ 4 3234
+ 4 3
- 3 5
+ 7
thanks in advance
If your objective is to print out the equations, this function arranges them in your desired way:
def arithmetic_format(eq_list, sep = 4):
top = mid = bot = ""
sep = " " * sep
for eq in eq_list:
chars = eq.split()
width = len(max(chars, key=len)) + 2
top += chars[0].rjust(width) + sep
mid += chars[1] + chars[2].rjust(width - 1) + sep
bot += "-" * width + sep
return f"{top}\n{mid}\n{bot}"
p_list = ['32 + 5', '4 - 1', '345 + 2390']
answer = arithmetic_format(p_list)
print(answer)
Out:
32 4 345
+ 5 - 1 + 2390
---- --- ------
There are many ways to achieve this. Here's one:
plist = ['32 + 5', '4 - 1', '345 + 2390']
spaces = ' ' * 4
def parts(plist):
return [e.split() for e in plist]
def widths(plist):
return [max(map(len, e))+2 for e in parts(plist)]
def get_tokens(plist, idx):
if idx == 0:
return [f'{e:>{w}}' for (e, _, _), w in zip(parts(plist), widths(plist))]
if idx == 1:
return [f'{s}{n:>{w-1}}' for (_, s, n), w in zip(parts(plist), widths(plist))]
return ['-' * w for w in widths(plist)]
for idx in range(3):
print(spaces.join(get_tokens(plist, idx)))
Output:
32 4 345
+ 5 - 1 + 2390
---- --- ------
Try this:
p_list = ['32 + 5', '4 - 1', '345 + 2390']
up= []
down=[]
for op in p_list:
new = op.split(' ')
up.append(new[0] + ' '*4)
if new[1] == '-':
down.append(str(0 - int(new[-1])) + ' '*4)
else:
down.append('+' + new[-1] + ' '*3)
for index,value in enumerate(up):
print(value, end=' ')
print('')
for index,value in enumerate(down):
print(value, end=' ')
# 32 4 345
# +5 -1 +2390

How can I make this a correct test cases list?

I am doing this programming problem to run without entering numbers every time. I want to make it run with the answer that I have entered in the testCase.
https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=945
class TestCase:
def __init__(self,input,output):
self.input = input
self.output = output
testCases = []
t1 = TestCase((3, 3, (0, 1), (1, 2), (2, 0), 3), "NOT BICOLORABLE.")
'''t2 = TestCase(('2', '0 1','1 2', '9'), 'BICOLORABLE.')
t3 = TestCase(('9', '8', '0 1', '0 2', '0 3', '0 4', '0 5', '0 6', '0 7', '0 8', '0'), 'BICOLORABLE.')'''
testCases.append(t1)
#testCases.append(t2)
#testCases.append(t3)
and here is the code (if there is any mistake please correct me.)
def solve(input):
while True:
try:
num_v = int(input())
num_e = int(input())
e = {i: [] for i in range(num_v)}
for i in range(num_e):
line = input().split()
src, dst = int(line[0]), int(line[1])
e[src].append(dst)
e[dst].append(src)
seen = {} # v_id: int: is_0_colored: boolean
bicolorable = True
output = bicolorable
v_id = 0
v_processor = [(0, True)]
while v_id < len(v_processor):
p = v_processor[v_id]
seen[p[0]] = p[1]
for dst in e[p[0]]:
if dst in seen:
if p[1] == seen[dst]:
bicolorable = False
break
else:
v_processor.append((dst, not p[1]))
v_id += 1
if not bicolorable:
break
if bicolorable:
print("BICOLORABLE.")
else:
print("NOT BICOLORABLE.")
except(EOFError):
break
return output
And this is the test script to run the code.
# Test script
for i in range(len(testCases)):
print(testCases[i].input)
print("*** Testing program with test case no.", i)
%timeit global output; output=solve(testCases[i].input)
if output==testCases[i].output:
print("Okay")
else:
print("Incorrect!\nExpected output:", testCases[i].output)
print("Actual output:", output)
My problem is that when I run it shows TypeError: 'tuple' object is not callable. I don't understand what I did wrong and I have tried many time to change the way of how the input numbers is in the testCase but still not work.
(3, 3, (0, 1), (1, 2), (2, 0), 3)
*** Testing program with test case no. 0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-f3a3fe984f4b> in <module>()
4 print(testCases[i].input)
5 print("*** Testing program with test case no.", i)
----> 6 get_ipython().magic('timeit global output; output=solve(testCases[i].input)')
7
8 if output==testCases[i].output:
5 frames
<decorator-gen-52> in timeit(self, line, cell)
<magic-timeit> in inner(_it, _timer)
<ipython-input-35-20bd60aca820> in solve(input)
5 while True:
6 try:
----> 7 num_v = int(input())
8 num_e = int(input())
9
TypeError: 'tuple' object is not callable
enter image description here
Thank you so much in advance.

Find Numbers That Multiply To Make List Of Numbers

I have a voting system for something where people rate things from one to ten. I am able to get the number of total votes, but not their distribution. I can, however, access the totals for each score (but not what score they are for).
For example, say two people voted 2 and three 4 then I would get [4, 12]. Humanly, it is possibly to work out what the votes were, however as there is a lot of data, I need an algorithm that is able to do it programmatically. To solve this humanly, I would know that there were 5 votes and this I would know that it was either one four and four thees or two twos and three fours. Because this isn't the best example, we can't tell which one it would be and so it this situation, the algorithm should spit out all of the solutions. With the real data, it is very rare that something like this occurs.
The input is in the form of an int representing the total number of votes cast, and a list of all of the vote subtotals. The output should be an array containing pars (x, y) where there are x number of y votes cast. If more than one solution is present, the algorithm should return all of them in an array.
EDIT:
Here's some real data (17 people voted):
Dunkel - 60 + 18 + 8 + 18 + 10 + 4 + 3 + 1 = 122
Satomi - 20 + 14 + 24 + 12 + 3 + 4 + 3 = 80
Bottersnike - 16 + 28 + 5 + 8 + 6 + 4 + 4 = 71
Woon - 40 + 36 + 8 + 21 + 5 + 16 = 126
Limelier - 10 + 18 + 6 + 15 + 8 + 4 + 6 = 67
RandomGamer - 16 + 6 + 10 + 4 + 6 + 4 + 7 = 53
Pillar - 10 + 8 + 21 + 6 + 15 + 4 + 9 + 4 + 2 = 79
EdgedPixel - 8 + 28 + 12 + 4 + 18 + 2 + 2 = 74
Lock - 20 + 24 + 7 + 18 + 10 + 8 + 6 + 2 = 95
Huri - 10 + 8 + 7 + 6 + 15 + 20 + 3 + 2 + 3 = 74
Sean - 18 + 32 + 8 + 5 + 4 + 9 + 2 = 78
And the answers (sorry about the different order):
Woon - 4*10 + 4*9 + 1*8 + 3*7 + 0*6 + 1*5 + 4*4 + 0*3 + 0*2 + 0*1 = 126
Dunkel - 6*10 + 2*9 + 1*8 + 0*7 + 3*6 + 2*5 + 1*4 + 1*3 + 0*2 + 1*1 = 122
Lock - 2*10 + 0*9 + 3*8 + 1*7 + 3*6 + 2*5 + 2*4 + 2*3 + 0*2 + 2*1 = 95
Satomi - 2*10 + 0*9 + 3*8 + 4*7 + 2*6 + 0*5 + 0*4 + 1*3 + 2*2 + 3*1 = 80
Pillar - 1*10 + 0*9 + 1*8 + 3*7 + 1*6 + 3*5 + 1*4 + 3*3 + 2*2 + 2*1 = 79
Sean - 0*10 + 0*9 + 4*8 + 0*7 + 3*6 + 1*5 + 2*4 + 3*3 + 2*2 + 2*1 = 78
EdgedPixel - 0*10 + 0*9 + 1*8 + 4*7 + 2*6 + 0*5 + 1*4 + 6*3 + 1*2 + 2*1 = 74
Huri - 1*10 + 0*9 + 1*8 + 1*7 + 1*6 + 3*5 + 5*4 + 1*3 + 1*2 + 3*1 = 74
Bottersnike - 0*10 + 0*9 + 2*8 + 4*7 + 0*6 + 1*5 + 2*4 + 2*3 + 2*2 + 4*1 = 71
Limelier - 1*10 + 2*9 + 0*8 + 0*7 + 1*6 + 3*5 + 2*4 + 0*3 + 2*2 + 6*1 = 67
RandomGamer - 0*10 + 0*9 + 2*8 + 0*7 + 1*6 + 2*5 + 1*4 + 2*3 + 2*2 + 7*1 = 53
I need an algorithm that is able to do it programmatically
I'd begin by factoring your totals.
What is the most efficient way of finding all the factors of a number in Python?
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
This will return all of the factors, very quickly, of a number n.
that would get you well on your way; obviously a listed total that doesn't have 5 for a factor did not come from a group that rated 5's
step 1) factor each number in your list of totals
step 2) create dictionary with all possible ratings as the keys; ie keys 1-10; each with empty lists as values.
step 3) check if each list of factors has a factor which matches each rating key; if so append the total it represents to the values list of possibilities for that respective key
from random import randint
from random import shuffle
VOTES = 200
RATINGS = 10
# Generate Test Data
ratings = {}
for i in range(1,(RATINGS+1)):
ratings[i] = []
for i in range(VOTES):
rate = randint(1,RATINGS)
ratings[rate].append(rate)
subtotals = []
for key, values in ratings.iteritems():
subtotals.append(sum(values))
subtotals = [i for i in subtotals if i != 0]
subtotals.sort()
hidden_subtotals = {}
for key, values in ratings.iteritems():
hidden_subtotals[key] = sum(values)
print '==================================='
print 'Generate Hidden Test Data'
print 'unknown actual votes: %s' % ratings
print 'unknown actual subtotals: %s' % hidden_subtotals
print '==================================='
print 'Present Problem'
print 'known vote total: %s' % VOTES
print 'known subtotals: %s' % subtotals
print 'known total: %s' % sum(subtotals)
print 'number of ratings used: %s of %s' % (len(subtotals), RATINGS)
print '==================================='
def factors(n):
f = list(set(reduce(list.__add__, ([i, n//i] for i in range(
1, int(n**0.5) + 1) if n % i == 0))))
f.sort()
return f
# Factor Each
subtotal_factors = {}
for i in subtotals:
subtotal_factors[i]=(factors(i))
print 'process 1: %s' % subtotal_factors
# Remove Factors greater than highest rating
possible_ratings = {}
for i in subtotal_factors:
possible_ratings[i] = [
z for z in subtotal_factors[i] if z<=RATINGS]
print 'process 2: %s' % possible_ratings
# Remove Factors if not enough votes for that possibility; too small relative to subtotal
for i in possible_ratings:
possible_ratings[i] = [
z for z in possible_ratings[i] if i/z < VOTES]
print 'process 3: %s' % possible_ratings
step 4) then you'll have a problem where 2's will fit in 4's, 6's, 8's, 10's; 4's will fit in 8's, and 3's will fit in 6's and 9's. You'll have to apply some logic to clean up the results.
I have now solved my problem. I used litepresence's code as a base, and then implemented what they described as step four. For the future, this is the code I used:
from random import randint
from random import shuffle
import itertools
NUM_RATINGS = 10
RATING = [10, 10, 10, 10, 10, 10, 9, 9, 8, 6, 6, 6, 5, 5, 4, 3, 1]
VOTES = len(RATING)
ratings = {}
for i in range(1, (NUM_RATINGS + 1)):
ratings[i] = []
for i in RATING:
ratings[i].append(i)
subtotals = []
for key, values in ratings.iteritems():
subtotals.append(sum(values))
subtotals = [i for i in subtotals if i != 0]
subtotals.sort()
hidden_subtotals = {}
for key, values in ratings.iteritems():
hidden_subtotals[key] = sum(values)
print '==================================='
print 'Hidden Test Data:'
print 'unknown actual votes: %s' % ratings
print 'unknown actual subtotals: %s' % hidden_subtotals
print '==================================='
print 'Present Problem:'
print 'known vote total: %s' % VOTES
print 'known subtotals: %s' % subtotals
print 'known total: %s' % sum(subtotals)
print 'number of ratings used: %s of %s' % (len(subtotals), NUM_RATINGS)
print '==================================='
def factors(n):
f = list(set(reduce(list.__add__, ([i, n//i] for i in range(
1, int(n**0.5) + 1) if n % i == 0))))
f.sort()
return f
# Factor Each
subtotal_factors = {}
for i in subtotals:
subtotal_factors[i]=(factors(i))
print 'process 1: %s' % subtotal_factors
# Remove Factors greater than highest rating
possible_ratings = {}
for i in subtotal_factors:
possible_ratings[i] = [
z for z in subtotal_factors[i] if z<=NUM_RATINGS]
print 'process 2: %s' % possible_ratings
# Remove Factors if not enough votes for that possibility; too small relative to subtotal
for i in possible_ratings:
possible_ratings[i] = [
z for z in possible_ratings[i] if i/z < VOTES]
print 'process 3: %s' % possible_ratings
end_res = {}
other = {} # (count, [poss])
for i in possible_ratings.items():
if len(i[1]) == 1:
end_res[i[0]] = (i[1][0], i[1][0])
else:
other[i[0]] = (subtotals.count(i[0]), i[1])
combs = {}
for i in other.items():
combs[i[0]] = (i[1][0], []) # (count, [data])
for a in i[1][1]:
for b in i[1][1]:
if (a, b) not in combs[i[0]]:
if a * b == i[0]:
combs[i[0]][1].append((a, b))
lists = []
for i in combs.items():
for j in range(i[1][0]):
lists.append([])
for n in i[1][1]:
lists[-1].append((n[0], n[1], i[0]))
toprocess = itertools.product(*lists)
working = []
for test in toprocess:
works = True
seen = []
tot = 0
for i in test:
if i[1] in seen:
works = False
break
tot += i[0]
if tot > VOTES:
works = False
break
seen.append(i[1])
if not works:
continue
else:
working.append(test)
formattedWs = []
for w in working:
w = list(w)
notseen = [i + 1 for i in range(NUM_RATINGS)]
for i in w:
notseen.remove(i[1])
for i in notseen:
w.append((0, i))
t = ""
def f(x, y):
return y[1] - x[1]
w.sort(cmp=f)
for i in w:
t += "%d*%d + " % (i[0], i[1])
t = t[:-3]
formattedWs.append(t)
seen = []
for w in list(formattedWs):
if w in seen:
formattedWs.remove(w)
else:
seen.append(w)
print "==================================="
for n, w in enumerate(formattedWs):
print "Solution #%d: %s" % (n + 1, w)

how to calculate 24?

I wrote a python script trying to solve the 'calculate 24' problem, which originated from a game, drawing 4 cards from a deck of cards and try to get the value 24 using +,-, *, and /.
The code is working, only that it have many duplications, for example, I input 2, 3, 4, 5 to get the value of 24, it will find and print that 2*(3 + 4 + 5) is 24, but it will also print 2*(5 + 4 + 3), 2*(5 + 3 + 4), etc., while it will find 4*(3 + 5 - 2), it will also print 4*(5 + 3 - 2). Could anyone please give me some hints on how to remove duplicated answers?
The code is as follows:
def calc(oprands, result) :
ret=[]
if len(oprands)==1 :
if oprands[0]!=result :
return ret
else :
ret.append(str(oprands[0]))
return ret
for idx, x in enumerate(oprands) :
if x in oprands[0:idx] :
continue
remaining=oprands[0:idx]+oprands[idx+1:]
temp = calc(remaining, result-x) # try addition
for s in temp :
ret.append(str(x) + ' + ' + s)
if(result%x == 0) : # try multiplication
temp = calc(remaining, result/x)
for s in temp :
ret.append(str(x) + ' * (' + s + ')')
temp = calc(remaining, result+x) # try subtraction
for s in temp :
ret.append(s + ' - ' + str(x))
temp = calc(remaining, x-result)
for s in temp :
ret.append(str(x) + ' - (' + s + ')')
temp = calc(remaining, result*x) # try division
for s in temp :
ret.append('(' + s + ') / ' + str(x))
if result!=0 and x%result==0 and x/result!=0 :
temp = calc(remaining, x/result)
for s in temp :
ret.append(str(x) + ' / ' + '(' +s +')')
return ret
if __name__ == '__main__' :
nums = raw_input("Please input numbers seperated by space: ")
rslt = int(raw_input("Please input result: "))
oprds = map(int, nums.split(' '))
rr = calc(oprds, rslt)
for s in rr :
print s
print 'calculate {0} from {1}, there are altogether {2} solutions.'.format(rslt, oprds, len(rr))
Calculate 24 is an interesting and challenging game. As other users pointed out in the comments, it's difficult to create a solution that doesn't present any flaw.
You could study the Rosetta Code (spoiler alert) implementation and compare it to your solution.

Python value problem: SyntaxError: invalid syntax

I'm learning, so go easy on me.
What am I doing wrong here:
#!/usr/bin/python3.1
import urllib.request
page = urllib.request.urlopen ("http://au.finance.yahoo.com/q?s=AUDUSD=X")
text = page.read().decode("utf8")
where = text.find('Last Trade:</th><td class="yfnc_tabledata1"><big><b><span id="yfs_l10_audusd=x">')
start_of_us_price = where + 80
end_of_us_price = start_of_us_price + 6
us_price = text[start_of_us_price:end_of_us_price]
where = text.find('Trade Time:</th><td class="yfnc_tabledata1"><span id="yfs_t10_audusd=x">')
start_of_trade_time = where + 72
end_of_trade_time = start_of_trade_time + 11
trade_time = text[start_of_trade_time:end_of_trade_time]
print ('The price is $ 'us_price' as of 'trade_time'")
The last line should be:
print ('The price is $ ', us_price, ' as of ', trade_time)
Consider this to understand it better:
>>> x = 3
>>> print('The value of x is:', 3, 'Yes!')
The value of x is: 3 Yes!

Categories

Resources