简体   繁体   English

如何比较两个包含数字的字符串?

[英]How do i compare two strings containing numbers?

I'm a beginner in Python struggling to solve the following exercise. 我是Python的初学者,正努力解决以下练习。

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. 因为第二个字符串中仅存在第一个字符串的2和5的平方。 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 . 首先,我创建了两个函数,将两个字符串都转换为整数列表,以便可以使用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. 然后,我创建了第三个函数,以从其他两个函数中获取列表,使用if语句和for循环比较它们,选择数字并将它们放在要转换为字符串的列表中,然后将其返回。

The problem is that when i run the program it tells me that some variables (s1, s2) are not defined. 问题是,当我运行程序时,它告诉我某些变量(s1,s2)未定义。

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 非常感谢你

One solution for this problem can be this: For parsing the two strings, you can use ast.literal_eval ( doc ). 解决此问题的一种方法是:为了解析两个字符串,可以使用ast.literal_evaldoc )。 First, you create list from string1 and set from string2 . 首先,您从string1创建列表,并从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]

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 然后,我将获得arr1中每个值的幂,然后查看它是否存在于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: 要解决Dio Phung关于将arr2更改为集合的评论,请执行以下操作:

If you're lost, Dio Phung recommends changing arr2 into a set, as a set provides constant lookup time. 如果您迷路了,Dio Phung建议将arr2更改为一个集合,因为集合提供了恒定的查找时间。 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). 这将使在arr2中查找arr1的n ^ 2值的主要逻辑快得多(特别是在数据集很大的情况下)。

You can view the documentation on time complexities here: 您可以在此处查看有关时间复杂度的文档:

https://wiki.python.org/moin/TimeComplexity https://wiki.python.org/moin/TimeComplexity

By changing arr2 into a set, we can perform the main logic of: 通过将arr2更改为集合,我们可以执行以下主要逻辑:

pow(val,2) in arr2

in O(1) time complexity, where as in a list, it would be O(n). 在O(1)时间复杂度中,如列表中所示,它将是O(n)。

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

Here is a solution with list comprehension and the join and split methods of str objects: 这是一个具有列表理解以及str对象的joinsplit方法的解决方案:

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)
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)

Here's a quick way to do it ( and avoid confusion from converting floats to ints, in case that int is in string1 ) 这是一种快速的方法(避免int在string1中,将浮点数转换为int会造成混淆)

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM