Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit788d95b

Browse files
added rotate_array.py (#13336)
* added rotate_array.py* [pre-commit.ci] auto fixes from pre-commit.com hooksfor more information, seehttps://pre-commit.ci* fixed issues* [pre-commit.ci] auto fixes from pre-commit.com hooksfor more information, seehttps://pre-commit.ci* fixed reverse issue* added doctests* [pre-commit.ci] auto fixes from pre-commit.com hooksfor more information, seehttps://pre-commit.ci* changed k to steps for a descriptive name* fixed non-pep---------Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parentf0d5949 commit788d95b

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
defrotate_array(arr:list[int],steps:int)->list[int]:
2+
"""
3+
Rotates a list to the right by steps positions.
4+
5+
Parameters:
6+
arr (List[int]): The list of integers to rotate.
7+
steps (int): Number of positions to rotate. Can be negative for left rotation.
8+
9+
Returns:
10+
List[int]: Rotated list.
11+
12+
Examples:
13+
>>> rotate_array([1, 2, 3, 4, 5], 2)
14+
[4, 5, 1, 2, 3]
15+
>>> rotate_array([1, 2, 3, 4, 5], -2)
16+
[3, 4, 5, 1, 2]
17+
>>> rotate_array([1, 2, 3, 4, 5], 7)
18+
[4, 5, 1, 2, 3]
19+
>>> rotate_array([], 3)
20+
[]
21+
"""
22+
23+
n=len(arr)
24+
ifn==0:
25+
returnarr
26+
27+
steps=steps%n
28+
29+
ifsteps<0:
30+
steps+=n
31+
32+
defreverse(start:int,end:int)->None:
33+
"""
34+
Reverses a portion of the list in place from index start to end.
35+
36+
Parameters:
37+
start (int): Starting index of the portion to reverse.
38+
end (int): Ending index of the portion to reverse.
39+
40+
Returns:
41+
None
42+
43+
Examples:
44+
>>> example = [1, 2, 3, 4, 5]
45+
>>> def reverse_test(arr, start, end):
46+
... while start < end:
47+
... arr[start], arr[end] = arr[end], arr[start]
48+
... start += 1
49+
... end -= 1
50+
>>> reverse_test(example, 0, 2)
51+
>>> example
52+
[3, 2, 1, 4, 5]
53+
>>> reverse_test(example, 2, 4)
54+
>>> example
55+
[3, 2, 5, 4, 1]
56+
"""
57+
58+
whilestart<end:
59+
arr[start],arr[end]=arr[end],arr[start]
60+
start+=1
61+
end-=1
62+
63+
reverse(0,n-1)
64+
reverse(0,steps-1)
65+
reverse(steps,n-1)
66+
67+
returnarr
68+
69+
70+
if__name__=="__main__":
71+
examples= [
72+
([1,2,3,4,5],2),
73+
([1,2,3,4,5],-2),
74+
([1,2,3,4,5],7),
75+
([],3),
76+
]
77+
78+
forarr,stepsinexamples:
79+
rotated=rotate_array(arr.copy(),steps)
80+
print(f"Rotate{arr} by{steps}:{rotated}")

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp