Loading...

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

KALOYAN_123 avatar KALOYAN_123 34 Точки

Проблем с задача 10.Array Manipulator от Exercise

Здравейте колеги, от известно време имам проблем със задача 10. Array Manipulator  от Exercise. Получавам 60/100 в judge и не мога да си намеря грешката. 

Моят код: https://pastebin.com/zcCUngfd

Условието: 

10. *Array Manipulator

Trifon has finally become a junior developer and has received his first task. It's about manipulating an array of integers. He is not quite happy about it, since he hates manipulating arrays. 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 arrays (and money) so you decide to try your luck.

The array may be manipulated by one of the following commands

  • exchange {index} – splits the array after the given index, and exchanges the places of the two resulting sub-arrays. E.g. [1, 2, 3, 4, 5] -> exchange 2 -> result: [4, 5, 1, 2, 3]
    • If the index is outside the boundaries of the array, print "Invalid index"
  • 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 array 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 array "[]"
  • end – stop taking input and print the final state of the array

Input

  • The input data should be read from the console.
  • On the first line, the initial array 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 array 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 array 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 array 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]

 

0
Fundamentals Module
niyazihasan avatar niyazihasan 83 Точки
Best Answer

Здравей колега,

Малко съкратих кода ти и го коригирах:

import sys


def exchange(numbers, i):
    first_part = numbers[:i + 1]
    second_part = numbers[i + 1:]
    return second_part + first_part


def max_even_index(numbers, even):
    max_number_even = -sys.maxsize
    max_number_even_index = -1
    for i in range(len(numbers)):
        if numbers[i] % 2 == even and numbers[i] >= max_number_even:
            max_number_even = numbers[i]
            max_number_even_index = i

    if max_number_even_index == -1:
        return 'No matches'
    else:
        return max_number_even_index


def min_even_index(numbers, even):
    min_number_even = sys.maxsize
    max_number_even_index = -1
    for i in range(len(numbers)):
        if numbers[i] % 2 == even and numbers[i] <= min_number_even:
            min_number_even = numbers[i]
            max_number_even_index = i

    if max_number_even_index == -1:
        return 'No matches'
    else:
        return max_number_even_index


def first(numbers, event, counter):
    first_list_odd = []
    count = 0
    for number in numbers:
        if count == counter:
            break
        if number % 2 == event:
            first_list_odd.append(number)
            count += 1

    return first_list_odd


def last(numbers, even, counter):
    last_list_even = []
    count = 0
    for i in range(len(numbers) - 1, -1, -1):

        if count == counter:
            break

        if numbers[i] % 2 == even:
            last_list_even.append(numbers[i])
            count += 1

    return last_list_even[::-1]


numbers_list = input().split(' ')
numbers_list = [int(x) for x in numbers_list]

command_input = input().split(' ')
while command_input[0] != 'end':
    command = command_input[0]

    if command == 'exchange':
        index = int(command_input[1])
        if len(numbers_list) > index >= 0:
            numbers_list = exchange(numbers_list, index)
        else:
            print('Invalid index')
    elif command == 'max':
        criteria = command_input[1]
        res = max_even_index(numbers_list, 0 if criteria == "even" else 1)
        print(res)
    elif command == 'min':
        criteria = command_input[1]
        res = min_even_index(numbers_list, 0 if criteria == "even" else 1)
        print(res)
    elif command == 'first':
        criteria = command_input[2]
        index = int(command_input[1])
        if len(numbers_list) >= index >= -1:
            print(first(numbers_list, 0 if criteria == "even" else 1, index))
        else:
            print('Invalid count')
    elif command == 'last':
        criteria = command_input[2]
        index = int(command_input[1])
        if len(numbers_list) >= index >= -1:
            print(last(numbers_list, 0 if criteria == "even" else 1, index))
        else:
            print('Invalid count')

    command_input = input().split(' ')

print(numbers_list)

0
KALOYAN_123 avatar KALOYAN_123 34 Точки

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

1
MomchilAntonov avatar MomchilAntonov 2 Точки

Привет, колеги,

Смея да твърдя, че тази задача ми отне най - много време за решаването и, от както се занимавам.

Ето го и моето решение. 

https://pastebin.com/TBC1eDwJ

0
18/10/2020 21:36:15
MomchilAntonov avatar MomchilAntonov 2 Точки

Когато решавах задачата judge не работеше и не бях проверявал решението там. Оказа се, че ми гърмят два теста и не мога да разбера защо. Резултата ми е 80/100. Дали е възможно някой да ми помогне да открия грешката в кода си, защото в PyCharm ми излизат всички примери и с дебъгване не става. Благодаря предварително.

0
krum_43 avatar krum_43 750 Точки

Ето още едно работещо решение.

https://pastebin.com/rTgtPdWn

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