I am trying to print out the output of the maximum route each in a separate line.
The code is here:
def triangle(rows):
PrintingList = list()
for rownum in range (rows ):
PrintingList.append([])
newValues = map(int, raw_input().strip().split())
PrintingList[rownum] += newValues
return PrintingList
def routes(rows,current_row=0,start=0):
for i,num in enumerate(rows[current_row]):
if abs(i-start) > 1:
continue
if current_row == len(rows) - 1:
yield [num]
else:
for child in routes(rows,current_row+1,i):
yield [num] + child
testcases = int(raw_input())
output = []
for num in range(testcases):
rows= int(raw_input())
triangleinput = triangle(rows)
max_route = max(routes(triangleinput),key=sum)
output.append(sum(max_route))
print '\n'.join(output)
I tried this:
2
3
1
2 3
4 5 6
3
1
2 3
4 5 6
When i try to output out the value, i get this:
print '\n'.join(output)
TypeError: sequence item 0: expected string, int found
How do change this? Need some guidance...
Try this:
print '\n'.join(map(str, output))
Python can only join strings together, so you should convert the ints to strings first. This is what the map(str, ...) part does.
#grc is correct, but instead of creating a new string with newlines, you could simply do:
for row in output:
print row
Related
I am practicing an algorithm on a website.
I want to add data(number) comma(,) every 3 digit.
But 'a', which variable I made, can't be the collect answer.
But 'b', which variable I searched, is the collect answer.
Can you tell me why 'a' is not the same as 'b'
length = 8
data = "12421421"
inv_result = []
for index in range(length):
if index % 3 == 0:
inv_result.append(',')
inv_result.append(str(data[index]))
else:
inv_result.append(str(data[index]))
result = inv_result[::-1]
#first comma delete
result.pop()
a = ''.join(result)
b = format(int(datas),",")
print(a)
print(b)
print(a == b)
result is
12,412,421
12,421,421
False
Your problem is that you didn't reverse the data in the beginning. The following (slightly cleaned up) code works:
length = 8
data = "12421421"
inv_data = data[::-1]
inv_result = []
for index in range(length):
if index % 3 == 0:
inv_result.append(',')
inv_result.append(str(inv_data[index]))
result = inv_result[::-1]
#first comma delete
result.pop()
a = ''.join(result)
b = format(int(data),",")
print(a)
print(b)
print(a == b)
because you are making it backwards with this line:
result = inv_result[::-1]
If you didn't reverse the order, then you would have the right order.
result = inv_result
result.pop(0) # remove first character which is a comma
But this only works if the number of digits is a multiple of three. For example, if your digits were 1234, then doing it this way would result in 123,4 instead of the desired 1,234.
So you have to reverse the string in the beginning or go through it in reverse order. Then leave the later inversion and pop() like you had it.
for index in range(length):
if index % 3 == 0:
inv_result.append(',')
inv_result.append(str(inv_data[-1-index]))# count from -1 to more negative, equivalent to going backwards through string
result = inv_result[::-1]
#first comma delete
result.pop()
A solution with comprehension:
data = "12421421"
len_data = len(data)
triplets_num = len_data // 3
remainder = len_data % 3
triplets = [data[:remainder]] if remainder else []
triplets += [data[remainder+i*3:remainder+3+i*3] for i in range(triplets_num)]
result = ','.join(triplets)
print(result)
def doorcheck(n):
doors = []
for i in range(n):
doors.append(False)
for i in range(n):
for x in range(n):
if (x+1) % (i+1) == 0:
if(doors[x] is False):
doors[x] = 1
else:
doors[x] = 0
for i in range(n-1):
print(doors[i], end = ' ')
print(doors[n-1], end = '\n')
t = int(input())
for i in range(t):
n = int(input())
doorcheck(n)
Here I am trying to print each desired output in a separate line.
As asked in the question
Example:
Input:
2
3
5
Output:
1 0 0
1 0 0 1 0
And I have used
for i in range(n-1):
print(doors[i], end = ' ')
print(doors[n-1], end = '\n')
the above code for this purpose. Is there a better way to do it?
Edit 1: The code above I wrote has a bug. But anyways #Barmar has given an excellent solution to my problem, which was about formatting output in a concise manner. And he also gave a suggestion for initializing an array which contains same element throughout its length. Thanks.
If you just want to print the elements of doors separated by spaces, use join()
print(' '.join(map(str, doors)))
You can also replace the loop that initializes doors with:
doors = [False] * n
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.
I get my data in python iterator where each line is a char separated by "\t".
I can create this like :
iter1 = []
str = ""
for j in range (0,3):
for i in range(0,9):
str += "1\t"
str += "1"
iter1.append(str)
str = ""
iter1 is looking like:
['1\t1\t1\t1\t1\t1\t1\t1\t1\t1', '1\t1\t1\t1\t1\t1\t1\t1\t1\t1', '1\t1\t1\t1\t1\t1\t1\t1\t1\t1']
Now, i want to join this iterator by "\n", but I also want that each "\t" will become "\n" so the final result would be :
1
1
1
1
1
1
After joining the iterator lines.
How can I do it in the fastest way?
You get tab-separated values in a list and want to convert all tabs to new-lines:
iter1 = ['\t'.join('1'*10) for _ in range(3)]
result = '\n'.join(iter1).replace('\t', '\n')
>>> iter1 = ['1\t1\t1\t1\t1',
'1\t1\t1\t1\t1',
'1\t1\t1\t1\t1']
>>> s = '\n'.join([char for line in iter1
for char in line.split('\t')])
>>> print s
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?