Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 68

Python Exercise Example 68

Python 100 Examples Python 100 Examples

**Problem:** Given n integers, shift the preceding numbers back by m positions in order, so that the last m numbers become the first m numbers

**Analysis:** None.

Program source code:

Example

#!/usr/bin/python

-- coding: UTF-8 --

if

name

==

'

main

'

:

n

=

int

(

raw_input

(

'

The integer n is:

\n

'

)

)

m

=

int

(

raw_input

(

'

Shift back by m positions:

\n

'

)

)

def

move

(

array

,

n

,

m

)

:

array_end

=

array

[

n

1

]

for

i

in

range

(

n

1

,-

1

,-

1

)

:

array

[

i

]

=

array

[

i

1

]

array

[

0

]

=

array_end

m

-=

1

if

m

0

:

move

(

array

,

n

,

m

)

number

=

[

]

for

i

in

range

(

n

)

:

number

.

append

(

int

(

raw_input

(

'

Enter a number:

\n

'

)

)

)

print

'

Original list:

'

,

number

move

(

number

,

n

,

m

)

print

'

After shifting:

'

,

number

The output of the above example is:


Integer n is:
8
Shift back m positions is:
5
Enter a number:
2
Enter a number:
8
Enter a number:
6
Enter a number:
1
Enter a number:
78
Enter a number:
45
Enter a number:
34
Enter a number:
2
原始列表: [2, 8, 6, 1, 78, 45, 34, 2]
移动之后: [1, 78, 45, 34, 2, 2, 8, 6]

Python 100 Examples Python 100 Examples