how can I assign variable b to indexes of the string a? - python-3.x

I have a problem with task.
Write a program that will replace the given position for the given string (also given by the user). The function has 3 parameters, string for analysis, position that should be replaced and the character that has services to be changed.
I tried it that way but it doesn't work.
At the end there is the same string as at the beginning
a =input("enter string\n")
print(len(a))
for i in enumerate(a):
print("individual indexes:",([i]))
b = input("enter the index number you want to replace\n")
b = str([a,i])
c = input("what do you want to change ?\n")
a1 = a.replace(b,c)
print(a1)

b = int(b)
a1 = a[:b] + 'c' + a[b:]
a =input("enter string\n")
print(len(a))
for i in enumerate(a):
print("individual indexes:",([i]))
b = int(input("enter the index number you want to replace\n"))
c = input("what do you want to change ?\n")
a1 = a[:b] + 'c' + a[b:]
print(a1)

First, a side note. Avoid using variable names such as: a, b...names should be meaningful.
For example:
a --> input_str
b --> idx_to_change
c --> new_char
a1 --> final_str
A full working example:
input_str =input("enter string\n")
print(len(input_str))
for i in enumerate(input_str):
print("individual indexes:",([i]))
idx_to_change = input("enter the index number you want to replace\n")
idx_to_change = input_str [int(idx_to_change)]
new_char = input("what do you want to change ?\n")
final_str = input_str.replace(idx_to_change, new_char)
print(final_str)

Related

Count number of continuous matching elements in two different numbers in Python

Suppose
we have two numbers a and b we need to calculate the continuous matching digits between the two numbers.
some examples are shown below:
a = 123456 b = 456 ==> I need count as : 3 digits matching
a = 556789 b = 55678 ==> I need count as : 5 digits matching
I don't want unique but continuous matching numbers and need the count. Also display the matching ones will be helpful. Also can we can we do in two different lists if numbers?
I am very new to python and trying out few things. Thanks
Given two numbers a and b:
a = 123456
b = 456
First you need to covert them to strings:
a_str = str(a)
b_str = str(b)
Then you need to check if there is a continuous match of b_str in a_str:
if b_str in a_str:
...
Finally you can check the length of b_str:
len(b_str)
This is the complete function:
def count_matching_elements(a, b):
a_str, b_str = str(a), str(b)
if b_str in a_str:
return len(b_str)
else:
return -1 # no matches
What you want here is know as the Longest common substring, you can find it like this (this code can be found here Find common substring between two strings, just a little difference that you actually want the len(answer)) :
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
else:
if (len(match) > len(answer)): answer = match
match = ""
return len(answer)
Note that a and b would have to be strings

Multiplication Python Script giving wrong output

The Code below gives an answer for almost any number I have tested with, even a 64 digits *64 digits. But when tried with
a = 123456
b = 123456
The final answer is negative.
Up until
a = 12345
b = 12345
The answer is correct.
Not sure where this is going wrong. I am relatively new to python so is there something I am missing out?
import numpy as np
a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
c = 1
pos_nums = []
while b != 0:
z = b % 10
pos_nums.append(z *c)
b = b // 10
c = c*10
pos_num = np.array([pos_nums])
multiply = pos_num *a
add = np.sum(multiply)
print(add)
I don't know why numpy is playing up, but something like this appears to work, and does the same thing.
All I've done is removed the conversion to a numpy array. Now when you multiply pos_num it essentially makes a copies of it into one list. sum counts the total value of the list, which has a amounts of b stored in it.
Hope this works for you :)
a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
c = 1
pos_nums = []
while b != 0:
z = b % 10
pos_nums.append(z *c)
b = b // 10
c = c*10
#pos_num = np.array(pos_nums)
pos_num = pos_nums
multiply = pos_num *a
add = sum(multiply)
print(add)
Output:
Enter Number 1: 123456
Enter Number 2: 123456
15241383936
numpy can't guess your next move!
you see when you define a numpy array it will assume a type for the array (like np.int16) and its not will not change unless you multiply it into something with other formats
what happend here?
you have multiplied a dtype=np.int32 array into an int in line:
multiply = pos_num *a
the result will be another np.int32 array (you can see that with print(multiply.dtype))
numpy can not guess that you intend to extend the array into for example np.float64
(not like regular python code, because there is a great performace hit to that)
what to do?
just simply define the type for it! (it a good practice to do this in other codes)
pos_num = np.array(pos_nums, dtype=np.float64)

Check if text contains a string and keep matched words from original text:

a = "Beauty Store is all you need!"
b = "beautystore"
test1 = ''.join(e for e in a if e.isalnum())
test2 = test1.lower()
test3 = [test2]
match = [s for s in test3 if b in s]
if match != []:
print(match)
>>>['beautystoreisallyouneed']
What I want is: "Beauty Store"
I search for the keyword in the string and I want to return the keyword from the string in the original format (with capital letter and space between, whatever) of the string, but only the part that contains the keyword.
If the keyword only occurs once, this will give you the right solution:
a = "Beauty Store is all you need!"
b = "beautystore"
ind = range(len(a))
joined = [(letter, number) for letter, number in zip(a, ind) if letter.isalnum()]
searchtext = ''.join(el[0].lower() for el in joined)
pos = searchtext.find(b)
original_text = a[joined[pos][1]:joined[pos+len(b)][1]]
It saves the original position of each letter, joins them to the lowercase string, finds the position and then looks up the original positions again.

Shortest path program Python

I've written the following program, and there are 2 'mistakes' which I don't know how to fix. Inputs b1, c1, d1, and e1 correspond to points and adjacent nodes.
For instance, if I give the input: A B C, this means that from point A you can travel to B and C. The input f1 corresponds to the starting and endpoint. For instance, if I give the input: A D, this means that you start at point A and want to finish at point D.
b1 = input()
c1 = input()
d1 = input()
e1 = input()
f1 = input()
b = b1.split()
c = c1.split()
d = d1.split()
e = e1.split()
f = f1.split()
b_node = b[1:]
c_node = c[1:]
d_code = d[1:]
e_node = e[1:]
f_node = f[1:]
G = {b[0]:b_node, c[0]:c_node, d[0]:d_node, e[0]:e_node}
def find_path(graph, start, end, path = []):
path = path + [start]
newpath = []
if start == end:
return path
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath)<len(shortest):
shortest = newpath
return shortest
print(find_path(G, f[0], f[1]))
I give my program the following input
A B C
B A C
C B D
D
A D
My questions are the following:
1. My program gives an error because d_node = [] (empty). However, this is
supposed to be so since from point D, you can't travel to any point! How can I make it run correctly?
2. Is there a way to let my program ask for a number 'N' points, and then give me N lines to give for those points all the adjacent info? I tried something of the form
input_list = []
x = int(input())
for i in range(x):
input_list.append(input())
But couldn't make it work.. Any ideas?
1:
You have a typo for 'd_node' as you have written 'd_code'.
2:
Try with a while-loop; continue if you enter a blank line (which will indicate that you are done entering points). Something like:
while True:
i = input()
if not i:
break

is there a way to iterate through a string by incrementing the char through string slicing?

For example I want to increment the variable b by one so that the loop now checks for the second character in the string. In this case, the character "o". b +1 is what I want to achieve.
a = 'Goodbye'
b = 'Good'
c = ''
for letter in a:
if letter == b[0]:
c += letter
#b [+1]
print(c)
else:
print("no")
You can access the second character with b[1], if you need to progressively increment into b, then use b[i] and increment i as needed.

Resources