why dynamic integer right align in python 3 - python-3.x

What I am trying to do below in my code is just print all the types of number formats available in right aligned manner.
def print_formatted(number):
for i in range(1, n+1):
width = len(format(i, 'b'))
print("{0:d} {0:o} {0:x} {0:{w}b}".format(i, w=len(format(i, 'b'))))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
Input:
4
Expected Output:
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
But actual output:
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
The above code works fine if I give a static value in-place of 'w' but if I pass dynamic changing value it is not working as expected. What am I missing here
Thanks in advance for your help.

Related

How to list the number of words in a row with the most words?

I try to write the number of words from the longest line. I was able to write the number of words in each line, but I can't print the maximum number. The max () function do not works. Can anyone help me?
import os
import sys
import numpy as np
with open('demofile.txt') as f:
lines = f.readlines()
for index, value in enumerate(lines):
number_of_words = len(value.split())
print(number_of_words)
demofile.txt
<=4 1 2 3 4 5 6 7 8 9 10 11
<=4 1 2 3 4 5 6 7 8 9
<=4 1 2 3 4 5 6 7 8 9 10 11 sdad adada affg
<=4 1 2 3 4 5 6 7 8 9 10 11
Output:
12
10
15
12
0
0
0
0
0
0
0
0
0
0
0
I also don't understand why it lists the number of words in the next lines where there are no words
If I understood correctly max() function doesn't work because you are searching max of strings so you need to convert them to ints(floats).
lines = [int(x) for x in lines.split(" ")] // converts to ints
maximum = max(lines)// should work now
UPD:
Edited with comment below.
Before:
int(x) for x in lines
Now:
int(x) for x in lines.split(" ")

Program to produce the following pattern

I am trying to print
2
1 3
2 4 6
1 3 5 7
2 4 6 8 10
I am not sure how to do it ,I could use print (...) And write everything but that is just stupid.
Is there a better way to do this?
for i in range(0, 5):
for j in range(0, i+1):
if i % 2 == 0:
print((j+1)*2, end=' ')
else:
print((j*2)+1, end=' ')
print()
maybe you can try this:
>>> def pattern_gen(layer):
... for i in range(layer):
... pattern=''
... start=(i+1)%2+1
... end=(i+(i+1)%2+1)*2
... for j in range(start,end,2):
... pattern+=f'{j} '
... print(pattern)
...
>>> pattern_gen(5)
2
1 3
2 4 6
1 3 5 7
2 4 6 8 10

Printing Pattern in Python

1. The Problem
Given a positive integer n. Print the pattern as shown in sample outputs.
A code has already been provided. You have to understand the logic of the code on your own and try and make changes to the code so that it gives correct output.
1.1 The Specifics
Input: A positive integer n, 1<= n <=9
Output: Pattern as shown in examples below
Sample input:
4
Sample output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Sample input:
5
Sample output:
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
2. My Answer
2.1 My Code
n=int(input())
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t)
for a in answer:
a.insert(0,i)
a.append(i)
print(answer)
outlst = [' '.join([str(c) for c in lst]) for lst in answer]
for a in outlst:
print(a)
2.2 My Output
Input: 4
4 4 4 4 4 4 4 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 3 2 1 2 3 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 4 4 4 4 4 4 4
2.3 Desired Output
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Your answer isn't as expected because you add the same object t to the answer list twice:
answer.insert(0, t)
answer.append(t)
More specifically, when you assign t = [i]*(2*i - 3), a new data structure is created, [i, ..., i], and t just points to that data structure. Then you put the pointer t in the answer list twice.
In the for a in answer loop, when you use a.insert(0, i) and a.append(i), you update the data structure a is pointing to. Since you call insert(0, i) and append(i) on both pointers that point to the same data structure, you effectively insert and append i to that data structure twice. That's why you end up with more digits than you need.
Instead, you could run the loop for a in answer for only the top half of the rows in the answer list (and the middle row that has was created without a pair). E.g. for a in answer[:(len(answer)+1)/2].
Other things you could do:
using literals as the arguments instead of reusing the reference, e.g. append([i]*(2*i-3)). The literal expression will create a new data structure every time.
using a copy in one of the calls, e.g. append(t.copy()). The copy method creates a new list object with a "shallow" copy of the data structure.
Also, your output digits are space-separated, because you used a non-empty string in ' '.join(...). You should use the empty string: ''.join(...).
n=5
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t.copy())
for a in answer:
a.insert(0,i)
a.append(i)
answerfinal=[]
for a in answer:
answerfinal.append(str(a).replace(' ','').replace(',','').replace(']','').replace('[',''))
for a in answerfinal:
print(a)
n = int(input())
for i in range(1,n*2):
for j in range(1,n*2):
if i <= j<=n*2-i: print(n-i+1,end='')
elif i>n and i>=j >= n*2 -i : print(i-n+1,end='')
elif j<=n: print(n-j+1,end="")
else: print(j-n+1,end='')
print()
n = int(input())
k = 2*n - 1
for i in range(k):
for j in range(k):
a = i if i<j else j
a = a if a<k-i else k-i-1
a = a if a<k-j else k-j-1
print(n-a, end = '')
print()

To print a pattern in Python using 'for' loop

I tried various programs to get the required pattern (Given below). The program which got closest to the required result is given below:
Input:
for i in range(1,6):
for j in range(i,i*2):
print(j, end=' ')
print( )
Output:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Required Output:
1
2 3
4 5 6
7 8 9 10
Can I get some hint to get the required output?
Note- A newbie to python.
Store the printed value outside of the loop, then increment after its printed
v = 1
lines = 4
for i in range(lines):
for j in range(i):
print(v, end=' ')
v += 1
print( )
If you don't want to keep track of the count and solve this mathematically and be able to directly calculate any n-th line, the formula you are looking for is the one for, well, triangle numbers:
triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
t = triangle(line)
print(' '.join(str(x+1) for x in range(t-line, t)))
# 1
# 2 3
# 4 5 6
# 7 8 9 10

How can I write this code more efficiently to make it run faster?

The function of the code is to transform the dataset such that for each given pair of movies, it counts the number of users that have seen both movies and keep track of that value(store it as a column value).
I have tried writing the code as such but it takes a lot of time to execute when the pairs increase.
def dataset_to_item_graph(self):
self.dataset1=self.dataset
items=self.dataset['movieId'].unique()
print(len(items))
ux=combinations(items,2)
item_edges=[]
for x in ux:
i = x[0]
j = x[1]
a = set(self.dataset1.loc[self.dataset1['movieId'] == i]['userId'])
b = set(self.dataset1.loc[self.dataset1['movieId'] == j]['userId'])
c = a.intersection(b)
if len(c) >0:
edge_list=[i,j,len(c)]
item_edges.append(edge_list)
else:
continue
item_graph = pd.DataFrame(item_edges, columns=['movie1','movie2','weight'])
return item_graph
This is the sample dataset I am working with:
userId movieId rating timestamp
0 1 1 4.0 964982703
1 1 3 4.0 964981247
2 1 6 4.0 964982224
3 1 47 5.0 964983815
4 1 50 5.0 964982931
5 2 1 3.0 964982931
6 2 3 4.0 964982831
7 2 6 4.0 964982933
8 3 47 5.0 964981249
9 3 1 2.0 964981248
10 3 50 3.5 965982931
This is the output I am expecting:
movieId1 movieId sum
0 1 3 2
1 1 6 2
2 1 47 2
3 1 50 2
4 3 6 1
5 3 47 1
6 3 50 1
7 6 47 1
8 6 50 1
9 47 50 2
It seems your problem is that big for loop. It could be interesting to launch subprocesses to compute those steps in parallel instead of sequencially. Do you know the multiprocessing module? You could try looking at this article, especially the example at the end, that uses from multiprocessing import Queue.

Resources