Home > other >  Python is a small white for help on a exercises
Python is a small white for help on a exercises

Time:10-10

Good god, I see a exercises on the buckle, title is:
[nums given an integer array and the target value of a target, can you please find out and in the array for the target values of the two integers, and return to their array subscript,

You can assume that each input only corresponding to an answer, but you can't reuse the same elements in the array,

Example:

A given nums=[2, 7, 11, 15], target=9

Because nums nums [0] + [1]=2 + 7=9
So back to [0, 1]

Source: the power button (LeetCode)
Link: https://leetcode-cn.com/problems/two-sum
Copyright belongs to the collar of the network, commercial reproduced please contact the official authorization, non-commercial reprint please indicate the source,]
The code I wrote is:
The class Solution (object) :
Def twoSum (self, nums, target=9) :
The self. The nums=,7,11,15 [2]
The self. The nums=nums
Ans=[]
For I in nums [:] :
For j in nums [I + 1:] :
Z=I + j
If z==9:
Ans. Append (len (nums [I]))
Ans. Append (len (nums [j]))
Break
The else:
I +=1
J +=1
Print (ans)
Operation result is only an empty list, don't know where is wrong, also please teach a great god!

CodePudding user response:

Why use class,
Your code is a lot of problems, if there is something wrong with the indentation, should be inside the for loop; Find accord with the value of the later, break out of the loop; Inside the for loop, don't pointer +=1 such operation, automatically cycle... And so on, to write, write a function to be good,

CodePudding user response:

You can write
 
Def twoSum (nums, target=9) :
For I in range (len (nums) :
For j in range (1, len (nums) :
If nums nums [I] + [j]==target:
Return [I, j]
Return 0
Nums=[2, 7, 11, 15]
Print (twoSum (nums))

CodePudding user response:

thanks for a great god, and saying I hold this for my assistant has failed to solve for the write hair short and concise, and I want to ask how code is inserted into the post?

CodePudding user response:

refer to the second floor max5173 response:
you can write
 
Def twoSum (nums, target=9) :
For I in range (len (nums) :
For j in range (1, len (nums) :
If nums nums [I] + [j]==target:
Return [I, j]
Return 0
Nums=[2, 7, 11, 15]
Print (twoSum (nums))

CodePudding user response:

reference faraway_44060 reply: 3/f
thanks for a great god, and saying I hold this for my assistant has failed to solve for the write hair short and concise, and I want to ask how code is inserted into the post?
reply box above, expression options on the left, you can insert the code
  • Related