البرمجة

فرز قائمة الأرقام ببساطة

To achieve this, you can use a while loop that continues until the list is sorted. Inside the loop, you can ask the user to pick two locations and swap the elements at those locations. Here’s the modified code:

python
list = [4, 2, 5, 5, 6, 4, 7, 6, 9, 5] print("Here's your current list:", list) sorted = False while not sorted: print("Pick a location between 1 and 10") num = int(input()) if num <= 10 and num >= 1: print("Please pick another location between 1 and 10") num1 = int(input()) tempBox1 = list[num - 1] tempBox2 = list[num1 - 1] list[num - 1] = tempBox2 list[num1 - 1] = tempBox1 print("Your new list is", list) sorted = all(list[i] <= list[i + 1] for i in range(len(list) - 1)) print("Great job, thank you for sorting my list.")

This code will repeatedly ask the user to swap elements until the list is sorted. It uses the all function to check if all elements in the list are in ascending order. If they are, the loop will exit, and the message “Great job, thank you for sorting my list.” will be printed.

المزيد من المعلومات

بالطبع! يبدو أنك تعمل على برنامج يسمح للمستخدم بفرز قائمة من الأرقام من الأصغر إلى الأكبر باستخدام عمليات تبديل بين مواقع العناصر. الهدف هو تعلم المستخدم كيفية فرز القائمة بنفسه. البرنامج يستخدم حلقة while لتكرار عملية تبديل العناصر حتى تكون القائمة مرتبة بشكل صحيح.

قمت بإنشاء قائمة افتراضية list تحتوي على الأرقام [4, 2, 5, 5, 6, 4, 7, 6, 9, 5]، ثم تطبع القائمة الأولية للمستخدم. ثم تقوم الحلقة while بتكرار العمليات التالية:

  1. تطلب من المستخدم اختيار موقعين في القائمة.
  2. تقوم بتبديل العناصر في هذين الموقعين.
  3. تطبع القائمة الجديدة.
  4. تستخدم دالة all للتحقق مما إذا كانت القائمة مرتبة بشكل صحيح.

إذا كانت القائمة ليست مرتبة، فإن الحلقة while ستستمر في تكرار العمليات. عندما تصبح القائمة مرتبة، سينتهي البرنامج ويظهر رسالة “Great job, thank you for sorting my list.”

زر الذهاب إلى الأعلى