迭代Python中的STRINGS(3)

时间:2017-11-16 21:49:05

标签: python string python-3.x

:编写一个名为foldStrings(string1,string2)的函数,该函数将两个字符串作为参数。如果
两个字符串的长度相等,该函数返回一个字符串,该字符串由两个字符串中每个字符串中的交替字符组成。如果两个字符串的长度不相等,则该函数返回字符串“这两个字符串不是 长度相等。“

例如,>>> foldStrings(“abc”,“def”)
应该返回字符串“adbecf”和>>> foldStrings(“a”,“bc”)
应该返回字符串“两个字符串的长度不相等。”

这是我到目前为止所做的:

sum = (n * (n+1))/2;

并打印出来:' s1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6' 而不是这个: ' s1a2n3t4o5s6'

3 个答案:

答案 0 :(得分:1)

当需要单个循环时,您有三个嵌套循环不必要地复杂化问题。

替换:

while counter < len(str2):
    for element in str1:
        for index in str2:
            newStr = newStr + element
            newStr = newStr + index
            counter += 1
return newStr

使用:

for index in range(len(str1)) :
    newStr = newStr + str1[index] + str2[index]

return newStr

在原始代码中,如果字符串长度为例如6,则代码为:

 Repeat 6 times:
     for every character in str1
         for every character in str1
             do stuff

使do stuff执行6 x 6 x 6次!你只想执行它6次,建议一个循环。

你做错了不是python特定的问题,而是你的算法和逻辑思维的问题。在数学上,问题表明单个迭代,而你有三个嵌套。在这种情况下,您可能已经手动遍历代码或使用调试器逐步完成它来演示思考中的缺陷。

答案 1 :(得分:0)

您可以使用#include <tuple> #include <type_traits> #include <iostream> #include <string> template<class...Ts> struct nth_is_compatible { using tuple = std::tuple<Ts...>; template<class T, std::size_t N> static constexpr bool check() { return std::is_convertible<decltype(std::get<N>(std::declval<tuple>())), T>::value; } }; struct Monkey { Monkey(std::string) {} // conversion constructor }; int main() { using checklist = nth_is_compatible<const int&, float, std::string>; constexpr auto list = checklist(); std::cout << list.check<int, 0>() << std::endl; std::cout << list.check<int, 1>() << std::endl; std::cout << list.check<int, 2>() << std::endl; // prove it's a constexpr and that it works for conversions constexpr auto monkeyable = checklist::check<Monkey, 2>(); std::cout << monkeyable << std::endl; }

跳过counter变量
range

这是一种更简洁的方式来替换def foldStrings(str1, str2): if len(str1) != len(str2): return "The two Strings are not equal in length" # This should really be a raise ValueError("The two Strings are not equal in length") newStr = '' for i in range(len(str1)): newStr += str1[i] + str2[i] return newStr 循环

for

答案 2 :(得分:0)

Id
相关问题