اذهب إلى المحتوى
  • 0

كيف أدمج int مع مصفوفة على Python؟

K@m@l

السؤال

لدي على Python المصفوفة التالية:[3,1,2,2,1,3,6,7,5,4,8]

def quick(self):
    first = self.lst[0]
    l1 = []
    l2 = []
    for item in self.lst[1:]:
        if item <= first:
            l1.append(item)
            print('this is l1:',l1)
        else:
            l2.append(item)
            print('this is l2:', l2)

        return _____

وأحاول : self.lst = l1 + first + l2

لكن أحصل على الخطأ:

self.lst = l1 + first + l2
builtins.TypeError: can only concatenate list (not "int") to list

كيف أدمج العنصر الأول من مصفوفة مع مصفوفة أخرى؟ هل هذا ممكن؟

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

first هي قيمة عددية، بينما 12و11 عناصر من مصفوفة، ويمكن دمج  القيم عبر الكود الآتي باستخدام []، هكذا:

self.lst = l1 + [first] + l2

سنستعمل خوارزمية numerous quicksort algorithms من أجل إدماج عنصر عددي مع مصفوفة:

algorithm quicksort(A, lo, hi) is
    if lo < hi then
        p := partition(A, lo, hi)
        quicksort(A, lo, p - 1)
        quicksort(A, p + 1, hi)

algorithm partition(A, lo, hi) is
    pivot := A[hi]
    i := lo        // place for swapping
    for j := lo to hi - 1 do
        if A[j] ≤ pivot then
            swap A[i] with A[j]
            i := i + 1
    swap A[i] with A[hi]
    return i

في لغة Python ستكون بالشكل الآتي:

def quicksort(A, lo, hi):
    if lo < hi:
        p = partition(A, lo, hi)
        quicksort(A, lo, p-1)
        quicksort(A, p+1, hi)

def partition(A, lo, hi):
    pivot = A[hi]
    i = lo
    for j in range(lo, hi):
        if A[j] <= pivot:
            A[i], A[j] = A[j], A[i]
            i += 1
    A[i], A[hi] = A[hi], A[i]
    return i

وبعد التجربة، سنحصل على النتيجة:

>>> lst = [3,1,2,2,1,3,6,7,5,4,8]
>>> quicksort(lst, 0, len(lst)-1)
>>> lst
[1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8]
رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...