I want to print the below pattern using Nested list comprehension. I am able to achieve this through normal for loops.
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
#
for i in range (1,8):
k=0
for j in range (1,i+1):
k=k+i
print k,
print
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Here you go:
pattern = [[j*i for j in range(1,i+1)] for i in range(1,8)]
print ("\n".join(" ".join(map(str, line)) for line in pattern))
First line will create a list (2d) containing the pattern and second line is to print the list in proper format.Make appropriate changes if you are using python 2.
List comprehensions aren't a direct replacement for loops in every case.
You use a list comprehension when you want to store the resulting data structure for later use- it takes up space in memory, etc. Since you are only printing out data, list comprehensions don't confer any major advantages, and may actually make your code harder to read and maintain.
Since other people have proposed list comprehension solutions, I'll also be helpful and point out that in python 2, you can get print as a function by putting the following at the start of your file:
from __future__ import print_function
This will work:
print("\n".join(" ".join(str(i*k) for k in range(1, i+1)) for i in range(1,8)))
Prints out:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
As #abought says, you don't want a nested list comprehension. Print one line at a time and save yourself storing a huge string in memory when you don't have to.
>>> for i in range(1, 8):
print ' '.join(map(str, range(i, i*i+1, i)))
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
And here's how another one of #abought's suggestions (the print_function) would be implemented:
>>> from __future__ import print_function
>>> for i in range(1, 8):
print(*range(i, i*i+1, i), sep=' ')
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
in simple manner u can break it like this
n = 5
for i in range(1,n+1):
nums = 1
for j in range(0,i):
print(nums*i,end=" ")
nums = nums +1
print("\r")
Related
I have a script that uses iterrows and have read that this is an inefficient method and would like to refine my code. But after reading other questions on the topic I haven't found the answer to my specific example. I'm a complete amateur coder so would appreciate any assistance in getting better.
I just want to remove duplicates in a series, keeping only the first and leaving blanks for subsequent rows with the same time. I keep the first row's time no matter what, so I start with comparing the second value.
def clean_times(df):
time = df.iloc[1]['Result'] # initilize to the first time gap
if ':' in time:
for index, row in df.iterrows():
if index > 1:
if row['Result'] == time:
df.loc[index, 'Result'] = ''
else:
time = row['Result']
return df
time = ''
x = [{'Result':'4:51:36'},{'Result':'0:01:27'},{'Result':'0:02:19'},{'Result':'0:02:42'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:03:03'},{'Result':'0:03:03'},{'Result':'0:03:23'},{'Result':'0:03:23'},{'Result':'0:03:23'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:04:02'},{'Result':'0:04:15'},{'Result':'0:04:15'},{'Result':'0:04:25'},{'Result':'0:04:25'},{'Result':'0:04:25'}]
df = pd.DataFrame(x)
df1 = clean_times(df)
Result
Result
0 4:51:36
1 0:01:27
2 0:02:19
3 0:02:42
4 0:02:57
5
6
7
8
9
10
11
12
13
14
15
16
17
18 0:03:03
19
20 0:03:23
21
22
23 0:03:57
24
25
26
27
28
29
30
31
32
33 0:04:02
34 0:04:15
35
36 0:04:25
37
38
Just use mask with a condition on the next (shifted) row:
df['Result'] = df['Result'].mask(df['Result']==df['Result'].shift(), '')
output:
Result
0 4:51:36
1 0:01:27
2 0:02:19
3 0:02:42
4 0:02:57
5
6
7
8
9
10
11
12
13
14
15
16
17
18 0:03:03
19
20 0:03:23
21
22
23 0:03:57
24
25
26
27
28
29
30
31
32
33 0:04:02
34 0:04:15
35
36 0:04:25
37
38
Recently I was looking at some code related to a deep learning paper, repo here: https://github.com/wuyifan18/DeepLog/blob/master/LogKeyModel_predict.py
This has more to do with python so I will not mention anything else about it. Below is a file we need to parse:
5 5 5 22 11 9 11 9 11 9 26 26 26 23 23 23 21 21 21
5 5 22 5 11 9 11 9 11 9 26 26 26
5 22 5 5 11 9 11 9 11 9 26 26 26
5 22 5 5 11 9 11 9 11 9 26 26 26
5 22 5 5 11 9 11 9 11 9 26 26 26 23 23 23 21 21 21
22 5 5 5 11 9 11 9 11 9 26 26 26 23 23 23 21 21 21
5 22 5 5 11 9 11 9 11 9 26 26 26 23 23 23 21 21 21
5 5 5 22 11 9 11 9 11 9 26 26 26 2 23 23 23 21 21 21
5 22 5 5 11 9 11 9 11 9 26 26 26
The following function is supposed to parse it. First, we take each line, and make a list with the elements being the numbers in that line separated by spaces. Then we subtract said numbers by one at line ###.
What happens next?
def generate(name):
hdfs = set()
# hdfs = []
with open('data/' + name, 'r') as f:
for ln in f.readlines():
ln = list(map(lambda n: n - 1, map(int, ln.strip().split()))) ###
ln = ln + [-1] * (window_size + 1 - len(ln))
# print(ln)
hdfs.add(tuple(ln))
print('Number of sessions({}): {}'.format(name, len(hdfs)))
return hdfs
I am not sure what the purpose of ln = ln + [-1] * (window_size + 1 - len(ln)) is exactly. What is it doing? I have not seen list multiplication being used in many places before, so I am not sure. When I try and print out more of it, it seems that -1 is not present in ln at all. Anyone have some idea?
Without delving into the code, the idea is to make all the lines the same length, based on the window
If your window size is 10, and a line contains only 5 entries, your list will look like: [1, 2, 3, 4, 5, -1, -1, -1, -1, -1], this is to deal with the static sized window.
I am trying to write a code where I put a number n in input() and in output I will get three same nxn tables. I cannot use if's nor '\t' nor lists. I am only a begginer so we cannot use any difficult functions or anything like that.
This is my code:
n = int(input('n: '))
for i in range(n):
for j in range(n):
print(f'{i*n + j + 1:2}', end=' ')
for k in range(n):
print(f'{i*n + k + 1:2}', end=' ')
for l in range(n):
print(f'{i*n + l + 1:2}', end=' ')
print()
The problem is that I need to put 4 whitespaces (a tab) behind every line of a table ( so that tables can be recognized as 3 and it doesn't look like one table).
My output looks like this now:
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
6 7 8 9 10 6 7 8 9 10 6 7 8 9 10
11 12 13 14 15 11 12 13 14 15 11 12 13 14 15
16 17 18 19 20 16 17 18 19 20 16 17 18 19 20
21 22 23 24 25 21 22 23 24 25 21 22 23 24 25
Output should look like this:
n: 5
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
6 7 8 9 10 6 7 8 9 10 6 7 8 9 10
11 12 13 14 15 11 12 13 14 15 11 12 13 14 15
16 17 18 19 20 16 17 18 19 20 16 17 18 19 20
21 22 23 24 25 21 22 23 24 25 21 22 23 24 25
Every time you finsh printing part of the line, mean after every for loop print some spaces:
n = int(input('n: '))
for i in range(n):
for j in range(n):
print(f'{i*n + j + 1:2}', end=' ')
print(' ', end='')
for j in range(n):
print(f'{i*n + j + 1:2}', end=' ')
print(' ', end='')
for j in range(n):
print(f'{i*n + j + 1:2}', end=' ')
print(' ', end='')
print()
Output:
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
6 7 8 9 10 6 7 8 9 10 6 7 8 9 10
11 12 13 14 15 11 12 13 14 15 11 12 13 14 15
16 17 18 19 20 16 17 18 19 20 16 17 18 19 20
21 22 23 24 25 21 22 23 24 25 21 22 23 24 25
and you can use the same name j in every loop it's not problem because here. because it will reinitialized by the for loop every time. Hope this is clear an simple for you.
Need help creating a 9 column descending half pyramid.
The first column must count 1-9.
Then with each row they should continue counting with that starting multiple. Would appreciate any help please.
for num in range(10):
for i in range(num):
print (num, end=" ")
print("\n")
>Current output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
>I need it to output as:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 27 35 42
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
You got your inner looping wrong. Considering the outer loop represents line numbers, the inner loop should start from line number, incrementing each time by line number till the square of line number:
for num in range(1, 10):
for i in range(num, num*num+1, num):
print(i, end=" ")
print("\n")
# 1
# 2 4
# 3 6 9
# 4 8 12 16
# 5 10 15 20 25
# 6 12 18 24 30 36
# 7 14 21 28 35 42 49
# 8 16 24 32 40 48 56 64
# 9 18 27 36 45 54 63 72 81
you were almost there! just a few minor adjustments:
for mul in range(1, 10):
for i in range(1, mul+1):
print (i * mul, end=" ")
print("\n")
what you need to print is i * mul; and the range needs to start at 1 and stop at (i.e. one before) mul+1.
a bit more compact and neatly aligned:
for mul in range(1, 10):
print(' '.join(f'{mul*i:2d}' for i in range(1, mul+1)))
this outputs:
1
2 4
3 6 9
4 8 12 16
...
9 18 27 36 45 54 63 72 81
I have to make a times table code using recursive functions. I have to ask the user for a number and print out the times tables from 1 to 12. And I have to use recursive functions and it is not allowed to use for loops or while loops and all variables besides the user input have to be defined inside the functions. I am having trouble defining the number that the user provided number needs to be multiplied with. E.X. 2 x 1 2 x 2 2 x 3.
def times_tables(num):
def multiply(x):
product = x * num
if x < 12:
print (str(multiply(x + 1)))
user = input("Enter a number: ")
times_tables(user)
If I define x in the times_tables function then every time the function runs it will get set back to whatever I set it to the first time. Thanks for your help.
You are not modifying x, x is passed by value, this mean it is copied.
If you want to keep the exit conditon outside the recursion you need a way to write X directly from the recursion, which probably would involve a global (bad practices so avoid).
You need to have the exit condition inside multiply, because that will be your recursion, in that case your X will increase and you will do the check on the proper incremented value. Or change the function all together as ruggfrancesco suggested
def times_tables(n, t=1):
if t == 13:
return
print(str(n) + " x " + str(t) + " = " + str(n*t))
times_tables(n, t+1)
times_tables(int(input("Enter number: ")))
Enter number: 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
3 x 11 = 33
3 x 12 = 36
When I (Image) Google "times table", I get a very different result from what the other answers produce. Below is my recursive solution in two dimensions:
def times_table(limit):
number_format = "{{:{}}}".format(len(str(limit ** 2)))
def times_table_recursive(number, increment):
minimum = max(increment, 1)
if number <= minimum * limit:
print(number_format.format(number if number > 0 else 'x'), end=' ')
times_table_recursive(number + minimum, increment)
elif increment < limit:
print()
increment += 1
print(number_format.format(increment), end=' ')
times_table_recursive(increment, increment)
else:
print()
times_table_recursive(0, 0)
times_table(12)
OUTPUT
> python3 test.py
x 1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 6 7 8 9 10 11 12
2 2 4 6 8 10 12 14 16 18 20 22 24
3 3 6 9 12 15 18 21 24 27 30 33 36
4 4 8 12 16 20 24 28 32 36 40 44 48
5 5 10 15 20 25 30 35 40 45 50 55 60
6 6 12 18 24 30 36 42 48 54 60 66 72
7 7 14 21 28 35 42 49 56 63 70 77 84
8 8 16 24 32 40 48 56 64 72 80 88 96
9 9 18 27 36 45 54 63 72 81 90 99 108
10 10 20 30 40 50 60 70 80 90 100 110 120
11 11 22 33 44 55 66 77 88 99 110 121 132
12 12 24 36 48 60 72 84 96 108 120 132 144
>
Only goes up to times_table(30) without expanding Python's recursion depth limit.
def fun (no,i=1):
if i==10:
print (no*i)
else:
print (no*fun(i+1)
no=int (input ("Enter a no="))
fun (no)