Reputation: 387
I'm a beginner in Python struggling to solve the following exercise.
Write a function that takes two strings containing whole numbers (integers) separated by commas. The function should return another string similar to the first string having the square numbers of the first string in the second string. In other words, the third string should only contain the numbers of the first string whose square numbers are found in the second string
Example
string1 = "2, 5, 3, 11"
string2 = "19, 25, 4, 181"
returns the string3 = "2, 5"
because only the square of 2 and 5 of the first string are present in the second string. The rest are not.
I have an idea of how it should done. First off i created two functions which convert both strings into lists of integers in order to be able work with every single number through their indexes using split
. I don't know if that's the right way to do so. Both functions return a list
Then i created a third function to take the lists from the two other functions, compare them using an if statement and the for cycle , select the numbers and put them in a list to be converted into a string and return it.
The problem is that when i run the program it tells me that some variables (s1, s2) are not defined.
Here is my code
def f1 (stringa1):
s1 = stringa1.split()
return s1
def f2 (stringa2):
s2 = stringa2.split()
return s2
def mystring (s1, s2):
lista = []
s1=stringa1
for i in s2:
if (s2[i] == s1[i**2]):
lista.append(s1)
ls = lista(map(str,i))
return ls
Any help will be appreciated. Thank you very much
Upvotes: 1
Views: 956
Reputation: 3281
First I would create arrays from the string, and trim any white space
arr1 = [int(str.strip()) for str in string_1.split(',')]
arr2 = set([int(str.strip()) for str in string_2.split(',')])
arr3 = [int(str.strip()) for str in string_3.split(',')]
Then, I would get the power of each value in arr1, and see if it exists in arr2
arr4 = [val for arr in arr1 if pow(val,2) in arr2 ]
To address Dio Phung's comment regarding changing arr2 to a set:
If you're lost, Dio Phung recommends changing arr2 into a set, as a set provides constant lookup time. This would make the main logic of looking up the n^2 value of arr1 in arr2, significantly faster (especially if the dataset is large).
You can view the documentation on time complexities here:
https://wiki.python.org/moin/TimeComplexity
By changing arr2 into a set, we can perform the main logic of:
pow(val,2) in arr2
in O(1) time complexity, where as in a list, it would be O(n).
Upvotes: 2
Reputation: 7204
Here's a quick way to do it ( and avoid confusion from converting floats to ints, in case that int is in string1 )
floater = lambda x: float(x)
sqrtr = lambda x: math.sqrt(int(x))
string1 = "2, 5, 3, 11"
string2 = "19, 25, 4, 181"
a = list(map(floater, list(string1.split(","))))
b = list(map(sqrtr, list(string2.split(","))))
list(set(a) & set(b))
# [2.0, 5.0]
and just in case you need ints you can remap with this:
inter = lambda x: int(x)
list(map(inter,(list(set(a) & set(b)))))
# [2, 5]
Upvotes: 1
Reputation: 2563
string1 = "2, 5, 3, 11"
string2 = "19, 25, 4, 181"
def answer(str1, str2):
num1 = map(int, str1.split(', ')) # convert str1 into a list of ints
num2 = set(map(int, str2.split(', '))) # convert str2 into a list of ints
matches = [n for n in num1 if n**2 in num2] # create a new list of matches
return ", ".join(map(str, matches)) # return it as a comma-separated string
answer(string1, string2)
Upvotes: 1
Reputation: 1054
Here is a solution with list comprehension and the join
and split
methods of str
objects:
def square_isin(s1, s2):
numbers = []
s2_int = [int(v) for v in s2.split(", ")]
for s in [int(v) for v in s1.split(", ")]:
if s*s in s2_int:
numbers.append(s)
return ', '.join([str(v) for v in numbers])
string3 = square_isin(string1, string2)
Upvotes: 1
Reputation: 16573
You should split the string to turn them into sequences of integers, then iterate through the first and check if the square is in the second sequence.
def myfunc(s1, s2):
nums = [int(i) for i in s1.split(", ")]
squares = {int(i) for i in s2.split(", ")}
return ", ".join([str(num) for num in nums if num * num in squares])
string1 = "2, 5, 3, 11"
string2 = "19, 25, 4, 181"
string3 = myfunc(string1, string2)
print(string3)
Output:
2, 5
Upvotes: 2
Reputation: 195408
One solution for this problem can be this: For parsing the two strings, you can use ast.literal_eval
(doc). First, you create list from string1
and set from string2
.
Then you iterate over the list and check if power of two of the value is inside the set.
Example:
string1 = "2, 5, 3, 11"
string2 = "19, 25, 4, 181"
from ast import literal_eval
lst1 = literal_eval('[' + string1 + ']')
set2 = literal_eval('{' + string2 + '}')
rv = [i for i in lst1 if i**2 in set2]
print(rv)
Prints:
[2, 5]
Upvotes: 3