Simple word scrambler - python-3.x

counter = 0
sentence = 'Hello World'
split = str.split(sentence)
for str in split:
c = split[counter]
scramble = c[4] + c[0] + c[3] + c[1] + c[2]
counter += 1
print (scramble)
The program should rearrange each word in a string into a specific pattern but I cannot figure out how to print the scrambled text onto the same line.

Here you go
counter = 0
sentence = 'Hello World'
split = str.split(sentence)
for str in split:
c = split[counter]
scramble = c[4] + c[0] + c[3] + c[1] + c[2]
counter += 1
print (scramble, end=" ")
The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.

Related

Python string formatting for encryption

I need help figuring out how to do these following thigns for a string
If the character is an uppercase: change it to lowercase with '!' sign on its both sides (e.g. 'M' --> '!m!');
If the character is a lowercase: change it to uppercase with '!' sign on its both sides (e.g. 'm' --> '!M!');
If the character is a digit: cube the digit, i.e. raise to the power of 3 (e.g. '5' --> '125');
If the character is a blank space: replace it with '$' symbol;
Otherwise: keep it as it is.
I don't know where to start, besides a possible loop statement.
You can do this:
string = "Mm5 #"
new_string = ""
for char in string:
if char.isupper():
new_string += "!" + char.lower() + "!"
elif char.islower():
new_string += "!" + char.upper() + "!"
elif char.isdigit():
new_string += str(int(char) ** 3)
elif char == " ":
new_string += "$"
else:
new_string += char
print(new_string)
>> !m!!M!125$#
Iterate over the string.
According to the transformation rules, transforms each character in the string.
Returns the new string.
def convertString(input):
output = ''
for char in input:
if char.isupper():
char = '!' + char.lower() + '!'
output += char
elif char.islower():
char = '!' + char.upper() + '!'
output += char
elif char.isdigit():
char = int(char) * int(char) * int(char)
char = str(char)
output += char
elif char.isspace():
char = '$'
output += char
else:
char = char
output += char
return output
if __name__ == '__main__':
input = 'Mm 5:)'
output = convertString(input)
print(output)
Output
!m!!M!$125:)
Here's answer for your question. It is in Kotlin but you can get the logic and convert it in Python.
fun main(){
println("Enter String: ")
val str = readln()
var newString = ""
for (s in str){
when{
s.isDigit() -> newString += (s.digitToInt() * s.digitToInt() * s.digitToInt())
s.isLowerCase() -> newString += "!" + s.uppercase() + "!"
s.isUpperCase() -> newString += "!" + s.lowercase() + "!"
s == ' ' -> newString += "$"
}
}
println("String formatted as: $newString")
}

White Spaces issue while converting to binary

I'm implementing A5/1 algorithm, I have the following function:
def to_binary(plain):
print(plain)
binary = str(''.join(format(ord(x), 'b') for x in plain))
j = len(binary)
binary_values = []
k = 0
while(k < j):
binary_values.insert(k,int(binary[k]))
k = k + 1
return(binary_values)
then I'm reading the input as the following:
plainText = input("Please enter your plaintext : ")
print ("You entered : "+ plainText)
plainText = to_binary(plainText)
After that I generate a keyStream and I store it in a list, then I obtain the ciphered text as the following:
while(i < len(plainText)):
cipherText = cipherText + str(plainText[i] ^ keyStream[i])
i = i + 1
Now I can decrypt the ciphered text using the following function:
def decrypt(cipher,keystream):
s = ""
binary = []
i = 0
while(i<len(cipher)):
binary.insert(i,int(cipher[i]))
s = s + str(binary[i]^keystream[i])
i = i +1
print(s)
return convert_binary_to_str(s)
and the convert_binary_to_str function is:
def convert_binary_to_str(bin_data):
str_data =' '
for i in range(0, len(bin_data), 7):
temp_data = bin_data[i:i + 7]
decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)
return str_data
Everything is working fine if the input was a sentence with no white spaces, but if the sentence was for example "Hello There", the decryption is corrupted because the white space representation in binary this way is taking "6 bits" while the other alphabetical characters are "7-bits" long, what can I do to solve this?? I need to store the plain text in a list to apply the algorithm.

How to fix the error "index out of range"

I have to split the string with some "" in the string
I am a beginner in python, plz help me QQ
With the problem that line3 shows "index out of range"
windows
data = input().split(',')
for i in range(len(data)):
for j in range(len(data[i])):
if data[i][j] == '"':
data[i] += "," + data[i + 1]
data.pop(i + 1)
if data[i + 1][j] == '"':
data[i] += "," + data[i + 1]
data.pop(i + 1)
print(data[i])
sample input:
'str10, "str12, str13", str14, "str888,999", str56, ",123,", 5'
sample output:
str10
"str12, str13"
str14
"str888,999"
str56
",123,"
5
Your error occurs if you acces a list/string behind its data. You are removing things and access
for i in range(len(data)):
...
data[i] += "," + data[i + 1]
If i ranges from 0 to len(data)-1 and you access data[i+1] you are outside of your data on your last i!
Do not ever modify something you iterate over, that leads to desaster. Split the string yourself, by iterating it character wise and keep in mind if you are currently inside " ... " or not:
data = 'str10, "str12, str13", str14, "str888,999", str56, ",123,", 5'
inside = False
result = [[]]
for c in data:
if c == ',' and not inside:
result[-1] = ''.join(result[-1]) # add .strip() to get rid of spaces on begin/end
result.append([])
else:
if c == '"':
inside = not inside
result[-1].append(c)
result[-1] = ''.join(result[-1]) # add .strip() to get rid of spaces on begin/end
print(result)
print(*result, sep = "\n")
Output:
['str10', ' "str12, str13"', ' str14', ' "str888,999"', ' str56', ' ",123,"', ' 5']
str10
"str12, str13"
str14
"str888,999"
str56
",123,"
5
Add .strip() to the join-lines to get rid of leading/trailing spaces:
result[-1] = ''.join(result[-1]).strip()

Reason for result of output of Python code

why the while loop is executing more times than expected in printing a pascal triangle?
every time the while loop is executed x is incremented by 1 whereas n remains the same
I just started learning python
please help
memo = {0:1}
def fac(n):
if n not in memo:
memo[n] = n*fac(n-1)
return memo[n]
else:
return memo[n]
def pascal(x, space):
while(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
pascal(x, space)
n = eval(input())
space = n
x = 0
pascal(x, space)
You are using two methods to iterate through the numbers in the pascal function, a while loop, and a recursive call. You just need one of them.
Keeping the while loop:
def pascal(x, space):
while(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
Keeping the recursive call, turning the while into an if:
def pascal(x, space):
if(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
pascal(x, space)
Given 3 as input, both versions print the following:
1
1 1
1 2 1
1 3 3 1

Caesar Cipher shift on new lines

I am having a problem with my code trying to do an advanced caesar cipher shift. I changed a certain letter to another, and then added a string to certain parts of a file before encoding, but am having problems doing the shifting now. This is my code:
import string
import sys
count = 1
cont_cipher = "Y"
#User inputs text
while cont_cipher == "Y":
if count == 1:
file = str(input("Enter input file:" ""))
k = str(input("Enter shift amount: "))
purpose = str(input("Encode (E) or Decode (D) ?: "))
#Steps to encode the message, replace words/letter then shift
if purpose == "E":
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s
for letter in file_contents:
if letter == "e":
file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
lines = file_contents.split('\n')
def middle_message(lines, position, word_to_insert):
lines = lines[:position] + word_to_insert + lines[position:]
return lines
new_lines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]
#math to do the actual encryption
def caesar(word, shifts):
word_list = list(new_lines)
result = []
s = 0
for c in word_list:
next_ord = ord(c) + s + 2
if next_ord > 122:
next_ord = 97
result.append(chr(next_ord))
s = (s + 1) % shifts
return "".join(result)
if __name__ == "__main__":
print(caesar(my_file, 5))
#close file and add to count
my_file.close()
count = count + 1
The error I am getting is:
TypeError: ord() expected a character, but string of length 58 found
I know that I need to split it into individual characters, but am not sure how to do this. I need to use the updated message and not the original file in this step...

Resources