Ú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
- AMD Ryzen 9 / 7 / 5 9***(X) "Zen 5" (AM5)
- Milyen routert?
- Xbox Series X|S
- AMD Navi Radeon™ RX 9xxx sorozat
- Kerékpárosok, bringások ide!
- World of Tanks - MMO
- Samsung Galaxy Watch6 Classic - tekerd!
- Vicces képek
- Okos Otthon / Smart Home
- Székesfehérvár és környéke adok-veszek-beszélgetek
- További aktív témák...
- Lenovo Thinkpad P1 Gen 6 - i9-13980HX, 32GB, 2TB SSD, 16" WQUXGA (3840 2400), RTX 4090
- 15.gen! Intel Core Ultra 9 285K +16-32GB DDR5 RAM +hűtött VRM-es Z890 lap! GAR/SZÁMLA (a Te nevedre)
- OP AudioCodes C450HD Ip Phones - Szines kijelzős - Teams/ Zoom telefon - Új dobozos
- ATEN Cat 5 KVM over IP Switch Altusen KH1508AI - Új ára 284.000Ft
- AirPort Extreme 802.11n (3rd Generation) Model A1301 -
- ÁRGARANCIA! Épített KomPhone i5 12400F 16/32/64GB RAM RTX 3060 12GB GAMER PC termékbeszámítással
- Apple MacBook Air 13 M1 8GB 256GB magyar bill 1 év garancia
- AKCIÓ!!! HP ZBook Power 15 G8 Mobile Workstation i7-11850H 32GB 1000GB Nvidia RTX A2000
- Apple iPhone 14 128GB,Használt,Adatkabelel,12 hónap garanciával
- 5G LTE! Microsoft Surface Pro 8 i7-1185G7 16GB 256GB 1 év garancia
Állásajánlatok
Cég: Laptopszaki Kft.
Város: Budapest
Cég: BroadBit Hungary Kft.
Város: Budakeszi

