Need to sum the total of Multiplication without using loops - python-3.x

num = 5
for i in range(1,num):
for j in range(1,num):
print(i * j, end="\t")
print()
I have this multiplication table and i need to sum all of the numbers given without using loops.
can anyone advise?

Mathematics makes any task easier.
Formula is (n(n+1)/2)^2. Just put n = num-1. num-1 because your for loop generates table upto number 4.
Code:
>>> num = 5
>>> sum = ((num*(num-1))/2)**2
>>> print(sum)
100.0

I think you want to sum all resulting multiplication then add few lines in your code.
num = 5
multi_list = []
for i in range(1,num):
for j in range(1,num):
multi_list.append(i*j)
print(sum(multi_list))
#100

Related

I don't know why the correct answer isn't coming up

I'm novice programmer.
I want the smallest of the input values ​​to be output, but I don't know what's wrong.
Input example :
10
10 4 2 3 6 6 7 9 8 5
Output example :
2
n = int(input())
a = input().split()
min=a[0]
for i in range(n) :
if a[i] < min :
min = a[i]
print(min)
what is the problem? please help me
Your code should work (and it does for me).
Nevertheless, min is a reserved Python word. Taking that into consideration, I also recommend the following changes for it to be more idiomatic:
a = input().split()
min_num = a[0]
for element in a:
if element < min :
min = element
print(min)
Variables can be either number or strings. For example "2" is different from 2.
The function split returns an array of strings. You would need to convert each to a number if you want to do number comparison, like:
n = int(input())
a = input().split()
min=int(a[0])
for i in range(n) :
if int(a[i]) < min :
min = int(a[i])
print(min)
Note: you already did that for n (first line in original code), but you did not do the same when you access a.
So, min is actually a python built-in, which would be very useful in this scenario. Also, you are not making the input values in a into integers, so we can do that too:
n = int(input())
a = list(map(int, input().split()))
print(min(a))
We use map to turn all the values from the split list into integers, then turn the map object back into a list. Then, using min, we can find the smallest number very easily, without a for loop.
I think you should convert each element to integers before comparing them.
a = [int(i) for i in input().split()]
Your code should work, but it will compare strings against strings instead of integers against integers.

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

Counting pairs of numbers that adds up to a specific value in Python

i want to count how many pairs of numbers in a list can add to a specific number, this is my code in python but the output is not what it should be
list = [1,2,3,4]
x=3
count = 0
for i in range(len(list)):
for j in range(len(list)):
if i + j == x:
count+=1
print(count)
You could simpilify your code with functions from the built-in itertools module, depending on how you would like to iterate through the list, i.e. combinations, combinations with replacements, or products.
import itertools as itt
in_list = [1,2,3,4]
tgt_num = 3
count = 0
for a,b in itt.combinations(in_list, 2): # returns 1
# for a,b in itt.combinations_with_replacement(in_list, 2): # returns 1
# for a,b in itt.product(in_list, in_list): # returns 2
if a + b == tgt_num:
count += 1
print(count)
Your code has some issues:
One is that it never directly references the items of the list. Because of this, it will only work assuming that the numbers in the list are in ascending order, each is one apart, and that it starts at 1.
Another is that it iterates through the pairs of numbers too many times.
Finally, there are some indentation issues, but I'm guessing those were just lost in the copy-paste. I tried to re-indent it, but when I ran it I got "4", when it should be "1".
Here's a version that incorporates indexing the list, which should resolve the above issues.
list = [1,2,3,4]
x = 3
count = 0
for i in range(0,len(list)):
pair1 = list[i]
pair2 = list[i+1:]
for j in range(0,len(pair2)):
if pair1 + pair2[j] == x:
count += 1
print(count)

Interest calculator on Python

I know that this has been asked already, but I'm having trouble with how I should implement this so I'm asking here.
My python code so far is:
def calculate():
p = 10000 # dollars
n = 12 # months
r = 8 # interest %
t = float(raw_input("Type the number of year that the money will be compounded for:"))
b = p * r
a = b ** t
print(a)
calculate()
Math formula
Like John Coleman mentioned in the comments you didn't implement the formula at all.
In your code you just multiplied p with r and b to the power of t.
The right formula looks like this: p*(1+(r/n))**(n*t).
I would recommend you to read an article related to python basic operators you can find one on Python Course.
def calculate():
p = 10000
n = 12
r = .08
t = float(input("Type the number of year that the money will be compounded for:"))
formula = p*(1+(r/n))**(n*t)
return formula
print (calculate())
So you need to return a value since you are writing a function. I would say input all your values into the function directly like so:
def calculate(P, r, n , t):
exponent = n*t
parends = 1 + (r/n)
val = parends ** exponent
ans = P * val
return ans
print(calculate(10000, .08, 12, 1))
I would check out other resources to learn how to use functions. Codeacademy is a good one.
Here is the function just not broken into pieces:
def shorter(P, r, n, t):
return P*(1+(r/n))**(n*t)
print(shorter(10000, .08, 12, 1))

Convert list of integers to a single integer : ValueError

I am trying to convert a list of integers in Python into a single integer say for example [1,2,3,4] to 1234(integer). In my function, I am using following piece of code:
L = [1,2,3,4]
b = int(''.join(map(str, L)))
return b
The compiler throws a ValueError. Why so? How to rectify this issue?
You can do this like this also if that cause problems:
L = [1,2,3,4]
maxR = len(L) -1
res = 0
for n in L:
res += n * 10 ** maxR
maxR -= 1
print(res)
1234
another solution would be
L = [1,2,3,4]
digitsCounter = 1
def digits(num):
global digitsCounter
num *= digitsCounter
digitsCounter *= 10
return num
sum(map(digits, L[::-1]))
the digits() is a non pure function that takes a number and places it on place value depending on the iteration calling digits on each iteration
1. digits(4) = 4 1st iteration
2. digits(4) = 40 2nd iteration
3. digits(4) = 400 3rd iteration
when we sum up the array returned by map from the inverted list L[::-1] we get 1234 since every digit in the array is hoisted to it place value
if we choose not no invert L array to L[::-1] then we would need our digits function to do more to figure out the place value of each number in the list so we use this to take adv of language features

Resources