How to link elements from a string with numbers in Python? - python

I'd like to link elements from a string with numbers in Python.
Users need to give an input string (one word such as "world") and then the elements of that string (here the letters of the word "world") needs to be linked to numbers starting from 0.
Then, when you give another string as an input, the corresponding numbers need to be printed.
What I tried:
# input
string = str(input())
# loop to link numbers with string input
number = -1
for letter in string:
number += 1
Now I'd like to link the first letter of the input string with the number 0 and so on.
E.g.:
string = "world"
than "w" = 0, "o" = 1, "r" = 2, "l" = 3 and "d" = 4.
And then when you give another string such as "lord" I want to get the following output:
3124
Because "lord" --> "l" = 3, "o" = 1, "r" = 2 and "d" = 4
I don't know how I can save these numbers to their corresponding letter.

a = "world"
tracker = dict()
for index, value in enumerate(a):
tracker[value] = index
b = "lord"
result = ""
for str_char in b:
result += str(tracker[str_char])
print(result)

There is built-in data structure that can store key value pairs and it is called
dictionary
You can make it as such:
string = "world"
letters_numbers = {}
numerator = 0
for char in string:
if char not in letters_numbers:
letters_numbers[char] = numerator
numerator += 1
then you can get another string, such as lord:
string2 = "lord"
numbers = []
for char in string2:
numbers.append(str(letters_numbers[char]))
print("".join(numbers)) # prints 3124
This way you can use words that has same letter multiple times and still get correct results.

Related

function to get nth letter from a string outputs number 1

when I try to get second character of string "hello" to get letter e it prints "1" for some reason
string = "hello"
print_string = string[2]
print(print_string)
I want to get the letter e or nth letter but I just get number 1
It's not printing a number 1; it is printing a lowercase letter "L", which is the third letter in the world "hello". Remember that Python is zero-indexed, so the first letter will be at index 0, and the second letter at index 1. Try:
string = "hello"
print_string = string[1]
print(print_string)
python is index-based, counting begins with zero:
string = "hello"
h e l l o\
0 1 2 3 4
use:
print(string[0])
to access "h"
or:
print(string[4])
to access "o"
it's not necessary to use an additional variable "print_string" in this case.
Here's another way of looking at it:
>>> for index, letter in enumerate("hello"):
... print (f'index={index} letter={letter}')
...
index=0 letter='h'
index=1 letter='e'
index=2 letter='l'
index=3 letter='l'
index=4 letter='o'

split a string to have chunks containing the maximum number of possible characters

e.g. string = 'bananaban'
=> ['ban', 'anab', 'an']
My attempt:
def apart(string):
letters = []
for i in string:
while i not in letters:
letters.append(i)
print("The letters are:" +str(letters))
x = []
result = []
return result
string = str(input("Enter string: "))
print(apart(string)
Basically, If I know all the letters that are in the word/string, I want to add them into x, until x contains all letters. Then I want to add x into result.
In my examaple "bananaban" it would mean [ban] is one x, because "ban" countains the letter "b","a" and "n". Same goes for [anab]. [an] only contains "a" and "n" because it is the end of the word.
Would be cool if somebody could help me ^^
IIUC, you want to split after all characters are in the current chunk.
You could use a set to keep track of the seen characters:
s = 'bananaban'
seen = set()
letters = set(s)
out = ['']
for c in s:
if seen != letters:
out[-1] += c
seen.add(c)
else:
seen = set(c)
out.append(c)
output: ['ban', 'anab', 'an']
The logical way seens to be first create a set with all letters in your string, then go over teh original one, collecting each character, and startign a new collection each time the set of letters in the collection match the original.
def apart(string):
target = set(string)
result = []
component = ""
for char in string:
component += char
if set(component) == target:
result.append(component)
component = ""
if component:
result.append(component)
return result
Using a set of the characters in the string, you can loop through the string and add or extend the last group in your resulting list:
S = "bananaban"
chars = set(S) # distinct characters of string
groups = [""] # start with an empty group
for c in S:
if chars.issubset(groups[-1]): # group contains all characters
groups.append(c) # start a new group
else:
groups[-1] += c # append character to last group
print(groups)
['ban', 'anab', 'an']

multiplying letter of string by digits of number

I want to multiply letter of string by digits of number. For example for a word "number" and number "123"
output would be "nuummmbeerrr". How do I create a function that does this? My code is not usefull, because it doesn't work.
I have only this
def new_word(s):
b=""
for i in range(len(s)):
if i % 2 == 0:
b = b + s[i] * int(s[i+1])
return b
for new_word('a3n5z1') output is aaannnnnz .
Using list comprehension and without itertools:
number = 123
word = "number"
new_word = "".join([character*n for (n, character) in zip(([int(c) for c in str(number)]*len(str(number)))[0:len(word)], word)])
print(new_word)
# > 'nuummmbeerrr'
What it does (with more details) is the following:
number = 123
word = "number"
# the first trick is to link each character in the word to the number that we want
# for this, we multiply the number as a string and split it so that we get a list...
# ... with length equal to the length of the word
numbers_to_characters = ([int(c) for c in str(number)]*len(str(number)))[0:len(word)]
print(numbers_to_characters)
# > [1, 2, 3, 1, 2, 3]
# then, we initialize an empty list to contain the repeated characters of the new word
repeated_characters_as_list = []
# we loop over each number in numbers_to_letters and each character in the word
for (n, character) in zip(numbers_to_characters, word):
repeated_characters_as_list.append(character*n)
print(repeated_characters_as_list)
# > ['n', 'uu', 'mmm', 'b', 'ee', 'rrr']
new_word = "".join(repeated_characters_as_list)
print(new_word)
# > 'nuummmbeerrr'
This will solve your issue, feel free to modify it to fit your needs.
from itertools import cycle
numbers = cycle("123")
word = "number"
output = []
for letter in word:
output += [letter for _ in range(int(next(numbers)))]
string_output = ''.join(output)
EDIT:
Since you're a beginner This will be easier to understand for you, even though I suggest reading up on the itertools module since its the right tool for this kind of stuff.
number = "123"
word = "number"
output = []
i = 0
for letter in word:
if(i == len(number)):
i = 0
output += [letter for _ in range(int(number[i]))]
i += 1
string_output = ''.join(output)
print(string_output)
you can use zip to match each digit to its respective char in the word (using itertools.cycle for the case the word is longer), then just multiply the char by that digit, and finally join to a single string.
try this:
from itertools import cycle
word = "number"
number = 123
number_digits = [int(d) for d in str(number)]
result = "".join(letter*num for letter,num in zip(word,cycle(number_digits)))
print(result)
Output:
nuummmbeerrr

Counting words starting with a character

Write a function that accepts a string and a character as input and
returns the count of all the words in the string which start with the
given character. Assume that capitalization does not matter here. You
can assume that the input string is a sentence i.e. words are
separated by spaces and consists of alphabetic characters.
This is my code:
def count_input_character (input_str, character):
input_str = input_str.lower()
character = character.lower()
count = 0
for i in range (0, len(input_str)):
if (input_str[i] == character and input_str[i - 1] == " "):
count += 1
return (count)
#Main Program
input_str = input("Enter a string: ")
character = input("Enter character whose occurances are to be found in the given input string: ")
result = count_input_character(input_str, character)
#print(result)
The only part missing here is that how to check if the first word of the sentence is stating with the user given character. consider this output:
Your answer is NOT CORRECT Your code was tested with different inputs. > For example when your function is called as shown below:
count_input_character ('the brahman the master of the universe', 't')
####### Your function returns ############# 2 The returned variable type is: type 'int'
### Correct return value should be ######## 3 The returned variable type is: type 'int'
You function misses the first t because in this line
if (input_str[i] == character and input_str[i - 1] == " "):
when i is 0, then input_str[i - 1] is input_str[-1] which Python will resolve as the last character of the string!
To fix this, you could change your condition to
if input_str[i] == character and (i == 0 or input_str[i - 1] == " "):
Or use str.split with a list comprehension. Or a regular expression like r'(?i)\b%s', with (?i) meaning "ignore case", \b is word boundary and %s a placeholder for the character..
Instead of looking for spaces, you could split input_str on whitespace, this would produce a list of words that you could then test against character. (Pseudocode below)
function F sentence, character {
l = <sentence split by whitespace>
count = 0
for word in l {
if firstchar(word) == character {
count = count + 1
}
}
return count
}
Although it doesn't fix your specific bug, for educational purposes, please note you could rewrite your function like this using list comprehension:
def count_input_character (input_str, character):
return len([x for x in input_str.lower().split() if x.startswith(character.lower())])
or even more efficiently(thanks to tobias_k)
def count_input_character (input_str, character):
sum(w.startswith(character.lower()) for w in input_str.lower().split())
def c_upper(text, char):
text = text.title() #set leading char of words to uppercase
char = char.upper() #set given char to uppercase
k = 0 #counter
for i in text:
if i.istitle() and i == char: #checking conditions for problem, where i is a char in a given string
k = k + 1
return k

Alphabet to integers

I'm trying to create a programm in which a user inputs a string e.g 'roller' and the program converts the alphabet to numbers such as a=1, b=2, c=3 etc, and the calculate the sum of these values. But, if the program finds two same letters in a row then it doubles the sum. So far I have done this:
input = raw_input('Write Text: ')
input = input.lower()
output = []
sum=0
for character in input:
number = ord(character) - 96
sum=sum+number
output.append(number)
print sum
which calculates the sum of the characters and also appends the converted characters to a new array. So can anyone help me to double the sum if two letters appear in a row?
Store the previous character and compare it to the current character. If they're the same, double the value.
word = 'hello'
out = []
c_prev = None
for c in word:
value = ord(c) - ord('a')
if c == c_prev: # double if repeated character
value = value * 2
out.append(value)
c_prev = c # store for next comparison
print(sum(out))

Categories

Resources