Why can't I find max number in a file like this? - python

I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the list. I tried to do so with the following code:
i = 0
with open('jan14.nSets.txt','r') as data:
for num in data:
if num > i:
i = num
print(i)
where jan14.nSets.txt is the following:
12
80
46
51
0
64
37
9
270
23
132
133
16
6
18
23
32
75
2
9
6
74
44
41
56
17
9
4
8
5
3
27
1
3
42
23
58
118
100
185
85
63
220
38
163
27
198
Rather than 270, I receive 9 as an output, and I do not understand why this is the case. I know that there are builtins for this, but I would like to know why this doesn't work to help me understand the language. I am using python2.7

num is a string, not a number. Turn it into an integer first using int():
num = int(num)
You are comparing text, so it is ordered lexicographically, '9' > '80' because the ASCII character '9' has a higher codepoint than '8':
>>> '9' > '80'
True
After the '9' line, all other lines either have an initial digit that is smaller than '9', or the line is equal.
You could use the max() function instead, provided you first use map() to turn all lines into integers:
with open('jan14.nSets.txt','r') as data:
i = max(map(int, data))
or use a generator expression (in Python 2, more memory efficient than map()):
with open('jan14.nSets.txt','r') as data:
i = max(int(num) for num in data)
Both pull in all lines from data, map the lines to integers, and determine the maximum value from those.

Related

How to print 6 rows of 7 numbers with user input

I must write a program that accepts a number, n, where -6 < n < 2. The program must print out the numbers n to n+41 as 6 rows of 7 numbers. The first row must contain the values n to n+6, the second, the values n+7 to n+7+6, and so on.
That is, numbers are printed using a field width of 2, and are right-justified. Fields are separated by a single space. There are no spaces after the final field.
Output:
Enter the start number: -2
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
The numbers need to be directly lined under each other.
I have absolutely no idea how to do this
This is my code so far:
start = int(input('Enter the start number: '))
for n in range(n,n+41):
If you could help me I will really appreciate it.
I assume you are not allowed to use a library to tabulate the numbers for you and are expected to do the logic yourself.
You need to print 6 rows of numbers. Start by determining the first number of each row. That is given by range(n,n+42,7) (note, not n+41). For starting value -2, those are the numbers -2, 5, 12, 19, 26, 33. Every other number in the row is just the next 6 integers. If the first number in the row is leftmost then the entire row is given by range(leftmost, leftmost + 7). So the first row those are the numbers -2, -1, 0, 1, 2, 3, 4.
To print 6 rows of 7 numbers you need a loop with 6 iterations, one for each value of leftmost. Inside that loop you print the other numbers. The only complication is all of the numbers in the list must be followed by a space, except the last. So that has to get special treatment.
You need to specify format {0:2d} to ensure that "numbers are printed using a field width of 2".
n = -2
for leftmost in range(n,n+42,7):
for value in range(leftmost,leftmost + 6):
print("{0:2d}".format(value), end=" ")
print("{0:2d}".format(leftmost+6))
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
check the tabulate library here, you can use it to format the output - the tablefmt="plain" parameter produces a very similar table.
If you store the numbers in a list you can use list slicing to get the rows of 7 numbers each and put those in an another list to satisfy the format that tabulate is expecting
from tabulate import tabulate
n = 2
while not -6 < n < 2:
n = int(input('Please submit a number greater than -6 and smaller than 2:\n'))
number_list, output_list = [], []
for i in range(42):
number_list.append(n + i)
for i in range(6):
output_list.append(number_list[i*7:i*7+7])
print()
print(
tabulate(
output_list,
tablefmt='plain'
)
)
Please submit a number greater than -6 and smaller than 2:
-3
-3 -2 -1 0 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
32 33 34 35 36 37 38

python script to find the unique value

I have a script to find the unique value from 2 files
1.csv
11 12 13 14
21 22 23 24
11 32 33 34
2.csv
41 42 43 44 45
51 52 53 54 55
41 62 63 64 65
script is:
import csv
import sys
# Count all first-column numbers.
counts = {}
# Loop over all input files.
for a in sys.argv[1:]:
# Open the file for reading.
with open(a) as c:
# Read it as a CSV file.
reader = csv.reader(c, delimiter=' ')
for row in reader:
count = counts.get(row[0], 0)
# Increment the count by 1.
counts[row[0]] = count + 1
# Print only those numbers that have a count of 1.
print([i for i, c in counts.items() if c == 1])
Usage:
$ python 1.py 1.csv 2.csv
output is
['51', '21']
but i want the output in different row like
51
21
Use string.join to join the list items on a \n:
l = ['51', '21']
print("\n".join(l))
Edit:
In your code (which actually is from an answer I gave you yesterday), do this:
print("\n".join([i for i, c in counts.items() if c == 1]))
Replace the last line by the following:
for result, count in counts.items():
if count == 1:
print(result)
It's not the most concise way to do it but at least it's quite readable

Difference between result in a returing a function and printing in Python IDE

given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. a being 1, b being 2, etc. As an example:
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (As a string.)
cc = "The sunset sets at twelve o' clock."
for i in cc:
if ord(i) >= 97 and ord(i) <= 122:
s = ord(i)-96,
print ''.join(map(str, s)),
elif ord(i)>=65 and ord(i) <= 90:
ss = ord(i)-64,
print ''.join(map(str, ss)),
Output: 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11
The error raised when used inside function:
def alphabet_position(text):
for i in text:
if ord(i) >= 97 and ord(i) <= 122:
s= ord(i)-96
return ''.join(map(str, s)),
elif ord(i) >= 65 and ord(i) <= 90:
ss= ord(i)-64
return ''.join(map(str, ss)),
is
Traceback (most recent call last):
File "/Users/greatergood/Desktop/acsii2.py", line 10, in <module>
print alphabet_position("The sunset sets at twelve o' clock.")
File "/Users/greatergood/Desktop/acsii2.py", line 8, in alphabet_position
return ''.join(map(str, ss)),
TypeError: argument 2 to map() must support iteration
Any help appreciated!
map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list. https://docs.python.org/2/library/functions.html#map
Your arguments s and ss are integers and therefore not iterable
Is this what you wanted to achieve?
def alphabet_position(text):
list_of_alphabet = []
for i in text:
if ord(i) >= 97 and ord(i) <= 122:
s = ord(i) - 96
list_of_alphabet.append(s)
elif ord(i) >= 65 and ord(i) <= 90:
ss = ord(i) - 64
list_of_alphabet.append(ss)
return list_of_alphabet
list_of_alphabet = alphabet_position("The sunset sets at twelve o' clock.")
print list_of_alphabet
Your non-function variant works by accident.
You have put a comma at the end of the assignments
s = ord(i)-96, and ss = ord(i)-64,
which makes both s and ss a tuple
and thus map works accidentally.
In your function version you omitted the dangling commas,
hence map stops working.
Compare these:
s = ord('t') - 96,
print type(s)
versus
s = ord('t') - 96
print type(s)
Note, that your code has a few other problems.
As mkiever says, your first version appears to work because you made s and ss into tuples. Even though we often write tuples with parentheses, they are actually created by the use of the comma. The parentheses are only needed when the code would be ambiguous without them.
It's not clear why you're doing map(str, s) though. map is used to apply a function to each item in an iterable, not to a single item. To convert a single integer like s to a string you can simply do str(s).
You can simplify your test by converting the letters to the same case, rather than handling upper and lower case separately.
def letter_ord(c):
return str(ord(c.upper()) - 64) if c.isalpha() else ''
cc = "The sunset sets at twelve o' clock."
a = [letter_ord(c) for c in cc]
print(' '.join([u for u in a if u]))
output
20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11
Or as a one-liner:
cc = "The sunset sets at twelve o' clock."
print(' '.join(filter(None, map(lambda c: str(ord(c.upper()) - 64) if c.isalpha() else '', cc))))

Python, Loops, Multiples

I cannot figure out what I am doing wrong; I keep getting a traceback error.
Can someone tell me what I am doing wrong or point me in the right direction, please?
Multiples = str(input('Multiples of 13 from 200 to 100'))
for counter in range(max):
for i in reversed(list(range(100,201))):
if i%13==0:
print(i,'total','*= 13')
list1 = {}
for j in list(range(2,i+1)):
if i%j == 00:
list1 = []
print(list1)
I am trying to get the output to look like the following:
Multiples of 13 from 200 to 100
195 = 13 times 15
182 = 13 times 14
169 = 13 times 13
156 = 13 times 12
143 = 13 times 11
130 = 13 times 10
117 = 13 times 9
104 = 13 times 8
Also, could someone tell me how to enter code in this block, because each time I click on the code or CTRL-K my format is off?
I feel like you're overcomplicating things..
output = []
x = 0
while True:
if 13 * x > 200:
break
output.append('{0} = 13 times {1}'.format(13*x, x))
x += 1
for x in reversed(output):
print(x)
Output
195 = 13 times 15
182 = 13 times 14
169 = 13 times 13
156 = 13 times 12
143 = 13 times 11
130 = 13 times 10
117 = 13 times 9
104 = 13 times 8
91 = 13 times 7
78 = 13 times 6
65 = 13 times 5
52 = 13 times 4
39 = 13 times 3
26 = 13 times 2
13 = 13 times 1
0 = 13 times 0
There are actually quite a few things that are preventing the output from looking like you want it to:
In Multiples = str(input('Multiples of 13 from 200 to 100')), asking for input prompts the user to input a number, and will then assign that input to Multiples.
You're not actually printing Multiples of 13 from 200 to 100.
max is not a number, so you can't call range on it. I've assumed you haven't defined max elsewhere, of course, so if you have, kindly update your code to include it.
print(i,'total','*= 13') will print <number> total *=13. This does not remotely resemble the output you want.
You never actually insert anything into list1 before printing it. Even if you did, it would appear inside a list so it would look like [<element>].
Since the code as provided is not a minimal complete and verifiable example that would let us pinpoint your exact error, I suspect you will need to rewrite your code from scratch - as written, none of it conforms to the output you want to get. This is far more complicated than it has to be in any case.
All you have to do is
Go through the numbers 201, 200, ... 100
Check if each number is divisible by 13
Use the handy division operator / to get the value of the number divided by 13 as a float (a decimal number) and convert it to integer by using int().
Here's a minimal example of the right way to do this:
print('Multiples of 13 from 200 to 100') # prints this string
for i in range(201,100,-1): # iterate through 201, 200, 199 ... 100
if i % 13 == 0: # checks if number is divisible by 13 ...
# prints out the result of number divided by 13 in the format you want
print(i, '= 13 times', int(i/13))

There is a 4 in my prime number list generated in Python

Here is my code.
#Prime numbers between 0-100
for i in range(2,100):
flg=0
for j in range(2,int(i/2)):
if i%j==0:
flg=1
break
if flg!=1:
print(i)
And the output is
2
3
4 <-
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
I have no idea why there is this 4.
Pardon me if i made some noobish mistake, as i can't seem to figure it out.
The reason is that range is not inclusive, i.e.
>>> range(2,2)
[]
So when you access 4, you don't check for divisors. Change for example to range(2,int(i/2)+1)
To speed up your calculation, you can use math.sqrt instead of /2 operation, for example as:
import math
and then
for j in range(2, int(math.sqrt(i)+1)):

Categories

Resources