I am able to understand the logic here for the below pattern but not getting the way of implementation, please can someone help me here.
The pattern I want is like below, (in first column everything till 5, then second column after 5 leaving first and last row and so on. . )
1
2 6
3 7 9
4 8
5
Try this:
n = int(input())
for i in range(1, (n//2)+2):
for j in range(i):
print(i + ((n - 1) * j) - (j * (j - 1)) , end=' ')
print()
for i in range((n//2)+2, n + 1):
for j in range(n - i + 1):
print(i + ((n - 1) * j) - (j * (j - 1)), end=' ')
print()
Output:
n = 9
1
2 10
3 11 17
4 12 18 22
5 13 19 23 25
6 14 20 24
7 15 21
8 16
9
Logic
n = 9
1 |
2 10 |(10 - 2) = 8
3 11 17 |(11 - 3) = 8, (17 - 11) = 6
4 12 18 22 |(12 - 4) = 8, (18 - 12) = 6, (22 - 18) = 4
5 13 19 23 25 |(13 - 5) = 8, (19 - 13) = 6, (23 - 19) = 4, (25 - 23) = 2
6 14 20 24 |(14 - 6) = 8, (20 - 14) = 6, (24 - 20) = 4
7 15 21 |(15 - 7) = 8, (21 - 15) = 6
8 16 |(16 - 8) = 8
9 |
For example in line5
first number is 5 + ((n - 1) * 0) - (0 * -1) = 5
next value 5 + ((n - 1) * 1) - (1 * 0) = 13
next value 5 + ((n - 1) * 2) - (1 * 2) = 19
next value 5 + ((n - 1) * 3) - (2 * 3) = 23
next value 5 + ((n - 1) * 4) - (3 * 4) = 25
above 5 is i value and 0,1,2,3,4 are j values
generalised formula for calculating the value i + ((n - 1) * j) - (j * (j - 1))
Related
Code
a = int(input("enter a no"))
b = int(input("enter a range"))
for i in range(1, a+1):
print(i)
for j in range(1, b + 1):
c = i * j
print(i, "*", j, "=", c)
Desired output
1 2 3
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30
You can tell print to finish with something other than a newline by specifying the "end" argument:
a = int(input("enter a no "))
b = int(input("enter a range "))
for i in range(1, a+1):
print(i, end=" ")
print("")
for j in range(1, b + 1):
for i in range(1, a+1):
c = i * j
print(i, "*", j, "=", c, end=" ")
print("")
In this case I split the main loop into two separate loops, the first outputs the top line (1, 2, 3...) with some large spacing, whilst the second then does all of the others with slightly less spacing.
I also switched the order of the later loops since there should be b lines, each with a multiplications, so the b loop needs to be the outer (first) loop.
In both cases an empty print statement is used to output a newline when we need it.
This is what you are looking for:
a = int(input("enter a no"))
b = int(input("enter a range"))
for i in range(1, a + 1):
print(i, end="\t"*4)
print("")
for k in range(1, b + 1):
for j in range(1, a + 1):
print(j, "*", k, "=", j*k, end="\t"*2)
print("")
You have to think line-by-line, since you cannot go back in stdout.
The first for will fill the first line
I modified your nested loop because you were using the wrong variables
"\t" is meant to get decent formatting, but it will eventually break if numbers are too big: I believe there is a more refined approach that I am not aware of
print("") is just meant to go to the next line
Approach
Approach is use f-strings to left align all the prints into fields of width 20
Use fixed field widths since otherwise columns won't line up with single and multi-digit numbers
Use print parameter end = '' to avoid carriage returns on after printing a field
Code
a = int(input("enter a no "))
b = int(input("enter a range "))
width = 20
for i in range(1, a+1):
print(f'{i:<{width}}', end="") # Print all multipliers on a single row
print("")
for j in range(1, b + 1):
# Looping over multiplication row
for i in range(1, a+1): # Looping through the columns to multipl
s = f'{i} * {j} = {i*j}' # Expression for column field
print(f'{s:<{width}}', end = '') # Print field left aligned to width 20
print("") # New row
Test
enter a no 4
enter a range 10
1 2 3 4
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3 4 * 1 = 4
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 4 * 2 = 8
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 4 * 3 = 12
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30 4 * 10 = 40
I corrected it like this. Thankyou guys.
just add the end="\t"*4 to fix the alignment issue.
a = int(input("enter a no "))
b = int(input("enter a range "))
for i in range(1, a+1):
print(i, end="\t"*4)
print("")
for j in range(1, b + 1):
for i in range(1, a+1):
c = i * j
print(i, "*", j, "=", c, end="\t"*2)
print("")
for i in range(3,33,3):
for j in range(1,11,1):
print("3 *", j, '=', i)
if j == 10:
break
This is the output that I am getting:
3 * 1 = 3
3 * 2 = 3
3 * 3 = 3
3 * 4 = 3
3 * 5 = 3
3 * 6 = 3
3 * 7 = 3
3 * 8 = 3
3 * 9 = 3
3 * 10 = 3
Could anyone please point out the error for me?
If you just want to print multiples of 3, you don't need two loops. Just one loop from 1 to 10, and then multiply that by 3.
for i in range(1, 11):
j = i * 3
print('3 *', i, '=', j)
I believe you want the product as well as the multiplier, you can use enumerate for this. The code will look something like this:
for i,j in enumerate(range(3,33,3)):
print("3 *", i, '=', j)
Change the i to i * j:
for i in range(3,33,3):
for j in range(1,11,1):
print("3 *", j, '=', i * j)
if j == 10:
break
Here is a simplified version:
for i in range(1, 11):
print(f"3 * {i} = {3 * i}")
Output:
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
You're doing nested loops*, but you meant to loop in parallel. You can do that with zip():
for i, j in zip(range(3, 33, 3), range(1, 11)):
print("3 *", j, '=', i)
Output:
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Canonical question: How to iterate through two lists in parallel?
* This creates a Cartesian product, but it's cut short by the break.
However, in this case it's simpler to just do the math, like in Barmar's answer.
When I was little, I played the next game with my cousins:
"Zero in the car's license plates": by using the numbers in the car's license plate numbers and using the elementary operations (sum, subtraction, product and division) once each, you had to find an order that equaled 0.
For example, if we have the following license plate:
2591 --> (2*5)-(9+1) = 0
2491 --> (2*4)+1 -9 = 0
I would like to make a program in Haskell or Python that it is able to play this game, and print the steps that gives a result of 0.
getZero 2491 = 2*4+1-9
getZero 2591 = 2*5-9+1
Maybe its impossible to make this; I hope that you can help me.
This is probably off topic but a fun toy puzzle.
An easy way to think of the issue is in perhaps four separate parts:
Boring plumbing for the arguments and printing the results
Construct all possible expressions of binary operations of the given numbers.
Interpret these expressions to obtain a numeric literal and drop any result that is not zero.
Pretty print the expression.
We could perform extra steps, such as filtering out duplicates based on algebraic rules (a + b and b + a are morally the same), but I skipped that.
The boring plumbing is just getting our plate numbers (one for each argument), breaking those down into digits, running our computation, and printing the solution.
import Data.Foldable
import Data.List
import System.Environment
main :: IO ()
main =
do ns <- getArgs
for_ ns $ \n -> do
let digitList = map (read . (:[])) (n :: String) :: [Int]
putStrLn $ "---------- " ++ show n ++ " ----------"
putStrLn $ unlines (map render (solutions digitList))
Construction The real fun is in this construction of a binary tree of operations and leafs with the literals. First we define our expression language:
data Expr = Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
| Lit Int
deriving (Eq, Ord, Show)
And we can use these expressions along with a Haskell list monad to build all possible expressions (assuming a non-empty list as input):
operations :: [Expr -> Expr -> Expr]
operations = [Add, Sub, Mul, Div]
exprsOf :: [Expr] -> [Expr]
exprsOf [term] = [term]
exprsOf xs =
do x <- xs
y <- (delete x xs)
o <- operations
exprsOf (o x y : delete y (delete x xs))
That is, x is one of the elements in the original set of expressions. y is another element (but not x). o is one of our legal operations (addition, subtraction, etc). And we recursively reduce this list size till we are left with the top level expression (variable name term). If you don't understand the operation that's OK - specific parts that confuse you would make a fine (on topic) question.
Interpretation With the expressions built we can now interpret them and filter out any that don't result in zero.
The interpreter is just using addition (+) when we see our Add constructor and same for the other operations. I lifted everything into the Maybe Applicative because I didn't want division by zero or with a remainder to show up in our results.
interp :: Expr -> Maybe Int
interp (Lit n) = Just n
interp (Add a b) = (+) <$> interp a <*> interp b
interp (Sub a b) = (-) <$> interp a <*> interp b
interp (Mul a b) = (*) <$> interp a <*> interp b
interp (Div a b) | interp b == Just 0 = Nothing
| interp b == Nothing = Nothing
| otherwise =
case divMod <$> interp a <*> interp b of
Nothing -> Nothing
Just (x,0) -> Just x
_ -> Nothing -- Ignore uneven division
Applying this interpretation is just a matter of filtering for Just 0:
solutions :: [Int] -> [Expr]
solutions xs = filter ((== Just 0) . interp) $ exprsOf (map Lit xs)
Rendering Finally, there's a pretty ugly render function just to emit the proper parenthesis so we see the right order of operations:
render :: Expr -> String
render (Lit n) = show n
render (Add a b) = "(" ++ render a ++ " + " ++ render b ++ ")"
render (Sub a b) = "(" ++ render a ++ " - " ++ render b ++ ")"
render (Mul a b) = "(" ++ render a ++ " * " ++ render b ++ ")"
render (Div a b) = "(" ++ render a ++ " / " ++ render b ++ ")"
Example Run
*Main> :main 2591
---------- "2591" ----------
(((2 * 5) - 9) - 1)
(1 - ((2 * 5) - 9))
(((2 * 5) - 1) - 9)
(9 - ((2 * 5) - 1))
((9 - (2 * 5)) + 1)
(1 + (9 - (2 * 5)))
((9 + 1) - (2 * 5))
((2 * 5) - (9 + 1))
((1 - (2 * 5)) + 9)
(9 + (1 - (2 * 5)))
((1 + 9) - (2 * 5))
((2 * 5) - (1 + 9))
(((5 * 2) - 9) - 1)
(1 - ((5 * 2) - 9))
(((5 * 2) - 1) - 9)
(9 - ((5 * 2) - 1))
((9 - (5 * 2)) + 1)
(1 + (9 - (5 * 2)))
((9 + 1) - (5 * 2))
((5 * 2) - (9 + 1))
((1 - (5 * 2)) + 9)
(9 + (1 - (5 * 2)))
((1 + 9) - (5 * 2))
((5 * 2) - (1 + 9))
(((9 + 1) / 2) - 5)
(5 - ((9 + 1) / 2))
(((9 + 1) / 5) - 2)
(2 - ((9 + 1) / 5))
((2 * 5) - (9 + 1))
((9 + 1) - (2 * 5))
((5 * 2) - (9 + 1))
((9 + 1) - (5 * 2))
(((1 + 9) / 2) - 5)
(5 - ((1 + 9) / 2))
(((1 + 9) / 5) - 2)
(2 - ((1 + 9) / 5))
((2 * 5) - (1 + 9))
((1 + 9) - (2 * 5))
((5 * 2) - (1 + 9))
((1 + 9) - (5 * 2))
This isn't the best implementation, because there are quite a lot of repeats, but does get a result.
Using itertools, I generated every different state (permutation) that the numbers and operations could be in, e.g.:
[('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4'), ('1', '3', '4', '2'), ('1', '4', '2', '3'), ....... ('4', '1', '3', '2'), ('4', '2', '1', '3'), ('4', '2', '3', '1'), ('4', '3', '1', '2'), ('4', '3', '2', '1')]
[('+', '-', '*'), ('+', '*', '-') ...... ('/', '-', '*'), ('/', '*', '-')]
...then, I made a function that adds brackets to every possible state of the calculation:
[1,'+',2,'-',3,'*',4] becomes:
1 + 2 - 3 * 4
( 1 + 2 ) - ( 3 * 4 )
( 1 + 2 - 3 ) * 4
1 + ( 2 - 3 * 4 )
( 1 + 2 ) - 3 * 4
1 + 2 - ( 3 * 4 )
1 + ( 2 - 3 ) * 4
... and then, evaluated each different possibility, and if it was zero I printed it out.
Heres all the code:
from itertools import permutations, combinations, chain
import sys
operations = ['+', '-', '*', '/'] # basic operations
# add every combination of brackets to the calculation
def addBrackets(calc):
possibilities = []
possibilities.append(" ".join(calc))
possibilities.append(" ".join(str(s) for s in list(chain(["("], calc[:3], [")"], [calc[3]], ["("], calc[4:], [")"]))))
possibilities.append(" ".join(str(s) for s in list(chain(["("], calc[:-2], [")"], calc[-2:]))))
possibilities.append(" ".join(str(s) for s in list(chain(calc[:2], ["("], calc[2:], [")"]))))
possibilities.append(" ".join(str(s) for s in list(chain(["("], calc[:3], [")"], calc[3:]))))
possibilities.append(" ".join(str(s) for s in list(chain(calc[:4], ["("], calc[4:], [")"]))))
return possibilities
def getZero(n): # 2491
nums = [x for x in str(n)] # [2, 4, 9, 1]
while len(nums) < 4:
nums = ['0'] + nums # add zeroes if the input was less than 1000 e.g. [5, 3, 1] -> [0, 5, 3, 1]
possible_number_order = list(permutations(nums)) # get every number order
possible_op_order = list(combinations(operations, 3)) # get combinations of 3 of the operations
possible_op_permutations = list(chain(list(permutations(p)) for p in possible_op_order)) # chain together all the permutations of each combination
possible_op_order = []
for perms in possible_op_permutations:
possible_op_order.extend(perms) # add all the lists into one
for n in possible_number_order: # for each number order
for op in possible_op_order: # for each operation order
calculation = [n[0],op[0],n[1],op[1],n[2],op[2],n[3]] # create a list with the order of the operation
for calc in addBrackets(calculation): # for each bracket position
try:
result = eval(calc) # evaluate
if abs(result) <= 0.001: # to check for float comparison
print("{} = {}".format(calc, 0))
except: # ZeroDivisionError
continue
if __name__ == "__main__":
for user_input in [int(n) for n in sys.argv[1:]]:
print("-------{0:04}-------".format(user_input)) # print 0 padded output
getZero(user_input)
Enter the input as command line arguments:
$ python3.6 zerogame.py 2491 2591
-------2491-------
( 2 * 4 - 9 ) + 1 = 0
( 2 * 4 ) - 9 + 1 = 0
( 2 * 4 ) + ( 1 - 9 ) = 0
( 2 * 4 + 1 ) - 9 = 0
( 2 * 4 ) + 1 - 9 = 0
2 * 4 + ( 1 - 9 ) = 0
2 + ( 1 - 9 ) / 4 = 0
( 4 * 2 - 9 ) + 1 = 0
( 4 * 2 ) - 9 + 1 = 0
( 4 * 2 ) + ( 1 - 9 ) = 0
( 4 * 2 + 1 ) - 9 = 0
( 4 * 2 ) + 1 - 9 = 0
4 * 2 + ( 1 - 9 ) = 0
4 + ( 1 - 9 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 * 5 ) + 9 = 0
1 - ( 2 * 5 ) + 9 = 0
( 1 - 5 * 2 ) + 9 = 0
1 - ( 5 * 2 ) + 9 = 0
( 1 + 9 ) - ( 2 * 5 ) = 0
1 + ( 9 - 2 * 5 ) = 0
( 1 + 9 ) - 2 * 5 = 0
1 + 9 - ( 2 * 5 ) = 0
( 1 + 9 ) / 2 - 5 = 0
( 1 + 9 ) - ( 5 * 2 ) = 0
1 + ( 9 - 5 * 2 ) = 0
( 1 + 9 ) - 5 * 2 = 0
1 + 9 - ( 5 * 2 ) = 0
( 1 + 9 ) / 5 - 2 = 0
Write function count_Kprimes with given parameters k, start, nd, that returns a list of the k-primes between start (inclusive) and end (inclusive).
Here is my attempt:
def count_Kprimes(k, start, nd):
ls = []
for x in range(start, nd + 1):
y = x
l = []
for i in range(2, x + 1):
while y % i == 0:
l.append(i)
y /= i
if len(l) == k:
ls.append(x)
return ls
However, my code takes too much time to process and I want to simply my code. How can it be done? Thank you so much!
This task is taken from Codewar
Well, I had fun solving this anyway. Here is a solution based on array-logic
def count_Kprimes(k, start, nd):
x = np.arange(start, nd + 1, dtype=np.float)
# divs will contain all divisors (plus one extra column)
divs = np.ones((x.size, k + 1))
# we have to loop only nd / 2^(k-1) to get all divisors
for i in range(2, int(nd / 2 ** (k - 1)) + 1):
# but each possible divisor "i" may occur up to k times
# we loop until k+1 to catch also number that exceed our target,
# so we can discard them later
for j in range(1, k + 2):
# check for each row (dimension 0) if i is a divisor
# then set the first zero-value in dimension 1 to be this divisor
d = np.prod(divs, axis=1)
divs[[[np.rint(x/d/i)==x/d/i][0],np.argmin(divs[np.rint(x/d/i)==x/d/i], axis=1)]] = i
# The correct result we're looking for is each row that has exactly
# k values != 1 (which equals to exactly one "1" per row)
indices = np.apply_along_axis(lambda x: x[x==1].size == 1, 1, divs)
for val, d in zip(x[indices], divs[indices]):
print "{} = {}".format(int(val), " * ".join([str(int(_)) for _ in d[:-1]]))
count_Kprimes(3, 1, 100)
returns
8 = 2 * 2 * 2
12 = 2 * 2 * 3
18 = 2 * 3 * 3
20 = 2 * 2 * 5
27 = 3 * 3 * 3
28 = 2 * 2 * 7
30 = 2 * 3 * 5
42 = 2 * 3 * 7
44 = 2 * 2 * 11
45 = 3 * 3 * 5
50 = 2 * 5 * 5
52 = 2 * 2 * 13
63 = 3 * 3 * 7
66 = 2 * 3 * 11
68 = 2 * 2 * 17
70 = 2 * 5 * 7
75 = 3 * 5 * 5
76 = 2 * 2 * 19
78 = 2 * 3 * 13
92 = 2 * 2 * 23
98 = 2 * 7 * 7
99 = 3 * 3 * 11
I'm trying to do a substitution trace for this code:
def hanoi(n):
if n == 1:
return 1
else:
return 2 * hanoi(n - 1) + 1
print hanoi(4)
Output:
15
This is what I did:
2 * (4 - 1) + 1
2 * (3) + 1
6 + 1
7
I'm not sure what I'm doing wrong.
You have a recursion function and after each step it converted to sub functions with n-1 :
Actually you have this :
2 * hanoi(4 - 1) + 1
2 * hanoi(3) + 1
2 * (2 * hanoi(2) + 1) + 1
2 * (2 * (2 * hanoi(1) + 1) + 1) + 1
2 * (2 * (2 * 1 + 1) + 1) + 1 = 15
2 * hanoi(4-1) + 1 is not the same as 2 * (4-1) + 1