Python ord() and chr() - python-3.x

I have:
txt = input('What is your sentence? ')
list = [0]*128
for x in txt:
list[ord(x)] += 1
for x in list:
if x >= 1:
print(chr(list.index(x)) * x)
As per my understanding this should just output every letter in a sentence like:
))
111
3333
etc.
For the string "aB)a2a2a2)" the output is correct:
))
222
B
aaaa
For the string "aB)a2a2a2" the output is wrong:
)
222
)
aaaa
I feel like all my bases are covered but I'm not sure what's wrong with this code.

When you do list.index(x), you're searching the list for the first index that value appears. That's not actually what you want though, you want the specific index of the value you just read, even if the same value occurs somewhere else earlier in the list too.
The best way to get indexes along side values from a sequence is with enuemerate:
for i, x in enumerate(list):
if x >= 1:
print(chr(i) * x)
That should get you the output you want, but there are several other things that would make your code easier to read and understand. First of all, using list as a variable name is a very bad idea, as that will shadow the builtin list type's name in your namespace. That makes it very confusing for anyone reading your code, and you even confuse yourself if you want to use the normal list for some purpose and don't remember you've already used it for a variable of your own.
The other issue is also about variable names, but it's a bit more subtle. Your two loops both use a loop variable named x, but the meaning of the value is different each time. The first loop is over the characters in the input string, while the latter loop is over the counts of each character. Using meaningful variables would make things a lot clearer.
Here's a combination of all my suggested fixes together:
text = input('What is your sentence? ')
counts = [0]*128
for character in text:
counts[ord(character)] += 1
for index, count in enumerate(counts):
if count >= 1:
print(chr(index) * count)

Related

trouble with tripling letters [duplicate]

How can I iterate over a string in Python (get each character from the string, one at a time, each time through a loop)?
As Johannes pointed out,
for c in "string":
#do something with c
You can iterate pretty much anything in python using the for loop construct,
for example, open("file.txt") returns a file object (and opens the file), iterating over it iterates over lines in that file
with open(filename) as f:
for line in f:
# do something with line
If that seems like magic, well it kinda is, but the idea behind it is really simple.
There's a simple iterator protocol that can be applied to any kind of object to make the for loop work on it.
Simply implement an iterator that defines a next() method, and implement an __iter__ method on a class to make it iterable. (the __iter__ of course, should return an iterator object, that is, an object that defines next())
See official documentation
If you need access to the index as you iterate through the string, use enumerate():
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
Even easier:
for c in "test":
print c
Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.
i = 0
while i < len(str):
print str[i]
i += 1
But then again, why do that when strings are inherently iterable?
for i in str:
print i
Well you can also do something interesting like this and do your job by using for loop
#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
print ( name[index] ) #just like c and c++
Answer is
M r . S u r y a a
However since range() create a list of the values which is sequence thus you can directly use the name
for e in name:
print(e)
This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.
We have used tow Built in Functions ( BIFs in Python Community )
1) range() - range() BIF is used to create indexes
Example
for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4
2) len() - len() BIF is used to find out the length of given string
If you would like to use a more functional approach to iterating over a string (perhaps to transform it somehow), you can split the string into characters, apply a function to each one, then join the resulting list of characters back into a string.
A string is inherently a list of characters, hence 'map' will iterate over the string - as second argument - applying the function - the first argument - to each one.
For example, here I use a simple lambda approach since all I want to do is a trivial modification to the character: here, to increment each character value:
>>> ''.join(map(lambda x: chr(ord(x)+1), "HAL"))
'IBM'
or more generally:
>>> ''.join(map(my_function, my_string))
where my_function takes a char value and returns a char value.
Several answers here use range. xrange is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange is superior.
You can also do the following:
txt = "Hello World!"
print (*txt, sep='\n')
This does not use loops but internally print statement takes care of it.
* unpacks the string into a list and sends it to the print statement
sep='\n' will ensure that the next char is printed on a new line
The output will be:
H
e
l
l
o
W
o
r
l
d
!
If you do need a loop statement, then as others have mentioned, you can use a for loop like this:
for x in txt: print (x)
If you ever run in a situation where you need to get the next char of the word using __next__(), remember to create a string_iterator and iterate over it and not the original string (it does not have the __next__() method)
In this example, when I find a char = [ I keep looking into the next word while I don't find ], so I need to use __next__
here a for loop over the string wouldn't help
myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
if char == "'":
continue
processedInput+=char
if char == '[':
next_char=word_iterator.__next__()
while(next_char != "]"):
processedInput+=next_char
next_char=word_iterator.__next__()
else:
processedInput+=next_char

How to assign the value of an index of a list to a variable in Python if you only know the index number and don't know or care about the element

I just spent 4 hours trying to google the answer asked pretty much as above. There were 10,000 results on how to find the index of an element. But I am not interested in any of the elements and never know what they will be, how long they will be, nor what they will contain since the string is user's input.
I have studied the Python manual for "lists" and tried several methods. I used loops of several types. List comprehensions were simply too complicated for my tiny brain although I tried. In fact, I tried for 4 hours googling and tweaking things maybe a hundred times but I only received errors after error of every type which I chased down one by one. I am not providing any code because I am not interested in having anyone fix it (its for an online course and that would be cheating). I just want to know the syntax for one little thing that is preventing me from making it work.
I need to assign the position of any element (i.e., the index integer value) anywhere in the list to a variable so I can control some boundaries. The most important thing for me is to set some conditions for the first character of the string converted to a list.
I was not very clear explaining what I am trying to do so I edited to add this:
pseudo code:
1. Ask the user for input and assign it a variable
2 Convert the string into a list where each letter of the string is an element of the list.
#The operation is dependent only on the position and not on the content of each character in the list.
3 For some elements of the list (but not all of them, which is why a loop won't work) perform an operation depending on their position (or index value)in the list.
in other words:"if the element is in position 0 of the list (or 3 or 27 etc) of the list then do something to the element." And I won't know or care what the content of the original element was.
If I know how to do that then I can extrapolate it for other character positions in the list.
I am an total beginner, and am not familiar with technical jargon, so please provide the simplest, least complex method! :-) Thank you in advance.
I'm an amateur myself but I will take a shot. If you can please do share some more context and some code for clarity.
I just checked the comment you made 50 mins ago. If I understand correctly, you want to assign the indexes to a variable. If that's correct can use the enumerate function. It's a built-in function for sequences. If we were to apply enumerate on our list named text it will return the position e.g. the index and the value of that position.
text = ["B", "O", "O", "M"]
for index, value in enumerate(text):
print(index, value)
This code will give you the following result:
0 B
1 O
2 O
3 M
Inside the for loop, you have the index variable that will now refer to the position of each value. You can now apply further conditions, like if index == 0:... and do your thing.
Does this help?
I also tried this one:
I think this is what you want. It assigns the value of an index (0,1,2,3) of a list to a variable.
list = ["item 1", "item 2", "item 3"]
item = input("Enter some text: ")
if item == list[0]:
index = 0
elif item == list[1]:
index = 1
elif item == list[2]:
index = 2
print(index)
I tried this because you said: "if this is index 0 of the list then do this"
It checks if the value of the input is the item with index 0 of the list.
list = ["item 1", "item 2", "item 3"]
item = input("Enter some text: ")
if item == list[0]:
print("This is index 0 of the list")
else:
print("This is not index 0 of the list")
If this is not the thing you're looking for, could you please try to explain it in a different way? Or maybe try writting some code too please.

Inner workings of map() in a specific parsing situation

I know there are already at least two topics that explain how map() works but I can't seem to understand its workings in a specific case I encountered.
I was working on the following Python exercise:
Write a program that computes the net amount of a bank account based a
transaction log from console input. The transaction log format is
shown as following:
D 100
W 200
D means deposit while W means withdrawal. Suppose the following input
is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
One of the answers offered for this exercise was the following:
total = 0
while True:
s = input().split()
if not s:
break
cm,num = map(str,s)
if cm=='D':
total+=int(num)
if cm=='W':
total-=int(num)
print(total)
Now, I understand that map applies a function (str) to an iterable (s), but what I'm failing to see is how the program identifies what is a number in the s string. I assume str converts each letter/number/etc in a string type, but then how does int(num) know what to pick as a whole number? In other words, how come this code doesn't produce some kind of TypeError or ValueError, because the way I see it, it would try and make an integer of (for example) "D 100"?
first
cm,num = map(str,s)
could be simplified as
cm,num = s
since s is already a list of strings made of 2 elements (if the input is correct). No need to convert strings that are already strings. s is just unpacked into 2 variables.
the way I see it, it would try and make an integer of (for example) "D 100"?
no it cannot, since num is the second parameter of the string.
if input is "D 100", then s is ['D','100'], then cm is 'D' and num is '100'
Then since num represents an integer int(num) is going to convert num to its integer value.
The above code is completely devoid of error checking (number of parameters, parameters "type") but with the correct parameters it works.
and map is completely useless in that particular example too.
The reason is the .split(), statement before in the s = input().split(). This creates a list of the values D and 100 (or ['D', '100']), because the default split character is a space ( ). Then the map function applies the str operation to both 'D' and '100'.
Now the map, function is not really required because both values upon input are automatically of the type str (strings).
The second question is how int(num) knows how to convert a string. This has to do with the second (implicit) argument base. Similar to how .split() has a default argument of the character to split on, so does num have a default argument to convert to.
The full code is similar to int(num, base=10). So as long as num has the values 0-9 and at most 1 ., int can convert it properly to the base 10. For more examples check out built in int.

Cryptopals challenge 4 concern

i am not getting the desired results for Cryptopals challenge 4 set 1.
The concept of the program to check to see if any of these 300ish strings have been XORd by a single character. So with a brute force, my solution is take every string, XOR it with every character on the keyboard, and check to see if any of these results produce an english sentence. if not, then check the next string. Here is my code:
MY_DICT = {}
index = 0
my_plaintext = "Now that the party is jumping"
#fills the dictionary with hex strings from the txt file
with open("hexstrings.txt") as f:
my_list = f.readlines()
for x in my_list:
MY_DICT[index] = x.rstrip('\n')
index = index + 1
i=0
input() #this is just here to help me keep track of where i am when running it
#this loop fills possible_plaintext with all the possible 255 XORs of the i'th string
#of the dictionary that was previously filler from the txt file
for i in range(326):
possible_plaintexts = brute_force_singlechar_xor(MY_DICT[i])
print(possible_plaintexts)
if possible_plaintexts == my_plaintext: #line of concern
print("ya found it yay :) ")
Im sure that myBruteForce function works because it worked properly on the last problem where i XORd every possible char against a string. and i also know that the plaintext is the one provided bc i saw the solution. im just not sure why my program isnt recognizing that the plaintext is not in the dictionary.
(i am aware that using a scoring system to score every string to see if its close to english would be easier, but this is the way i chose to do it for now until i figure out how to get my scoring function to work /: )
How is your dictionary "possible_plaintexts" like when you print it?
Can you spot the solution in the printed text? How is it printed?
The decrypted string should also have a '\n' character.

How can I write the following script in Python?

So the program that I wanna write is about adding two strings S1 and S2 who are made of int.
example: S1='129782004977', S2='754022234930', SUM='883804239907'
So far I've done this but still it has a problem because it does not rive me the whole SUM.
def addS1S2(S1,S2):
N=abs(len(S2)-len(S1))
if len(S1)<len(S2):
S1=N*'0'+S1
if len(S2)<len(S1):
S2=N*'0'+S2
#the first part was to make the two strings with the same len.
S=''
r=0
for i in range(len(S1)-1,-1,-1):
s=int(S1[i])+int(S2[i])+r
if s>9:
r=1
S=str(10-s)+S
if s<9:
r=0
S=str(s)+S
print(S)
if r==1:
S=str(r)+S
return S
This appears to be homework, so I will not give full code but just a few pointers.
There are three problems with your algorithm. If you fix those, then it should work.
10-s will give you negative numbers, thus all those - signs in the sum. Change it to s-10
You are missing all the 9s. Change if s<9: to if s<=9:, or even better, just else:
You should not add r to the string in every iteration, but just at the very end, after the loop.
Also, instead of using those convoluted if statements to check r and substract 10 from s you can just use division and modulo instead: r = s/10 and s = s%10, or just r, s = divmod(s, 10).
If this is not homework: Just use int(S1) + int(S2).

Resources