Python एल्गोरिदम

Rotate a List in Python

Move the last k values to the front while keeping their order, with one slice expression.

  • मध्यम
  • 2 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • 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 दूसरे किनारे पर वापस आते हैं।

मुख्य बातें

  1. values[-k:] is the tail that moves to the front.
  2. values[:-k] is the rest, which moves to the back.
  3. 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))
इस उदाहरण के लिए Run बटन बनाएँ

अपेक्षित आउटपुट

[4, 5, 1, 2, 3]

यह कैसे काम करता है

k को length से normalize करके दो slices जोड़े जाते हैं: समय और memory O(n) है।

मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।

अभ्यास के कार्य

बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।

  1. खाली input, एक element और duplicate values जाँचें।
  2. हर चरण के बाद state दिखाएँ।
  3. Performance को दूसरे solution से तुलना करें।
Python IDE में चलाएँ →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज