Unexplained syntax/EOF errors - python

I keep getting syntax errors in my print command (that's why the bracket is on the one at the bottom) and I also get an End of File error (unexpected end of file while parsing) if I try to run the code.
I put a bracket on the print statement, and I have tried re-typing the code with no success.
print ("input a number")
a = (str(input(''))
if 9 in (a)
(b = a.count('9')
if 8 in (a)
(c = a.count('8')
if 7 in (a)
(d = a.count('7')
if 6 in (a)
(e = a.count('6')
if 5 in (a)
(f = a.count('5')
if 4 in (a)
(g = a.count('4')
if 3 in (a)
(h = a.count('3')
if 2 in (a)
(i = a.count('2')
if 1 in (a)
(j = a.count('1')
if 0 in (a)
(k = a.count('0')
(print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
File "/home/ubuntu/workspace/SuPeRsIzE.py", line 26
^
SyntaxError: unexpected EOF while parsing
Notice the code is only 25 lines long - I haven't even opened it to 26 lines
---------------------------------------------------------------------------
File "/home/ubuntu/workspace/SuPeRsIzE.py", line 25
print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
^
SyntaxError: invalid syntax
This is what I get if I remove the bracket from the print statement.

So, the syntax error is actually because you're not ending your if statements with : and also you have a bunch of open brackets on each line in the if blocks. You may want to look at a tutorial for basic Python syntax.
The reason the syntax error doesn't happen immediately is because of how Python works. If we remove the linebreaks:
if 9 in (a)(b = a.count('9') if 8 in (a)(c = a.count('8') ...
What this does is it tries to test if 9 is in the right expression, which is a function call. It tries to call a as a function with the keyword argument b equal to a.count('9') if <expr> else <expr>, which is Python's ternary expression syntax. At the very end, it says "unexpected EOF" because it's expecting more close brackets because you open a lot of brackets that shouldn't even be there in the first place. If you put them all in, it says "invalid syntax" because it wants else statements to complete the ternary expressions.

This code is very confusing but addressing the syntax errors:
All of your if lines need to end with :
if 4 in (a) # missing : at the end
should be
if 4 in a:
Every if body starts with ( but isn't closed
(b = a.count('9')
should be
b = a.count('9')
You will be printing variables that you never assigned to, unless every if check is independently true. so I would recommend at least removing all the if checks and making it flat
b = a.count('9')
c = a.count('8')
d = a.count('7')
e = a.count('6')
f = a.count('5')
g = a.count('4')
h = a.count('3')
i = a.count('2')
j = a.count('1')
k = a.count('0')
print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
but I don't think this will produce the correct answer, though it's hard to see what your goal is.
These aren't errors, but you don't need the extra () around input and print. input() also supports taking a string to display
a = input('input a number: ')
# ...
print('the highest number...')
Update for comment explaining that the goal is to rearrange.
The simplest way is using the python sorted and then joining the result back to a single string
a = input('input a number: ')
highest = ''.join(sorted(a, reverse=True))
print('The highest number you can make is', highest)
However, if you want to keep your existing approach with all the variables, you need only replace the ints in your print with str by quoting them, and using sep='' to remove the spaces in between
print("the highest number you can make is ",
'9'*b, '8'*c, '7'*d, '6'*e, '5'*f, '4'*g,
'3'*h, '2'*i, '1'*j, '0'*k,
sep='')
A more imperative, but less repetitive approach would be to build up a result string as you went
a = input('input a number: ')
result = ''
for i in range(10, -1, -1):
count = a.count(str(i))
result += count * str(i)
print("the highest number you can make is", result)

b = a.count('9')
c = a.count('8')
d = a.count('7')
e = a.count('6')
f = a.count('5')
g = a.count('4')
h = a.count('3')
i = a.count('2')
j = a.count('1')
k = a.count('0')
´
print("the highest number you can make is", ´9´*b, ´8´*c, ´7´*d, ´6´*e, ´5´*f, ´4´*g, ´3´*h, ´2´*i, ´1´*j, ´0´*k)
this seems to work fine - thanks for the help everybody but this works for my purposes

Related

Hacker rank string separated challenge

I'm trying to solve a hacker rank challenge:
Given a string, s , of length n that is indexed from 0 to n-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings. on a single line (see the Sample below for more detail)
link: https://www.hackerrank.com/challenges/30-review-loop/problem
Error:
for example:
The input "adbecf" should output "abc def"
When I run python Visualizer my code seem to have the correct output.. but on hacker rank it's saying I have the wrong answer. Does anyone know what might be wrong with my code.
This is the code I tried -
class OddEven:
def __init__(self, input_statement):
self.user_input = input_statement
def user_list(self):
main_list = list(user_input)
even = []
odd = []
space = [" "]
for i in range(len(main_list)):
if (i%2) == 0:
even.append(main_list[i])
else:
odd.append(main_list[i])
full_string = even + space + odd
return(full_string)
def listToString(self):
my_string = self.user_list()
return(''.join(my_string))
if __name__ == "__main__":
user_input = str(input ())
p = OddEven(user_input)
print(p.listToString())
First of all, input is always string, you don't need to convert it here.
user_input = str(input())
Each line is provided to you as separate input. Number of strings equal to num in the first line. In this case 2, so...
count = input()
for s in range(int(count)):
...
user_input variable inside user_list function should be accessed as self.user_input, it's a property of an object, which you pass to function as self.
Also you can iterate over list directly.
Here:
full_string = even + space + odd
you're trying to concatenate list, which is not a good idea, you'll still get a list.
You can join list with separating them with some string using join string method.
' '.join(list1, list2, ..., listN)
It's better do define odd and even as empty strings.
And then join them the using concatenation (+).
Here:
if (i%2) == 0
you don't have to compare with 0. Python will evaluate what's to the right from condition as True or False. So:
if i % 2:
...
There is simpler solution:
def divide(self):
odd = even = ''
for i, c in enumerate(self.user_input):
if i % 2:
odd += c
else:
even += c
return even + ' ' + odd
Here is the simple code for this problem:)
T=int(input())
for i in range(0,T):
S=input()
print(S[0::2],S[1::2])

Brute force solution without itertools in Python

I'm new to Python.
I'm trying to calculate 3 ** 16 (¹[0-f], ²[0-f], ³[0-f])
but it's not working properly.
This is my code:
inp = str(input('value len 0-3 digit:'))
hexa = ('0123456789abcdef');
#len(hexa) = 16 digit
#pass = '36f'
pass = inp
for x in range(0, 3 ** len(hexa)):
#range = 0..(3 ^ 16)
if(hexa[x] == pass):
found = hexa[x]
#if result valid
print("pos: %d, pass: %s" % (x, found))
#print position
I got the error "index out of bound".
I need output like this:
000 #first
001
002
...
...
36f #found then break
...
...
fff #last
How do I fix it?
I believe your IndexError: string index out of range error comes from this logic:
for x in range(0, 3 ** len(hexa)):
Which probably should be:
for x in range(len(hexa) ** len(inp)):
A much smaller number. This is never going to work on input of more than one digit:
if(hexa[x] == pass):
You need to rethink this. Using Python's own hex() function, I came up with an approximation of what I'm guessing you're trying to do:
hexadecimal = input('hex value of 1-3 digits: ').lower()
hex_digits = '0123456789abcdef'
for x in range(len(hex_digits) ** len(hexadecimal)):
if hex(x) == "0x" + hexadecimal:
print("pos: %d, pass: %s" % (x, hexadecimal))
break
OUTPUT
> python3 test.py
hex value of 1-3 digits: 36f
pos: 879, pass: 36f
>
If that's not what you're trying to do, please explain further in your question.
Other issues to consider: don't use pass as the name of a variable, it's a Python keyword; input() returns a str, you don't need to call str on it; avoid semicolons (;) in Python.

Difficulty in inserting newline character into Python string after conversion from list form

The code I'm working on takes an input, and is meant to return a "staircase" of hashes and spaces. For instance, if the input was 5, the result should be:
#
##
###
####
#####
I've turned the input into a list of spaces and hashes, and then converted that to a string form, in order to insert \n in every space corresponding to the length of the input (e.g. every 5 characters above). However, my code prints the result in one line. Where am I going wrong??
x = input()
list = []
a = x-1
while a > -1:
for i in range(0, a):
list.append(" ")
for i in range(0, (x-a)):
list.append("#")
a = a - 1
continue
z = str("".join(list))
t = 0
while t<x:
z = z[t:] + "\n" + z[:t]
t = t + x
continue
print str(z)
Start with pseudocode, carefully laying out in clear English what you want the program to do.
Get a number from the user.
Go through each number from 1 until the user's number, inclusive.
On each line, print a certain number of spaces, starting from one fewer than the user's number and going down to zero, inclusive.
On each line, also print a certain number of hash symbols, starting from one and going up to the user's number, inclusive.
Now you can turn that into Python.
First, get a number from the user. It looks like you're using Python 2, so you could use input() or try the safer raw_input() and cast that to int().
num = input()
Going through each number from one until the user's number, inclusive, means a for loop over a range. On Python 2, using xrange() is better practice.
for i in xrange(1, num+1):
This next part will combine steps 3 and 4, using string multiplication and concatenation. For the spaces, we need a number equal to the max number of lines minus the current line number. For the hash symbols, we just need the current line number. You can multiply a string to repeat it, such as 'hi' * 2 for 'hihi'. Finally, the newline is taken care of automatically as the default end character in a Python 2 print statement.
print ' ' * (num-i) + '#' * i
Put it all together and it looks like this:
num = input()
for i in xrange(1, num+1):
print ' ' * (num-i) + '#' * i
As you discovered, achieving the same effect with an intricate structure of counters, nested loops, list operations, and slicing is more difficult to debug. The problems don't stop when you get it working properly, either - such code is difficult to maintain as well, which is a pain if you ever want to modify the program. Take a look at the official Python tutorial for some great examples of clear, concise Python code.
Try this
x = input()
list1 = []
a = x-1
while a > -1:
for i in range(0, a):
list1.append(" ")
for i in range(0, (x-a)):
list1.append("#")
a = a - 1
list1.append("\n")
continue
z = str("".join(list1))
print z

Stdin issues using Python

I recently participated in hackathon for the first time and got stuck on the first problem. I solved the algorithm, but couldn't figure out how to take values from stdin using Python. This is the question:
There are two college students that want to room together in a dorm. There are rooms of various sizes in the dormitory. Some rooms can accomodate two additional students while others cannot.
Input: the first input line will be a number n (1 ≤ n ≤ 100), which is the total number of rooms in the dorm. There will be n lines following this, where each line contains two numbers, p and q (0 ≤ p ≤ q ≤ 100). P is the number students already in the room, while q is the maximum number of students that can live in the room.
Output: print the number of rooms that the two students can live in.
This is my solution. I've tested it using raw_input() and it works perfectly on my interpreter, but when I change it to just input() I get an error message.
def calcRooms(p, q):
availrooms = 0
if q - p >= 2:
availrooms += 1
return availrooms
def main():
totalrooms = 0
input_list = []
n = int(input())
print n
while n > 0:
inputln = input().split() #accepts 2 numbers from each line separated by whitespace.
p = int(inputln[0])
q = int(inputln[1])
totalrooms += calcRooms(p, q)
n -= 1
return totalrooms
print main()
The error message:
SyntaxError: unexpected EOF while parsing
How do I accept data correctly from stdin?
In this particular case, use raw_input to take the entire line as string input.
inputln = raw_input().split()
This takes input line as a string and split() method splits the string with space as delimiter and returns a list inputln
The following code works the way you wanted.
def main():
totalrooms = 0
input_list = []
#n = int(input("Enter the number of rooms: "))
n = input()
while n > 0: # You can use for i in range(n) :
inputln = raw_input().split() #Converts the string into list
p = int(inputln[0]) #Access first element of list and convert to int
q = int(inputln[1]) #Second element
totalrooms += calcRooms(p, q)
n -= 1
return totalrooms
Or, alternatively you may use fileinput.
If input file is not passed as command line argument, stdin will be the default input stream.
import fileinput
for line in fileinput.input() :
#do whatever with line : split() or convert to int etc
Please refer : docs.python.org/library/fileinput.html
Hope this helps, drop comments for clarification if needed.

New to python (and programming) need some advice on arranging things diagonally

I'm finishing up an assignment for my 1035 computer science lab and the last thing I need to do is arrange inputted numbers in a diagonal line.
I've tried things like:
print (\tnum2)
and like this:
print ('\t'num2)
but I can't figure out how to do it. I've looked through my programming book, but have been unable to find an explanation on how to do it.
strings in python can be concatenated using the + sign. For example
print(' ' + str(a))
will give the following output for a=1
1
Notice the single blank space before 1. The function str(a) returns the integer a in string format. This is because print statement can only print strings, not integers.
Also
print(' ' * i)
prints i blank spaces. If i = 10, then 10 blank spaces will be printed.
So, the solution to the question can be:
a = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(a)):
print((' ' * i) + str(a[i]))
Here's a simple example that prints items in a list on a diagonal line:
>>> l = [1,2,3,4,5]
>>> for i in range(len(l)):
... print("\t" * i + str(l[i]))
...
1
2
3
4
5
You can also do it using .format
nome = input("nome:")
a = " "
b = len(nome)
for i in range(b):
print ("{0} {1}".format(a * i, nome[i]))
print ("\n next \n")
c=b
for i in range(b):
print ("{0} {1}".format(a * c, nome[i]))
c = c-1
this give diagonal increasing or decreasing

Categories

Resources