Új hozzászólás Aktív témák
-
cadtamas
tag
Codewars-on kaptam egy olyan feladatot, amibe beletört a bicskám.
3 működő megoldásom volt, de sajnos egyik sem elég gyors.
A feladat:
Sum of PairsGiven a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
sum_pairs([11, 3, 7, 5], 10)
# ^--^ 3 + 7 = 10
== [3, 7]
sum_pairs([4, 3, 2, 3, 4], 6)
# ^-----^ 4 + 2 = 6, indices: 0, 2 *
# ^-----^ 3 + 3 = 6, indices: 1, 3
# ^-----^ 2 + 4 = 6, indices: 2, 4
# * entire pair is earlier, and therefore is the correct answer
== [4, 2]
sum_pairs([0, 0, -2, 3], 2)
# there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)
sum_pairs([10, 5, 2, 3, 7, 5], 10)
# ^-----------^ 5 + 5 = 10, indices: 1, 5
# ^--^ 3 + 7 = 10, indices: 3, 4 *
# * entire pair is earlier, and therefore is the correct answer
== [3, 7]
Negative numbers and duplicate numbers can and will appear.NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.
A megoldásom működik, de nem elég gyors.
Lenne valakinek ötlete, hogy mivel tehetném gyorsabbá?
Csak egy iteráció van benne, hogy O(n) legyen a működés.def sum_pairs(ints, s):
list=[]
i=0
for pair1 in ints:
pair2=s-pair1
x=ints.index(pair1)
try:
y=ints[x:].index(pair2)+i
if x!=y:
list.append([x,y])
i+=1
except:
i+=1
if len(list)==0:
return None
list.sort(key=lambda x: x[1])
return [ints[list[0][0]], ints[list[0][1]]]
Új hozzászólás Aktív témák
- iPhone 16 Pro 256 GB 100% akku 2,5 év GARANCIA
- Eladó HP ProLiant Microserver Gen8 16 Gb RAM Xeon E3-1265L v2
- TP-LINK TL-SG105-M2 5-Port 2.5G asztali switch - Gar.: 2028.05.09
- Patriot Viper Venom RGB 2x16GB DDR5 6000MHz CL36 - Új, bontatlan, 5 év garancia - Eladó!
- ZOTAC RTX 5070 12GB GDDR7 Twin Edge - Új, Bontatlan - Eladó!
- Astro A50 4th Gen wireless + base station fejhallgató
- Apple iPhone 17 Pro Max 256GB Cosmic Orange használt, karcmentes 100% akku Apple garancia 2026
- ÁRGARANCIA!Épített KomPhone Ryzen 5 5600X 16/32/64GB RAM RX 7600 8GB GAMER PC termékbeszámítással
- BESZÁMÍTÁS! Nintendo Switch OLED 64GB játékkonzol garanciával hibátlan működéssel
- iPhone 13 Pro Max 128GB 100% (1év Garancia)
Állásajánlatok
Cég: PCMENTOR SZERVIZ KFT.
Város: Budapest
Cég: Laptopműhely Bt.
Város: Budapest

