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.
Related
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
I wanna ask how to convert an integer into string without using in-built function.
This is the original question:
Write a function string(ls) that returns a string representation of the list ls.
Note: do not use the built-in str() method for this task. We are attempting to emulate its behavior.
s = string(['a','b','c']) # '['a','b','c']'
s = string([1,2,3]) # '[1, 2, 3]'
s = string([True]) # '[True]'
s = string([]) # '[]'
Restrictions: Don't just return str(ls)! Don't use the str.join method, don't use slicing.
Here is my code:
def string(ls):
if len(ls)==0:
mess="'[]'"
return mess
elif isinstance(ls[0],str):
i=0
mess="'["
while True:
if i==len(ls)-1:
elem="'"+ls[i]+"'"
mess=mess+elem
break
else:
elem="'"+ls[i]+"', "
mess=mess+elem
i=i+1
mess=mess+"]'"
return mess
else:
i=0
mess="'["
while True:
if i==len(ls)-1:
elem=str(ls[i])+"]'"
mess=mess+elem
break
else:
elem=str(ls[i])+', '
mess=mess+elem
i=i+1
return mess
You can keep dividing a given integer by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function:
def int_to_string(i):
string = ''
while True:
i, remainder = divmod(i, 10)
string = chr(ord('0') + remainder) + string
if i == 0:
break
return string
so that:
print(int_to_string(0))
print(int_to_string(5))
print(int_to_string(65))
print(int_to_string(923))
would output:
0
5
65
923
This should work? I am fairly new so i do not know why your codes are so complicated.This should work too.
def int_to_string(i):
string = chr(ord("0") + i)
return string
I have a string as an input for the code I'm writing and let an example of the string be:
"12 inches makes 1 foot"
My goal is to have my code run through this string and just pull out the integers and add them. So the output for the string above would be 13. I am using try and except in here as well since another sample input string could be something like "pi is 3.14".
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
if a == int(a):
a= int(a)
thesum += a
print (thesum)
except ValueError as e:
print("Value Error: no int present")
I did what is above and I am not getting it to add the value of a (if it is an int) to "thesum". How can I get this to work? Also, I do want to have it in the try, except format so that I can call the ValueError
There is no need to check equality with a string. In fact, just try '4' == 4 in an interpreter. The answer is False because strings and integers are never equivalent. Just put thesum += int(a) into the loop instead of your if statement. If you don't want try-except, use if a.isdigit(): instead of try: and take out except: altogether:
for a in s:
if a.isdigit():
thesum += int(a)
print(thesum)
A good way would be the combination of several built-ins:
string = "12 inches makes 1 foot"
total = sum(map(int, filter(str.isdigit, string.split())))
filter() finds only the characters that are digits. We then convert each to an integer with map() and find the total with sum().
a is str, and int(a) is int(if possible), so a == int(a) will never equal.
just add the value of int(a), if the convert fails, it will raise ValueError.
The following codes should work.
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
thesum += int(a)
except ValueError as e:
print a
print thesum
I like "re" and comprehension to make it easier to read:
import re
print(sum(int(a) for a in re.findall(r'\d+', '12 inches make 1 foot')))
Then you can extend the regular expression for floats, etc.
Most of the earlier approaches discount the second input which is "pi is 3.14". Although question has been asked with stated assertion of parsing integer. It requires treatment of numbers as float to successfully process second input.
import unittest
import re
def isDigit(s):
return re.match(r'[\d.]+', s)
def stringParse(input):
input = [i.strip() for i in input.split()]
input = filter(lambda x: isDigit(x), input)
input = map(lambda x: float(x), input)
return sum(input)
class TestIntegerMethods(unittest.TestCase):
def test_inches(self):
self.assertEqual(stringParse("12 inches makes 1 foot"), 13.0)
def test_pi(self):
self.assertTrue(stringParse('pi is 3.14'), 3.14)
if __name__ == '__main__':
unittest.main()
Another take on the problem
Wanted to see if I'm going in the right direction. I have to change everything but the last four characters of a string into #. I've got two ideas so far.
First one:
def maskify(cc):
cc = raw_input("Enter passcode: ")
n = len(cc)
cc.replace(cc[0:n-4], #) # this one gives me the unexpected EOF while parsing error
Second one (I think this one's closer because it supposedly needs an algorithm):
def maskify(cc):
cc = raw_input("Enter passcode: ")
n = len(cc)
for i in range (0, n-4): # i think a for loop would be good but i don't know how i'm going to use it yet
cc.replace( #not entirely sure what to put here
pass
cc = raw_input("Enter passcode: ")
cc = ''.join(('#' * (len(cc) - 4), cc[-4:]))
The problem in the first example is that the # is unquoted. You need to change it to '#' otherwise it is parsed as the start of a comment and the enclosing parenthesis is a part of that comment. Although, this will only fix the parsing error.
The problem with strings is that you can't change characters inside of them (they are immutable). A common way to get around this is to create an array of the string, change the characters you want to change and then convert the array back to a string (often using ''.join(character_array)). Try that!
How about the following?
def maskify() :
cc = input("Enter passcode: ")
mask = '#'*(len(cc)-4)
return mask + cc[-4:]
I'm not sure how the flow of the rest of your program works, but I doubt whether you should be prompting for raw_input inside of this function. You can decide that depending on your needs. The alternative would look something like this:
def maskify(cc) :
return '#'*(len(cc)-4) + cc[-4:]
myInput = input("Enter passcode: ")
maskedInput = maskify( myInput )
NB: python2 uses raw_input instead of input
Just a little change to your own code:
cc = raw_input("Enter passcode: ")
n = len(cc)
c=""
for i in range(0, n-4): # i think a for loop would be good but i don't know how i'm going to use it yet
c+="#" #not entirely sure what to put here
cc= c+cc [-4:]
print cc
output:
Enter passcode: kased
#ased
The following solution makes the assumption that this would have a security type use, as such passcodes of 4 or fewer characters should just be hashed, otherwise someone would know the whole passcode.
def maskify(cc):
if len(cc) < 9:
split = [0,1,2,3,4,4,4,4,4][len(cc)]
else:
split = len(cc) - 4
return "#" * split + cc[split:]
for length in range(1,12):
test = string.lowercase[:length]
print "%s > %s" % (test, maskify(test))
Giving the following results:
a > #
ab > ##
abc > ###
abcd > ####
abcde > ####e
abcdef > ####ef
abcdefg > ####efg
abcdefgh > ####efgh
abcdefghi > #####fghi
abcdefghij > ######ghij
abcdefghijk > #######hijk
If the short hash is not required, then simply change the array as follows to get the other results:
def maskify(cc):
if len(cc) < 9:
split = [0,0,0,0,0,1,2,3,4][len(cc)]
else:
split = len(cc) - 4
return "#" * split + cc[split:]
Giving:
a > a
ab > ab
abc > abc
abcd > abcd
abcde > #bcde
abcdef > ##cdef
abcdefg > ###defg
abcdefgh > ####efgh
abcdefghi > #####fghi
abcdefghij > ######ghij
abcdefghijk > #######hijk
The string literal '#' is not the same as the character # which starts an inline comment.
def maskify(cc):
cc = raw_input("Enter passcode: ")
mask = '#'*(len(cc)-4)
return mask + cc[-4:]
As others have mentioned # starts a comment. If you want a string containing a hash you need to do '#'.
As André Laszlo mentioned, Python strings are immutable, so it's impossible for a string operation to change a string's content. Thus the str.replace() method can't change the original string: it needs to create a new string which is a modified version of the original string.
So if you do
cc = 'cat'
cc.replace('c', 'b')
then Python would create a new string containing 'bat' which would get thrown away because you're not saving it anywhere.
Instead, you need to do something like
cc = 'cat'
cc = cc.replace('c', 'b')
This discards the original string object 'cat' that was bound to the name cc and binds the new string 'bat' to it.
The best approach (AFAIK) to solving your problem is given in bebop's answer. Here's a slightly modified version of bebop's code, showing that it handles short strings (including the empty string) correctly.
def maskify(s) :
return '#' * (len(s) - 4) + s[-4:]
alpha = 'abcdefghij'
data = [alpha[:i] for i in range(len(alpha)+1)]
for s in data:
print((s, maskify(s)))
output
('', '')
('a', 'a')
('ab', 'ab')
('abc', 'abc')
('abcd', 'abcd')
('abcde', '#bcde')
('abcdef', '##cdef')
('abcdefg', '###defg')
('abcdefgh', '####efgh')
('abcdefghi', '#####fghi')
('abcdefghij', '######ghij')
First of all strings are immutable(they can't be changed) once created--so you can't change the value of cc with replace(). To change all parts of the string except the last four, do this:
def doso(text):
assert len(str(text))>4, 'Length of text should be >4'
ctext=str(text).replace(str(text)[:(len(str(text))-4)],'#'*(len(str(text))-4))
print(ctext)
>>>doso(123) prints 'Length of text should be >4' because len(text)== 3 which is what we expect
Hovever,
>>>doso(12345678) prints #####6789 which is exactly what we expect
Note: Doing '#' * (len(str(text))-4)) accounts for the number of characters we want to replace
# return masked string
def maskify(cc):
maskify = cc
maskifyL= len(maskify) - 4
char = ""
a=0
if maskifyL <= 2:
c2 = cc
else:
for a in range(maskifyL):
char += "#"
a += 1
c2 = maskify.replace(maskify[:maskifyL], char, maskifyL)
return c2
I'm new to Python and just playing around with some code. I am trying to build a "secret message generator" which takes a string (e.g. "1234567890") and outputs it based on a simple pattern (e.g. "1357924680"). I have the encoder working 90% (currently it can't handle apostrophes), but the decoder is giving me a lot of trouble. For anything over 6 characters, there is no problem. Inputting "1357924680" outputs "1234567890". However, for shorter odd numbered strings (e.g. "Hello"), it does not show the last character (e.g. it outputs "Hell"). My code is below. There may be a simpler way to write it, but since I built this myself, I'd appreciate working with my code rather than rewriting It. So, how can it be fixed?
#simple decoder
def decode(s2):
oddlist = []
evenlist = []
final = []
s2 = s2.lower() #makes a string lowercase
size = len(s2) #gets the string size
print "Size " + str(size) #test print
half = size / 2
print "Half " + str(half)
i = 0
while i < half:
if size % 2 == 0: #checks if it is even
split = size / 2 #splits it
oddlist.append(s2[0:split]) #makes a list of the first half
evenlist.append(s2[split:]) #makes a list of the second half
joinodd = ''.join(oddlist) #list -> string
joineven = ''.join(evenlist) #list -> string
else:
split = (size / 2) + 1
print split
oddlist.append(s2[0:split]) #makes a list of the first half
evenlist.append(s2[split:]) #makes a list of the second half
joinodd = ''.join(oddlist) #list -> string
joineven = ''.join(evenlist) #list -> string
string = joinodd[i] + joineven[i]
final.append(string)
i = i + 1
decoded = ''.join(final)
print final
return decoded
print decode("hello")
Maybe another answer will give you the error in your code but I want to make you a recommendation, if you are using python slice notation, use it ALL! This is an example of how you can do what you want in a more pythonic way:
import itertools
def encode(s):
return s[::2] + s[1::2]
def decode(s):
lim = (len(s)+1)/2
return ''.join([odd + even for odd,even in itertools.izip_longest(s[:lim], s[lim:],fillvalue="")])
def test(s):
print "enc:",encode(s)
print "dec:",decode(encode(s))
print "orig:",s
print
test("")
test("1")
test("123")
test("1234")
test("1234567890")
test("123456789")
test("Hello")
Output:
enc:
dec:
orig:
enc: 1
dec: 1
orig: 1
enc: 132
dec: 123
orig: 123
enc: 1324
dec: 1234
orig: 1234
enc: 1357924680
dec: 1234567890
orig: 1234567890
enc: 135792468
dec: 123456789
orig: 123456789
enc: Hloel
dec: Hello
orig: Hello
Your code is splitting the text into groups of two.
Which doesn't really work with words of odd length. So either you are skipping over one with
while i < half:
> ['hl', 'eo']
Or you make sure that you are getting all values with:
while i <= half:
> ['hl', 'eo', 'll']
Though this adds an extra letter to the output since it's technically adding another pair. You might need to re-think that algorithm.