How do I print only 3 values per line with right alignment? - python

The below is my current code. However, I want to print only 3 values per line with 5 spaces between column with right alignment. I am trying to get my code to match with the image below.
def formats():
import random
lst = []
for i in range(100):
lst.append(random.uniform(0, 1000)) #Get a random number btw 0 and 1000
num = eval(input('Enter number of values to retrieve: '))
for x in range(num+1):
print('${:>5,.2f}'.format(lst[x]), end=' ')

well, I tried this, and it is working fine,
for x in range(num):
print('${:>5,.2f}'.format(lst[x]), end=' ')
if (x+1)%3==0:
print('\n')
I don't know why you were using range(num+1). If you want 19 values, this will be returning 20.

Not the most elegant solution, but works fine. Including the justification.
import random
lst = []
for i in range(100):
lst.append(random.uniform(0, 1000)) #Get a random number btw 0 and 1000
num = eval(input('Enter number of values to retrieve: '))
groups_of_3 = [lst[0:num][i:i+3] for i in range(0, num, 3)]
for group in groups_of_3:
for value in group:
justfied_num = (str(value).split(".")[0] + "." + str(value).split(".")[1][0:2]).rjust(6)
print(f'${justfied_num}', end=' ')
print()

Related

How can I use for loops to figure out how to solve this?

enter image description here5
I have to use a for loop to code this. I have tried many times but it never works.
enter code here
num_of_times = 5
for x in range(1, num_of_times, 5):
for y in range(5, i+5):
print(y, end= '')
print('')
You can try this:
lst = []
for i in range(1, 5):
lst.append(i * 5)
print(*lst)
You basically want to print multiple of 5. That could be achieved with two nested for loops:
max = 5
for i in range(max):
line = ''
for j in range(i+1):
line += str(5 * (j+1)) + ' '
print(line)
The first loop goes from 0 to max-1 and stores the index in i ; the second loop goes from 0 to i+1 and stores the index in j.
Then, the result of 5 * (j+1) is added to a variable called line printed at the end of the j-loop.
Feel free to follow the loops and the value of each variable at every step with a paper and a pen, that should help you.
Here you go
for i in range(1,6):
for j in range (1, i+1):
print(j*5, end = ' ')
print('')

Python program which prints out line number and length of list: Error

Now I'm using while loops to try and do this because I'm not too good at using for loops. As the title reads, I'm trying to print out a table which has the line number next to the length of each line.
Error: When I hit run all I get is the above print out (line and number of words with dashes below). I do not get a series of printouts of y and z
Note: I'm probably making this way harder than it needs to be
Code:
list1 = ['Lets go outside','pizza time','show me the money']
list2 = []
print('line number of words')
print('---- ---------------')
x = 0
len_l1 = len(list1)
while len_l1 > 0:
split_lis1 = list1[0+x].split(' ')
list2.append(split_lis1)
len_l1 -= 1
x += 1
while len_l1 > 0:
q = 1
y = len(list1) - len(list1) + q(x)
z = len(list2[0+x])
print(y, z)
len_l1 -= 1
x += 1
what I want the print out to look like:
line number of words
---- ---------------
0 3
1 2
2 4
Thanks.
Yes, you might have overcomplicated the solution as there are out of the box Python methods that help you easily solve problems like this. For iteration with indexes, use enumerate, in the example below we set the index to start at 1. We can also use some simple string formatting defined in fmt to ensure consistent spacings.
li = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
fmt = ('{} {}')
for idx, sentence in enumerate(li,1):
no_of_words = len(sentence.split())
print(fmt.format(idx, no_of_words))
Then simple use split to split the whitespaces and get the total number of words and let enumerate manage the whole thing for you.
>>
line number of words
---- ---------------
1 3
2 2
3 4
list1 = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
for i in range(0, len(list1)):
length = len(list1[i].split(" "))
print(i + 1, " ", length)
Check out python docs for range and for details.

Diagonal shape in Python using while loops

I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable.
Here is my code for a square:
def drawSquare(size, drawingChar):
print('Square: ')
row = 1
while row <= size:
# Output a single row
drawRow(size, drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
It is supposed to print like:
x
x
x
x
based on a size and character entered by the user.
drawRow is another function similar to drawSquare:
def drawRow(size, drawingChar):
col = 1
while col <= size:
print(drawingChar, end=' ')
col = col + 1
It would make more sense with a for loop:
def drawSquare(size, drawingChar):
for i in range(size):
print(" "*i + drawingChar)
Example:
drawSquare(4, "p")
Output:
p
p
p
p
Please show your work for drawDiagonal (or anything) when asking a question.
Diagonal is probably the easier case here:
def drawDiagonal(size, drawingChar):
for y in range(size):
s = ' '* y + drawingChar
print(s)
drawDiagonal(4,"X")
X
X
X
X
(Maybe pick a fixed font)
The solution I came up with is:
def drawDiagonal(size, drawingChar):
print('Diagonal: ')
row = 1
while row <= size:
# Output a single row
drawRow(row - 1, ' ')
print(drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
Note: drawRow is defined separately (above, in question)
& drawDiagonal was called separately as well:
drawDiagonal(userSize, userChar)
where
userSize = input('Size: ')
userChar = input('Character: ')

Python 2 compiler doesn't read the correct values after the 31st inputted value

Solving the Smoothing the Weather problem on Codeabbey. It prints the correct output for the first 32 values after which it doesn't read the inputted values correctly. Inputted test values are well over 150.
Here is my code:
from __future__ import division
num=int(raw_input());
inp=((raw_input()).split(" "));
lists=[];
for i in inp:
if inp.index(i)==0 or inp.index(i)==len(inp)-1:
lists.append(inp[inp.index(i)])
else:
a,b,c=0.0,0.0,0.0;
a=float(inp[(inp.index(i))+1])
b=float(inp[inp.index(i)])
c=float(inp[(inp.index(i))-1])
x=(a+b+c)/3
x = ("%.9f" % x).rstrip('0')
lists.append(x)
for i in lists:
print i,
The index in the following code will always return the first occurrence of i in inp. So, if there are duplicate values in inp, then the whole logic fails.
if inp.index(i)==0 or inp.index(i)==len(inp)-1:
lists.append(inp[inp.index(i)])
The correct approach would be to enumerate and us correct indices:
from __future__ import division
num = int(raw_input())
inp = ((raw_input()).split(" "))
lists = []
for i, item in enumerate(inp): # This will loop through inp, while filling the next item in item and keep on incrementing i each time starting with 0
if i == 0 or i == len(inp)-1:
lists.append(inp[i])
else:
a = float(inp[i+1])
b = float(inp[i])
c = float(inp[i-1])
x = (a+b+c) / 3.0
x = ("%.9f" % x).rstrip('0')
lists.append(x)
for i in lists:
print i,
Hope that helps.

Divide list elements by list sum and place back into list

Here's the jist of what I'm trying to accomplish. I have a .txt file(dict.txt) which contain a ton of words. My task is count the frequency of each letter in the .txt file and put it in a list, convert each element into a percentage (divide ea element by 100), then use that list as my y_axis for my bar plot.
So far I've created a dictionary which contains each letter of alphabet as the key and the value equals the total amount of times that letter appears in the .txt file. Where I'm stuck is getting each value to divide by 100, then place that new number into a list where I can use as my y-axis for my plot. the x-axis are the letters themselves.
Here is the code I already wrote:
letter_dict = {}
word_list = []
filename = raw_input('Enter filename: ')
new_file = open(filename).readlines()
for i in new_file:
word = i.strip().lower()
word_list += list(word)
for letter in word_list:
if letter in letter_dict:
letter_dict[letter] += 1
else:
letter_dict[letter] = 1
x_axis = []
y_axis = []
summ= 0
for i in letter_dict.values(): #sum of all values in list
summ += i
value_list = list(letter_dict.values())
for k in letter_dict:
x_axis += [k]
print summ
y_axis = []
num_avg = []
for i in value_list:
y_axis += [int(i) / summ]
create_plot(x_axis, y_axis, filename) #this is for my "plot" function
whenever I for loop (i in value_list) then divide ea element by the sum, the printed list returns as [0,0,0,0,0,0,0,0,0,0,0,0,0,0]. I'm stumped.
The problem can be here:
y_axis += [int(i) / summ]
Dividing two integers resturns integer, here you get rounded the real result out.
As soon as one of the numbers is e.g. float, you will get float result.
y_axis += [int(i) / float(summ)]
The reason they return as 0 is because Python uses integer division. Use float to get more intuitive results.
In [1]: 1/5
Out[1]: 0
In [2]: float(1)/5
Out[2]: 0.2
Here is a rewritten version:
# Assumes Python 2.7
from collections import Counter
import matplotlib.pyplot as plt
from string import ascii_lowercase
def get_file():
fname = raw_input("Enter the file name: ")
with open(fname) as inf:
return inf.read()
def count_letters(s):
chars = Counter(s.lower())
return {ch:chars[ch] for ch in ascii_lowercase}
def plot_letters(count):
total = sum(count.values())
xs = range(len(ascii_lowercase))
ys = [count[ch] * 100. / total for ch in ascii_lowercase]
plt.bar(xs, ys)
plt.xticks([x+0.5 for x in xs], ascii_lowercase)
plt.show()
def main():
letters = get_file()
count = count_letters(letters)
plot_letters(count)
main()
which produces something like:

Categories

Resources