Python एल्गोरिदम
Rotate a List in Python
Move the last k values to the front while keeping their order, with one slice expression.
आप क्या सीखेंगे
- Right rotation with slicing
- Using % to handle large k
- collections.deque.rotate
Rotate right by 2
1
2
3
4
5
4
5
1
2
3
Cut and swap the two pieces
एक किनारे से बाहर जाने वाले elements दूसरे किनारे पर वापस आते हैं।
मुख्य बातें
values[-k:]is the tail that moves to the front.values[:-k]is the rest, which moves to the back.- k %=
len(values)makes k = 7 behave like k = 2 for five items.
इसका उपयोग कब करें?
- Algorithms और data structures की कार्यप्रणाली समझें।
- हर चरण देखें और edge cases जाँचें।
- समय और memory की जटिलता की तुलना करें।
देखें यह कैसे काम करता है
इंडेक्स चुनने के लिए किसी खाने पर क्लिक करें या स्लाइडर खिसकाएँ। जोड़ें या हटाएँ और देखें कि बाद के सभी तत्व क्यों खिसकते हैं।
उदाहरण कोड
main.py
def rotate_right(values, steps):
if not values:
return []
steps %= len(values)
return values[-steps:] + values[:-steps]
print(rotate_right([1, 2, 3, 4, 5], 2))
अपेक्षित आउटपुट
[4, 5, 1, 2, 3]
यह कैसे काम करता है
k को length से normalize करके दो slices जोड़े जाते हैं: समय और memory O(n) है।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- खाली input, एक element और duplicate values जाँचें।
- हर चरण के बाद state दिखाएँ।
- Performance को दूसरे solution से तुलना करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज