Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Julianh12 avatar Julianh12 3 Точки

10.List Manipulator Fundamental Module Python.Проблем с тази задача.ПОМОЩ!!!

  1. *List Manipulator

Trifon has finally become a junior developer and has received his first task. It is about manipulating a list of integers. He is not quite happy about it since he hates manipulating lists. They are going to pay him a lot of money, though, and he is willing to give somebody half of it if to help him do his job. You, on the other hand, love lists (and money) so you decide to try your luck.

The list may be manipulated by one of the following commands

  • exchange {index} – splits the list after the given index and exchanges the places of the two resulting sub-lists. E.g. [1, 2, 3, 4, 5] -> exchange 2 -> result: [4, 5, 1, 2, 3]

    • If the index is outside the boundaries of the list, print "Invalid index"

    • Negative index is considered invalid.

  • max even/odd– returns the INDEX of the max even/odd element -> [1, 4, 8, 2, 3] -> max odd -> print 4

  • min even/odd – returns the INDEX of the min even/odd element -> [1, 4, 8, 2, 3] -> min even > print 3

    • If there are two or more equal min/max elements, return the index of the rightmost one

    • If a min/max even/odd element cannot be found, print "No matches"

  • first {count} even/odd– returns the first {count} elements -> [1, 8, 2, 3] -> first 2 even -> print [8, 2]

  • last {count} even/odd – returns the last {count} elements -> [1, 8, 2, 3] -> last 2 odd -> print [1, 3]

    • If the count is greater than the list length, print "Invalid count"

    • If there are not enough elements to satisfy the count, print as many as you can. If there are zero even/odd elements, print an empty list "[]"

  • end – stop taking input and print the final state of the list

Input

  • The input data should be read from the console.

  • On the first line, the initial list is received as a line of integers, separated by a single space

  • On the next lines, until the command "end" is received, you will receive the list manipulation commands

  • The input data will always be valid and in the format described. There is no need to check it explicitly.

Output

  • The output should be printed on the console.

  • On a separate line, print the output of the corresponding command

  • On the last line, print the final list in square brackets with its elements separated by a comma and a space

  • See the examples below to get a better understanding of your task

Constraints

  • The number of input lines will be in the range [2 … 50].

  • The list elements will be integers in the range [0 … 1000].

  • The number of elements will be in the range [1 .. 50]

  • The split index will be an integer in the range [-231 … 231 – 1]

  • first/last count will be an integer in the range [1 … 231 – 1]

  • There will not be redundant whitespace anywhere in the input

  • Allowed working time for your program: 0.1 seconds. Allowed memory: 16 MB.

Examples

Input

Output

1 3 5 7 9

exchange 1

max odd

min even

first 2 odd

last 2 even

exchange 3

end

2

No matches

[5, 7]

[]

[3, 5, 7, 9, 1]

Input

Output

1 10 100 1000

max even

first 5 even

exchange 10

min odd

exchange 0

max even

min even

end

3

Invalid count

Invalid index

0

2

0

[10, 100, 1000, 1]

Input

Output

1 10 100 1000

exchange 3

first 2 odd

last 4 odd

end

[1]

[1]

[1, 10, 100, 1000]

 





















list_number=[int(num) for num in input().split(' ')]
length_list=len(list_number)
command_input=input()
new_list=[]
first_max_odd=0
first_min_odd=0
first_min_even=0
first_max_even=0
min_odd_count=0
max_odd_count=0
min_even_count=0
max_even_count=0
counter=1
while command_input!= "end":
    command_input=command_input.split(" ")
    first_min_odd = list_number[0]
    first_max_odd = list_number[0]
    first_max_even = list_number[0]
    first_min_even = list_number[0]

    if command_input[1].isdigit() == True:
        number=int(command_input[1])
        if command_input[0]=='exchange' and (number)<=length_list:
            list_number= list_number[number+1:] + list_number[:number+1]
            print(list_number)

            print("Invalid index")



    if command_input[0]=="max" and str(command_input[1])=="odd":
        for i in range(len(list_number)):
            if list_number[i] % 2==1:
                if first_max_odd<list_number[i]:
                    first_max_odd=list_number.index(list_number[i])
                    counter+=1

        if counter==0:
                    print("No matches")

    if command_input[0]=="min" and str(command_input[1])=="odd":
        for i in range(len(list_number)):
            if list_number[i] % 2==1:
                if first_min_odd>list_number[i]:
                    first_min_odd=list_number.index(list_number[i])
                    print(first_min_odd)
                    counter+=1
        if counter==0:
                    print("No matches")

    if command_input[0]=="min" and str(command_input[1])=="even":
        for i in range(len(list_number)):
            if list_number[i] % 2==0:
                if first_min_even>list_number[i]:
                    first_min_even=list_number.index(list_number[i])
                    print(first_min_even)
                    counter+=1
        if counter==0:
                    print("No matches")

    if command_input[0]=="max" and str(command_input[1])=="even":
        for i in range(len(list_number)):
            if list_number[i] % 2==0:
                if first_max_even<list_number[i]:
                    first_max_even=list_number.index(list_number[i])
                    print(first_max_even)
                    counter+=1
        if counter==0:
                    print("No matches")

    command_input = input()

Тагове:
0
Fundamentals Module
icowwww avatar icowwww 2673 Точки

Здравей,

Бях тръгнал да го оправям, но грешките са повече от правилните неща и няма да го познаеш после. По-добре намери някое готово решение и пренапиши твоето.

Тази част от условието даже ти липсва:

  • first {count} even/odd– returns the first {count} elements -> [1, 8, 2, 3] -> first 2 even -> print [8, 2]

  • last {count} even/odd – returns the last {count} elements -> [1, 8, 2, 3] -> last 2 odd -> print [1, 3]

 

Ако ще го пренаписваш ето няколко подсказки:

-добра идея ще е да спестиш писане с добавяне на променлива за изхода от модулното деление спрямо това дали е четно или нечетно и от 2 метода да стане един. Например:

    elif command_input[0] == "first":
        divisionRes = 0
        if command_input[2] == 'odd':
            divisionRes = 1

        count = int(command_input[1])
        res = []

        if count > length_list:
            print("Invalid count")
        else:
            for i in range(len(list_number)):
                if counter == count:
                    break
                if list_number[i] % 2 == divisionRes:
                    res.append(list_number[i])
                    counter += 1
            print(res)
        counter = 0

-isDigit не е правилно, защото проверява дали всеки символ е цифра, а при отрицателно минуса не е цифра

-нулирай променлива counter след използването

-сравняваш индекс със стойност на поле

- виж кога се иска да принтираш- в exchange принтираш, а не трябва. В другите трябва, но ти не принтираш

-виж отстоянието- в exchange print("Invalid index") ти е в проверката, а не трябва 

0
08/07/2021 23:40:15
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.