Capitalizing each words with chr and ord - python-3.x

First I have to receive a string from the user. The function would be capitalizing the introduced string object. It would make the words start with uppercased characters and all remaining characters have lower case. Here is what I did:
ssplit = s.split()
for z in s.split():
if ord(z[0]) < 65 or ord(z[0])>90:
l=(chr(ord(z[0])-32))
new = l + ssplit[1:]
print(new)
else:
print(s)
I can't see what I am doing wrong.

Using str.title() as suggested by #Pyer is nice. If you need to use chr and ord you should get your variables right - see comments in code:
s = "this is a demo text"
ssplit = s.split()
# I dislike magic numbers, simply get them here:
small_a = ord("a") # 97
small_z = ord("z")
cap_a = ord("A") # 65
delta = small_a - cap_a
for z in ssplit : # use ssplit here - you created it explicitly
if small_a <= ord(z[0]) <= small_z:
l = chr(ord(z[0])-delta)
new = l + z[1:] # need z here - not ssplit[1:]
print(new)
else:
print(s)
Output:
This
Is
A
Demo
Text

There are many python methods that could solve this easily for you. For example, the str.title() will capitalize the start of every word in the given string. If you wanted to ensure that all others were lowercase, you could first do str.lower() and then str.title().
s = 'helLO how ARE YoU'
s.lower()
s.capitalize()
# s = 'Hello How Are You'

Related

how to decrypt a string that is encrypted using XOR

I have tried to encrypt a string using a XOR operator and took the output in alphabets. Now when I am trying to decrypt it I'm not getting the string again.
Encryption code:
string= "Onions"
keyword = "MELLON"
def xor(string, key):
st=[]
ke=[]
xored=[]
for i in string:
asc= (ord(i))
st.append(int(asc))
print(st)
for i in key:
asc= (ord(i))
ke.append(int(asc))
print(ke)
for i in range(len(string)):
s1=st[i]
k1=ke[i]
abc = s1^k1
le = ord('A')+abc
ch = chr(le)
if le> 90:
le= le-26
ch = chr(le)
print(s1,k1)
print('XOR =',abc)
print(ch)
xored.append(ch)
print(xored)
return("" . join(xored))
Need help!!
The algorithm does not perform a pure XOR, but maps values conditionally to another value, leading to a relation that is no longer bijective.
To illustrate this point. See what this script outputs:
keyword = "MELLON"
print(xor("Onions", keyword) == xor("OTGEHs", keyword))
It will output True!
So this means you have two words that are encrypted to the same string. This also means that if you need to do the reverse, there is no way to know which of these is the real original word.
If you want to decryption to be possible, make sure to only use operations that lead to a bijective mapping. For instance, if you only use a XOR, without adding or subtracting values, it will be OK.
Here is an approach where only lower and uppercase letters of the Latin alphabet are allowed (for both arguments):
def togglecrypt(string, key):
mapper = "gUMtuAqhaEDcsGjBbreSNJYdFTiOmHKwnXWxzClQLRVyvIkfPpoZ"
res = []
for i, ch in enumerate(string):
shift = mapper.index(key[i % len(key)]) % 26
i = mapper.index(ch)
if i < 26:
j = 26 + (i + shift) % 26
else:
j = (i - shift) % 26
res.append(mapper[j])
return("".join(res))
keyword = "MELLON"
encoded = togglecrypt("Onions", keyword)
print(encoded) # TdsDAn
print(togglecrypt(encoded, keyword)) # Onions

Unable to successfully compare two strings

phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
new_phrase = phrase.split("+")#splits phrase at the + operator
print(len(new_phrase))
for item in new_phrase:
c = (new_phrase>new_phrase.index("^"))#actul differentiation part c is the power of whatever (this is where python has a problem) line 6
y = (new_phrase<(new_phrase.index("^")-1))# y is the number before x
print(float(c)*float(y)+"^"+float(c)-1)# this is the final differentiated answer
#however it keeps saying ^ is not in the list how can I fix this?
Using Python 3.8.1
The actual main code is starting at for item. This is where the problem occurs, as the input is supposed to be 3x^2+2x^1+-4x^4, or something like, that but Python cannot seem to find where the power to sign "^" in the list thus the rest of the code from the " c =" does not work.
I have created a working version from your code. Mainly the problem was the type inconsistency. Furthermore I have added several comments to the code for the better understanding and it contains several prints for the debugging.
Code:
phrase = input("Enter the equation you want differentiated: ").lower() # 3x^2+2x^1+-4x^4
new_phrase = phrase.split("+") # splits phrase at the + operator
print("Elements: {}".format(new_phrase)) # Print elements of differential
for item in new_phrase:
print("Tested element: {}".format(item))
c = float(item.split("^")[-1]) # Get after part of "^" character
y = float(item.split("^")[0].replace("x", "")) # Get before part of "^" character (withour "x")
print("c={} ; y={}".format(c, y))
print(
"Result: {}^{}".format(float(c) * float(y), float(c) - 1)
) # this is the final differentiated answer
Output:
>>> python3 test.py
Enter the equation you want differentiated: 3x^2+2x^1+-4x^4
Elements: ['3x^2', '2x^1', '-4x^4']
Tested element: 3x^2
c=2.0 ; y=3.0
Result: 6.0^1.0
Tested element: 2x^1
c=1.0 ; y=2.0
Result: 2.0^0.0
Tested element: -4x^4
c=4.0 ; y=-4.0
Result: -16.0^3.0
Here is some Python script that can differentiate algebraic expressions based on your code.
phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
# Splits phrase at the + operator
split_phrase = phrase.split("+")
# Placeholder for the differentiated phrase
new_phrase = ""
for item in split_phrase:
# Exponent - index of ^ - 1
c = int(item[item.index("^") + 1:])
#Coefficient - from 0 to index of x - 1
y = int(item[0:item.index("x")])
#Reconstructs the algebraic expression
new_phrase += str(c*y) + "x^" + str(c-1)
# Adds a plus sign if it is not the last item
if split_phrase.index(item) != len(split_phrase) - 1:
new_phrase += "+"

Use Python to reverse the words in a sentence

The question was: Return a sentence with the words reversed
>>> master_yoda('I am home')
'home am I'
It will eventually reverse the words of the line.
I am learning and performing Python in Jupyter Notebook.
def master_yoda(string):
l = string.split()``
p = len(string) - 1
final = ''
while p<0:
final = final + ' ' + s[p]
p = p-1
print (final)
master_yoda('Hello my name is Aryan')
The output is nothing..
No syntax errors , but still no output ...
Perhaps you should try this.
def master_yoda(string):
reversed_list = string.split(' ')
reversed_list.reverse()
reversed_string = ' '.join(reversed_list)
print(reversed_string)
master_yoda("i am home")
The big problem with the code is that you were testing for p < 0 but since p starts off with a positive value, the code never enters the while loop. You should really have been testing for p >= 0. The following code should do what you want, they way you seem to want it to:
def master_yoda(string):
l = string.split()
p = len(l) - 1
final = l[p]
p -= 1
while p >= 0:
final += ' ' + l[p]
p -= 1
return final
Note that this implementation fails if an empty string is passed as input. I tried to keep the code in the spirit of your own code and checking for an empty string would make it more complex. The simplest and most robust solution would be:
def master_yoda(string):
return ' '.join(reversed(string.split()))

Python lists and ranges

I'm trying to practice my python so I can improve. I'm kinda stuck and not sure how to proceed. I get an error saying "can only concatenate list(not 'int') to list." I'll leave my code and what I'm trying to do below.
Input a word string (word)
find the string length of word
use range() to iterate through each letter in word (can use to range loops)
Save odd and even letters from the word as lists
odd_letters: starting at index 0,2,...
even_letters: starting at index 1,3,...
print odd and even lists
word = input("Type: ")
word = list(word)
print(word)
odd_letters = []
even_letters = []
length = int(len(word))
for i in range(length):
if i/2 == 0:
even_letters = even_letters + i
elif i/2 != 0:
odd_letters = odd_letters + i
print(even_letters)
print(odd_letters)
I wrote this... Let me know what you think...
word = input("Choose a word to test: ")
word_len = len(word)
print(word," contains ",word_len," letters")
odd_letters = []
even_letters = []
for i in range(1,len(word),2):
even_letters.append(word[i])
for i in range(0,word_len,2):
odd_letters.append(word[i])
print("Odd letters are: ",odd_letters)
print("Even letters are: ",even_letters)
Your code is good, but i decided to find a quicker solution for the program you want. This is my code:
word = str(input("Enter word:"))
store_1 = [x for x in word]
store_2 = []
for idx, val in enumerate(store_1):
store_2.append(idx)
even_numbers = [y for y in store_2 if y%2 == 0]
odd_numbers = [z for z in store_2 if z%2 == 1]
print("List of Even numbers:",even_numbers)
print("List of Odd numbers:",odd_numbers)
The variable 'word' takes in the word from the user. The list 'store_1' uses list comprehension to separate the letters the in the word and store it. Next, i enumerate through 'store_1' and use the variable 'store_2' to only store the indexes of 'store_1'.
Next, I declare another variable 'even_numbers' that uses list comprehension to iterate through 'store_2' and find the even numbers. The next variable 'odd_numbers' also uses list comprehension to find the odd numbers in 'store_2'.
Then, it just prints the even and odd lists to the user. Hope this helps :)
You cannot add an integer to a list, as you have attempted to do here:
even_letters = even_letters + i
You can instead do this (which is now adding a list to a list, which is valid):
even_letters = even_letters + [i]
Or, use append to alter the list in-place, adding the new element to the end:
even_letters.append(i)
Few things:
You cannot "add" an integer directly to a list using '+'. Using append() would be best.
str and str types can be concatenated using '+' so you could change odd_letters and even_letters to str as shown below.
also, by adding 'i' to even and odd, you are adding the iteration variable value.
Since you want the letter to be appended, you need to refer the list index i.e word[i]
and the first letter of what is entered will be at an odd position :)
word = input("Type: ")
word = list(word)
print(word)
odd_letters = ''
even_letters = ''
length = int(len(word))
for i in range(1,length+1):
if i%2 == 0:
even_letters = even_letters + word[i-1]
else:
odd_letters = odd_letters + word[i-1]
print("even_letters",even_letters)
print("odd_letters",odd_letters)
word=input()
word_num=len(word)
print(word_num)
odd_num=[]
even_num=[]
for letters in range(0,word_num,2):
odd_num.append(word[letters])
for letters in range(1,word_num,2):
even_num.append(word[letters])
print(odd_num)
print(even_num)
This is the answer it works with every word, and follows all the requirements.

cutting a string at spaces python

I am beginning to learn python and want to cut a string at the spaces; so 'hello world' becomes 'hello' and 'world'. To do this i want to save the locations of the spaces in a list, but i can't figure out how to do this. In order to find the spaces i do this:
def string_splitting(text):
i = 0
for i in range(len(text)):
if (text[i]==' '):
After saving them in the list i want to display them with text[:list[1]] (or something like that)
Can anyone help me with the saving it in a list part; and is this even possible?
(Another way to cut the string is welcome to :-) )
Thanks.
Use split:
"hello world my name is".split(' ')
It will give you a list of strings
thanks, i tried to do it without the split option, should have said that in the question..
anyways this worked;
def split_stringj(text):
a = text.count(' ')
p = len(text)
l = [-1]
x = 0
y = 1
for x in range(p):
if (text[x]==' '):
l.append(x)
y += 1
l.append(p)
print l
for x in range(len(l)-1):
print text[l[x]+1:l[x+1]]

Resources