So, my question is simple. I'm simply struggling with syntax here. I need to read in a set of integers, 3, 11, 2, 4, 4, 5, 6, 10, 8, -12. What I want to do with those integers is place them in a list as I'm reading them. n = n x n array in which these will be presented. so if n = 3, then i will be passed something like this 3 \n 11 2 4 \n 4 5 6 \n 10 8 -12 ( \n symbolizing a new line in input file)
n = int(raw_input().strip())
a = []
for a_i in xrange(n):
value = int(raw_input().strip())
a.append(value)
print(a)
I receive this error from the above code code:
value = int(raw_input().strip())
ValueError: invalid literal for int() with base 10: '11 2 4'
The actual challenge can be found here, https://www.hackerrank.com/challenges/diagonal-difference .
I have already completed this in Java and C++, simply trying to do in Python now but I suck at python. If someone wants to, they don't have too, seeing the proper way to read in an entire line, say " 11 2 4 ", creating a new list out that line, and adding it to an already existing list. So then all I have to do is search said index of list[ desiredInternalList[ ] ].
You can split the string at white space and convert the entries into integers.
This gives you one list:
for a_i in xrange(n):
a.extend([int(x) for x in raw_input().split()])
and this a list of lists:
for a_i in xrange(n):
a.append([int(x) for x in raw_input().split()]):
You get this error because you try to give all inputs in one line. To handle this issue you may use this code
n = int(raw_input().strip())
a = []
while len(a)< n*n:
x=raw_input().strip()
x = map(int,x.split())
a.extend(x)
print(a)
Related
I want to count total number of '1's in binary format of a number which is in a list.
z = ['0b111000','0b1000011'] # z is a list
d = z.count('1')
print(d)
The output is 0.
Whereas the required output should be in the form of [3,3]
which is number of ones in every element that Z is containing :
Here it is :
z=['0b111000','0b1000011']
finalData = []
for word in z:
finalData.append(word.count('1'))
print(finalData)
The problem with your code was you were trying to use count() method on list type and it is used for string. You first need to get the string from the list and then use count() method on it.
Hope this helps :)
z = ['0b111000','0b1000011']
d = z.count('1')
This attempts to find the number of times the string '1' is in z. This obviously returns 0 since z contains '0b111000' and '0b1000011'.
You should iterate over every string in z and count the numbers of '1' in every string:
z = ['0b111000','0b1000011']
output = [string.count('1') for string in z]
print(output)
# [3, 3]
list.count(x) will count the number of occurrences such that it only counts the element if it is equal to x.
Use list comprehension to loop through each string and then count the number of 1s. Such as:
z = ['0b111000','0b1000011']
d = [x.count("1") for x in z]
print(d)
This will output:
[3, 3]
I have started learning python and using online interpreter for python 2.9-pythontutor
x=5,6
if x==5:
print "5"
else:
print "not"
It goes in else loop and print not.
why is that?
what exactly x=5,6 means?
, is tuple expr, where x,y will return a tuple (x,y)
so expression 5,6 will return a tuple (5,6)
x is nether 5 nor 6 but a tuple
When you declared x = 5, 6 you made it a tuple. Then later when you do x == 5 this translates to (5, 6) == 5 which is not true, so the else branch is run.
If instead you did x[0] == 5 that would be true, and print 5. Because we are accessing the 0 index of the tuple, which is equal to 5. Check out some tutorials on tuples for more info.
In Python when you write x = 4, 5, it is same as declaring a tuple as x = (4, 5). In interpreter, if you write:
>>> x = 4, 5
>>> x
(4, 5)
Hence, it is similar to comparing a tuple with an int.
X here acts as an array, where x is pointed to the first element of the array as x [0] = 5 and x [1] = 6
Execute this code, and the display will be 5
x=5,6
if x[0]==5:
print "5"
else:
print "not"
and try to See this link "http://www.pythontutor.com/visualize.html#mode=edit " you can run your code python step by step
I am trying to extract particular lines from txt output file. The lines I am interested in are few lines above and few below the key_string that I am using to search through the results. The key string is the same for each results.
fi = open('Inputfile.txt')
fo = open('Outputfile.txt', 'a')
lines = fi.readlines()
filtered_list=[]
for item in lines:
if item.startswith("key string"):
filtered_list.append(lines[lines.index(item)-2])
filtered_list.append(lines[lines.index(item)+6])
filtered_list.append(lines[lines.index(item)+10])
filtered_list.append(lines[lines.index(item)+11])
fo.writelines(filtered_list)
fi.close()
fo.close()
The output file contains the right lines for the first record, but multiplied for every record available. How can I update the indexing so it can read every individual record? I've tried to find the solution but as a novice programmer I was struggling to use enumerate() function or collections package.
First of all, it would probably help if you said what exactly goes wrong with your code (a stack trace, it doesn't work at all, etc). Anyway, here's some thoughts. You can try to divide your problem into subproblems to make it easier to work with. In this case, let's separate finding the relevant lines from collecting them.
First, let's find the indexes of all the relevant lines.
key = "key string"
relevant = []
for i, item in enumerate(lines):
if item.startswith(key):
relevant.append(item)
enumerate is actually quite simple. It takes a list, and returns a sequence of (index, item) pairs. So, enumerate(['a', 'b', 'c']) returns [(0, 'a'), (1, 'b'), (2, 'c')].
What I had written above can be achieved with a list comprehension:
relevant = [i for (i, item) in enumerate(lines) if item.startswith(key)]
So, we have the indexes of the relevant lines. Now, let's collected them. You are interested in the line 2 lines before it and 6 and 10 and 11 lines after it. If your first lines contains the key, then you have a problem – you don't really want lines[-1] – that's the last item! Also, you need to handle the situation in which your offset would take you past the end of the list: otherwise Python will raise an IndexError.
out = []
for r in relevant:
for offset in -2, 6, 10, 11:
index = r + offset
if 0 < index < len(lines):
out.append(lines[index])
You could also catch the IndexError, but that won't save us much typing, as we have to handle negative indexes anyway.
The whole program would look like this:
key = "key string"
with open('Inputfile.txt') as fi:
lines = fi.readlines()
relevant = [i for (i, item) in enumerate(lines) if item.startswith(key)]
out = []
for r in relevant:
for offset in -2, 6, 10, 11:
index = r + offset
if 0 < index < len(lines):
out.append(lines[index])
with open('Outputfile.txt', 'a') as fi:
fi.writelines(out)
To get rid of duplicates you can cast list to set; example:
x=['a','b','a']
y=set(x)
print(y)
will result in:
['a','b']
I want to create a list and fill it with 15 zeros, then I want to change the 0 to 1 in 5 random spots of the list, so it has 10 zeros and 5 ones, here is what I tried
import random, time
dasos = []
for i in range(1, 16):
dasos.append(0)
for k in range(1, 6):
dasos[random.randint(0, 15)] = 1
Sometimes I would get anywhere from 0 to 5 ones but I want exactly 5 ones,
if I add:
print(dasos)
...to see my list I get:
IndexError: list assignment index out of range
I think the best solution would be to use random.sample:
my_lst = [0 for _ in range(15)]
for i in random.sample(range(15), 5):
my_lst[i] = 1
You could also consider using random.shuffle and use the first 5 entries:
my_lst = [0 for _ in range(15)]
candidates = list(range(15))
random.shuffle(candidates)
for i in candidates[0:5]:
my_lst[i] = 1
TL;DR: Read the the Python random documentation, this can be done in multiple ways.
When i execute this testing code below, i get the error below it:
my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_input = input("Pick a number from 1 to 10?")
number_index = my_numbers.index(my_input)
print(number_index)
ERROR-----
number_index = my_numbers.index(my_input) ValueError: '1' is not in
list
is this python? if so, look like is python 3, then the error is simple: input give you a string, and you have a list of integers and no integer is going to be equal to a string, ever, so when you pass my_input, a string, to index it search in the list my_numbers for a match but all the things inside it are integer so it fail and give the error. The solution is simple transform the input to a integer like this:
my_input = int( input("Pick a number from 1 to 10?") )
the same apply to other languages but the fine details may vary...