简体   繁体   English

python O(N^2)中的两个数字求和程序

[英]Two number Sum program in python O(N^2)

I am used to write code in c++ but now I am trying to learn python.我习惯用 C++ 编写代码,但现在我正在尝试学习 Python。 I came to know about the Python language and it is very popular among everyone.我开始了解 Python 语言,它在每个人中都很受欢迎。 So I thought, let's give it a shot.所以我想,让我们试一试吧。

Currently I am preparing for companies interview questions and able to solve most of them in c++.目前我正在准备公司面试问题,并且能够用 C++ 解决大部分问题。 Alongside which, I am trying to write the code for the same in Python.除此之外,我正在尝试用 Python 编写相同的代码。 For the things which I am not familiar with, I do a google search or watch tutorials etc.对于我不熟悉的东西,我会谷歌搜索或观看教程等。

While I was writing code for my previously solved easy interview questions in python, I encountered a problem.当我为之前用 Python 解决的简单面试问题编写代码时,我遇到了一个问题。

Code : Given an array of integers, return indices of the two numbers such that they add up to a specific target.代码:给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。

You may assume that each input would have exactly one solution, and you may not use the same element twice.您可以假设每个输入都只有一个解决方案,并且您不能两次使用相同的元素。

Given an array of integers, print the indices of the two numbers such that they add up to a specific target.给定一个整数数组,打印两个数字的索引,使它们相加为特定目标。

def twoNum(*arr, t):
  cur = 0
  x = 0
  y = 0

  for i in range (len(arr) - 1):

      for j in range (len(arr) - 1):
          if(i == j):
              break
          cur = arr[i] + arr[j]
          if(t == cur):
              x = arr[i]
              y = arr[j]
              break

      if(t == cur):
          break

  print(f"{x} + {y} = {x+y} ")

arr = [3, 5, -4, 8, 11, 1, -1, 6]

target = 10

twoNum(arr, t=target)

So here is the problem: I have defined x, y in function and then used x = arr[i] and y = arr[j] and I m printing those values.所以问题来了:我在函数中定义了x, y然后使用x = arr[i]y = arr[j]并且我正在打印这些值。

output coming is : is 0 + 0 = 10 (where target is 10)输出是:是 0 + 0 = 10 (目标是 10)

This is I guess probably because I am using x = 0 and y = 0 initially in the function and it seems x and y values are not updating then I saw outline section in VSCode there I saw x and y are declared twice, once at the starting of the function and second in for loop.我猜这可能是因为我最初在函数中使用x = 0y = 0并且似乎xy值没有更新然后我在 VSCode 中看到了大纲部分,我看到xy被声明了两次,一次在函数的开始和 for 循环中的第二个。

Can anyone explain to me what is going on here?谁能向我解释这里发生了什么?

For reference, here is an image of the code I wrote in C++作为参考,这是我用 C++ 编写的代码的图像

这张图片是我用cpp写的代码,

Change this:改变这个:

def twoNum(*arr, t):

to this:对此:

def twoNum(arr, t):

* is used to indicate that there will be a variable number of arguments, see this . *用于表示将有可变数量的参数,请参阅this It is not for pointers as in C++.它不像 C++ 那样用于指针。

Basically what you are trying to do is to write C code in python.基本上你要做的是用python编写C代码。 I would instead try to focus first on how to write python code in a 'pythonic' way first.相反,我会首先尝试首先关注如何以“pythonic”方式编写 python 代码。 But for your question - sloving it your way using brute force in python:但是对于您的问题 - 在 python 中使用蛮力以您的方式解决问题:

In [173]: def two_num(arr, t):
 ...:     for i in arr:
 ...:         for j in arr[i + 1: ]:
 ...:             if i + j == t:
 ...:                 print(f"{i} + {j} = {t}")
 ...:                 return

Here's a way to implement a brute force approach using a list comprehension:这是使用列表推导式实现蛮力方法的一种方法:

arr = [1,3,5,7,9]
target = 6

i,j = next((i,j) for i,n in enumerate(arr[:-1]) for j,m in enumerate(arr[i+1:],i+1) if n+m==target)

output:输出:

print(f"arr[{i}] + arr[{j}] = {arr[i]} + {arr[j]} = {target}")

# arr[0] + arr[2] = 1 + 5 = 6

Perhaps even more pythonic would be to use iterators:也许使用迭代器更像是 Pythonic:

from itertools import tee
iArr = enumerate(arr)
i,j  = next((i,j) for i,n in iArr for j,m in tee(iArr,1)[0] if n+m==target)

When you get to implementing an O(n) solution, you should look into dictionaries:当您开始实施 O(n) 解决方案时,您应该查看字典:

d   = { target-n:j for j,n in enumerate(arr) }
i,j = next( (i,d[m]) for i,m in enumerate(arr) if m in d and d[m] != i )

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

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