تمارين فهرسة القوائم والأطوال
لديك قائمة things وقيمة to_find. اطبع أول فهرس تظهر عنده to_find داخل القائمة؛ أي أصغر عدد i يجعل things[i] مساوية لـto_find. مثلًا، إذا كانت القيم:
things = ['on', 'the', 'way', 'to', 'the', 'store']
to_find = 'the'
فيجب أن يطبع البرنامج 1.
يمكنك افتراض أن to_find موجودة في القائمة مرة واحدة على الأقل.
You will need to look at all the possible indices of
thingsand check which one is the answer.To look at all possible indices, you will need a loop over
range(len(things)).To check if an index is the answer, you will need to use:
if
- the index in a subscript
==
Since you're looking for the first index, you need to stop the loop once you find one.
You learned how to stop a loop in the middle recently.
You need to use
break.
جميل!
وبالمناسبة، الفهرسة وlen() تعملان مع النصوص أيضًا. جرّبهما في الطرفية.
إليك تمرينًا آخر. لديك نصان متساويان في الطول، مثل:
string1 = 'Hello' string2 = 'World' اطبعهما رأسيًا جنبًا إلى جنب، مع مسافة بين كل محرفين متقابلين:
H W e o l r l l o d
Did you experiment with indexing and
len()with strings in the shell?Forget loops for a moment. How would you print just the first line, which has the first character of each of the two strings?
In the second line you want to print the second character of each string, and so on.
You will need a
forloop.You will need indexing (subscripting).
You will need
range.You will need
len.You will need
+.You will need to index both strings.
You will need to pass the same index to both strings each time to retrieve matching characters.
رائع!
غالبًا يشبه حلك شيئًا كهذا:
for i in range(len(string1)):
char1 = string1[i]
char2 = string2[i]
print(char1 + ' ' + char2)
لكن هذا لا يعمل جيدًا إذا كان النصان مختلفين في الطول. بل إن الخطأ يختلف بحسب ما إذا كان string1 أو string2 هو الأطول.
تحديك التالي هو إصلاح هذه المشكلة بملء المحارف «المفقودة» بمسافات.
فمثلًا، إذا كانت القيم:
string1 = 'Goodbye' string2 = 'World' فيجب أن يكون الناتج:
G W o o o r d l b d y e وإذا كانت القيم:
string1 = 'Hello' string2 = 'Elizabeth' فيجب أن يكون الناتج:
H E e l l i l z o a b e t h
The solution has the same overall structure and essential elements of the previous solution, but it's significantly longer and will require a few additional ideas and pieces.
What should go inside
range()? Neitherlen(string1)norlen(string2)is good enough.You want a loop iteration for every character in the longer string.
That means you need
range(<length of the longest string>)In other words you need to find the biggest of the two values
len(string1)andlen(string2). You've already done an exercise like that.Once you've sorted out
for i in range(...),iwill sometimes be too big to be a valid index for both strings. You will need to check if it's too big before indexing.Remember, the biggest valid index for
string1islen(string1) - 1.len(string1)is too big.You will need two
ifstatements, one for each string.You will need to set e.g.
char1 = ' 'whenstring1[i]is not valid.
عمل ممتاز! خذ استراحة قصيرة؛ لقد استحققتها.