How do I simplify these nested for loops? - python-3.x

I was given this riddle :
My first idea was to solve it using python. (Later I realized algebra would have been much easier).
Here was my initial code:
a = 0
b = 0
c = 0
d = 0
for a in range(100):
for b in range(100):
for c in range(100):
for d in range(100):
if float(a + b)/4 == 8.0:
if float(a + c)/4 == 13.0:
if float(c - d)/4 == 6.0:
if float(b + d)/4 == 8.0:
print(float(a + b)/4, end=" ")
print(float(a + c)/4, end=" ")
print(float(c + -d)/4, end=" ")
print(float(b + d)/4, end=" and values are:")
print(a/4, end=" ")
print(b/4, end=" ")
print(c/4, end=" ")
print(d/4)
It worked, but obviously this is not very readable.
Looking on stack overflow leads to the solution being recursive functions, however I do not know how exactly to apply this because there are four different mathematical calculations.
For example this is what I tried at first:
val = [0, 0, 0, 0]
def recursive_solution(section):
for val[section] in range(100):
for val[section+1] in range(100):
if section == 0:
if float(val[section])/4 + float(val[section + 1])/4 == 8:
recursive_solution(1)
recursive_solution(0)
But this obviously does not work, as the second index is added to the fourth index, and one of the operations is a subtraction, and you can't add the fourth index to the fifth one because the fifth one doesn't exist.

Here's what I would do from your code: use a cartesian product and and statements:
from collections import product
for a, b, c, d in product(*([range(100)] * 4))
if (
float(a + b) / 4 == 8.0
and float(a + c) / 4 == 13.0
and float(c - d) / 4 == 6.0
and float(b + d) / 4 == 8.0
):
print(float(a + b) / 4, end=" ")
print(float(a + c) / 4, end=" ")
print(float(c + -d) / 4, end=" ")
print(float(b + d) / 4, end=" and values are:")
print(a / 4, end=" ")
print(b / 4, end=" ")
print(c / 4, end=" ")
print(d / 4)

Related

fibonacci diamond shape pattern in python

def fib(f, N):
f[1] = 0
f[2] = 1
for i in range(3, N + 1):
f[i] = f[i - 1] + f[i - 2]
def fiboTriangle(n):
N = n * (n + 1) // 2
f = [0]*(N + 1)
fib(f, N)
fiboNum = 1
for i in range(n):
for j in range(n-i):
print(end=" ")
for j in range(i):
print(f[fiboNum], end=" ")
fiboNum+=1
print()
for i in range(n,0,-1):
for j in range(n-i):
print(end=" ")
for j in range(i):
print(f[fiboNum], end=" ")
fiboNum+=1
print()
n = 3
fiboTriangle(n)
this is my code i get this output:
0
1 1
2 3 5
Traceback (most recent call last):
File "/home/ali/Python/emipro.py", line 38, in
fiboTriangle(n)
File "/home/ali/Python/emipro.py", line 34, in fiboTriangle
print(f[fiboNum], end=" ")
IndexError: list index out of range
but i want
diamond shape pattern in output
After receiving your comment I went back to reviewing the type of numbers you were attempting to create in a diamond format. I got a diamond with the numeric sequence you noted by changing:
N = n * (n + 1) // 2
to:
N = n * (n + 1)
Here is the full code.
def fib(f, N):
f[1] = 0
f[2] = 1
for i in range(3, N):
f[i] = f[i - 1] + f[i - 2]
def fiboTriangle(n):
N = n * (n + 1) # Changed this equation
f = [0]*(N + 1)
fib(f, N)
fiboNum = 1
for i in range(n):
for j in range(n-i):
print(end=" ")
for j in range(i):
print(f[fiboNum], end=" ")
fiboNum+=1
print()
for i in range(n,0,-1):
for j in range(n-i):
print(end=" ")
for j in range(i):
print(f[fiboNum], end=" ")
fiboNum+=1
print()
n = 3
fiboTriangle(n)
That produced the following diamond.
craig#Una:~/Python_Programs/Fibonacci$ python3 Fibonacci.py
0
1 1
2 3 5
8 13
21
Give that a try.

Python numbers triangle

I am trying to produce a balanced triangle but I got halfway there. I want the result in this format
1
12
123
1234
12345
1234
123
12
1
Here Is the code I have so far:
def numpat(n):
num = 1
for i in range(0, n):
num = 1
for j in range(0, i+1):
print(num, end=" ")
num = num + 1
print("\r")
n = 7
numpat(n)
First thing, try to use code tags in the questions because otherwise the spacing will not be clear.
Anyway you should conver num to a string in order to add digits to the end.
Try something like:
def numpat(n):
num = ""
for j in range(1, n+1):
num += str(j)
print(num, end=" ")
print("\r")
for j in range(len(num)):
num = num[0:-1]
print(num, end=" ")
print("\r")`

python3 pattern program diagonal

HOW IT SHOULD LOOK ALIKE
I want pattern to be like this, but I couldn't come up with the loops ((
rows = int(input("number of rows: "))
space = rows - 1
n = 5
for i in range(0, rows):
for j in range(0, space):
print("", end=" " * n)
for j in range(0, i + 1):
print("*", end=" " * n)
space = space - 1
print()
space = 1
for i in range(rows - 1, 0, +1):
for j in range(space, 0):
print(" ", end=" ")
for k in range(0, i - 1):
print("*", end=" " * n)
space = space + 1
print()
rows = int(input("number of rows: "))
width = int(input("width of your window: "))
space = 9 # space between stars
for i in range(rows):
string = " " * (i % space)
for j in range(width):
if j % space == 0:
string += "*"
else:
string += " "
print(string)

Why aren't the negative numbers being counted properly?

import time
total = 0
pos = 0
zeroes = 0
neg = 0
print('This program will add any seven numbers for you')
time.sleep(2)
print()
a = int(input('Please enter the first number: '))
total = total + a
if a > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
c = int(input('Please enter the third number: '))
total = total + c
if c > 0:
pos = pos + 1
elif c == 0:
zeroes = zeroes + 1
elif c < 0:
neg = neg + 1
time.sleep(2)
d = int(input('Please enter the fourth number: '))
total = total + d
if d > 0:
pos = pos + 1
elif d == 0:
zeroes = zeroes + 1
elif d < 0:
neg = neg + 1
time.sleep(2)
e = int(input('Please enter the fifth number: '))
total =total + e
if e > 0:
pos = pos + 1
elif e == 0:
zeroes = zeroes + 1
elif e < 0:
neg = neg + 1
time.sleep(2)
f = int(input('Please enter the sixth number: '))
total = total + f
if f > 0:
pos = pos + 1
elif f == 0:
zeroes = zeroes + 1
elif f < 0:
neg = neg + 1
time.sleep(2)
g = int(input('Please enter the seventh number: '))
total = total + g
if g > 0:
pos = pos + 1
elif g == 0:
zeroes = zeroes + 1
elif g < 0:
neg = neg + 1
time.sleep(2)
print()
print('The sum of your entries is: ', + total)
time.sleep(2)
print()
print('You entered', + pos, 'positive numbers')
time.sleep(2)
print()
print('You entered', + zeroes, 'zeroes')
time.sleep(2)
print()
print('You entered', + neg, 'negative numbers')
print()
time.sleep(3)
Hello! I have the variable 'neg' keeping a running total of all of the negative numbers that the user enters. It seems as if the negative numbers aren't always being added to the 'neg' running total at the end of the code.
I've been working with Python 3x for about a week now, so be gentle :)
Thanks in advance for the help!
Edit: I have reworked this into a (working) loop per the advice of Kevin, is this a good loop? It seems to work, I'm just looking for pointers as I'm kind of struggling with Python logic. Big thanks to Kevin, wish I could upvote you!
New code posted below:
import time
sums = 0
pos = 0
neg = 0
zero = 0
numb = 0
user_numb = 0
running = True
print('This program will add any 7 numbers for you')
time.sleep(.5)
print()
while running:
user_numb = int(input('Please enter a number: '))
sums = user_numb + sums
numb = numb + 1
print()
if user_numb > 0:
pos = pos + 1
elif user_numb < 0:
neg = neg + 1
elif user_numb == 0:
zero = zero + 1
if numb == 7:
running = False
print()
time.sleep(2)
print('The sum of the numbers entered was: ', + sums)
print()
time.sleep(2)
print('You entered', + pos, 'positive numbers')
print()
time.sleep(2)
print('You entered', + neg, 'negative numbers')
print()
time.sleep(2)
print('You entered', + zero, 'zeroes')
print()
print()
time.sleep(3)
In the section with b you forgot in the copy/pasted code to change all 'a' into 'b' and have still twice an 'a' there:
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0: # CHANGE TO 'b'
zeroes = zeroes + 1
elif a < 0: # CHANGE TO 'b'
neg = neg + 1
so you see wrong results only in case the second number is a 0 or negative.

Need to add all the integers between 2 other integers

This is as far as i have gotten and dont know where go on from here.
result = 0
x = int(input('First: '))
y = int(input('Last: '))
y = y+1
for i in range((print(x+1, y)):
print(result)
This should work:
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))
sumNum1Num2N = 0
print("Let's sum all the integers in this range [%d, %d]" %(num1, num2))
#This shows up the sum being done
for i in range(num1, num2 + 1):
sumNum1Num2N = sumNum1Num2N + i
print(sumNum1Num2N, " " , end="")
print()
print("The sum of the numbers between %d and %d is %d" %(num1, num2, sumNum1Num2N))
If you want to show the integers between 2 numbers.
for i in range(num1, num2 + 1):
print(i)
But if you want a fastest way to sum 2 numbers use the built-in functions sum and range:
m_sum = sum(range(num1, num2 + 1)) #[num1, num2]
Mathematically you can achieve also the sum of the numbers between A and B, where B > A:
B*(B + 1)/2 - (A - 1)*A/2
= (B^2 + B - A^2 + A) / 2
= ((B - A)*(B + A) + (B + A)) / 2
= (B + A) * (B - A + 1) / 2
But I think this is more complicated than the other 2 methods, even though the mathematical procedure is trivial ;)
Does this do what you need?
x = int(input('First: '))
y = int(input('Last: '))
for i in range(x,y+1):
print(i)
Try:
>>> x = int(input('First: '))
First: 1
>>> y = int(input('Last: '))
Last: 10
>>> print(' + '.join(str(e) for e in range(x+1,y)),'=',sum(range(x+1,y)))
2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 44

Resources