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

Commit 2e0e524

Browse files
committed
Add more snippe ts
1 parent 050ccb5 commit 2e0e524

File tree

1 file changed

+240
-0
lines changed

1 file changed

+240
-0
lines changed

‎public/data/python.json

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,74 @@
325325
],
326326
"tags": ["python", "list", "duplicates", "utility"],
327327
"author": "dostonnabotov"
328+
},
329+
{
330+
"title": "Find Duplicates in a List",
331+
"description": "Identifies duplicate elements in a list.",
332+
"code": [
333+
"def find_duplicates(lst):",
334+
" seen = set()",
335+
" duplicates = set()",
336+
" for item in lst:",
337+
" if item in seen:",
338+
" duplicates.add(item)",
339+
" else:",
340+
" seen.add(item)",
341+
" return list(duplicates)",
342+
"",
343+
"# Usage:",
344+
"data = [1, 2, 3, 2, 4, 5, 1]",
345+
"print(find_duplicates(data)) # Output: [1, 2]"
346+
],
347+
"tags": ["python", "list", "duplicates", "utility"],
348+
"author": "axorax"
349+
},
350+
{
351+
"title": "Partition List",
352+
"description": "Partitions a list into sublists of a given size.",
353+
"code": [
354+
"def partition_list(lst, size):",
355+
" for i in range(0, len(lst), size):",
356+
" yield lst[i:i + size]",
357+
"",
358+
"# Usage:",
359+
"data = [1, 2, 3, 4, 5, 6, 7]",
360+
"partitions = list(partition_list(data, 3))",
361+
"print(partitions) # Output: [[1, 2, 3], [4, 5, 6], [7]]"
362+
],
363+
"tags": ["python", "list", "partition", "utility"],
364+
"author": "axorax"
365+
},
366+
{
367+
"title": "Find Intersection of Two Lists",
368+
"description": "Finds the common elements between two lists.",
369+
"code": [
370+
"def list_intersection(lst1, lst2):",
371+
" return [item for item in lst1 if item in lst2]",
372+
"",
373+
"# Usage:",
374+
"list_a = [1, 2, 3, 4]",
375+
"list_b = [3, 4, 5, 6]",
376+
"print(list_intersection(list_a, list_b)) # Output: [3, 4]"
377+
],
378+
"tags": ["python", "list", "intersection", "utility"],
379+
"author": "axorax"
380+
},
381+
{
382+
"title": "Find Maximum Difference in List",
383+
"description": "Finds the maximum difference between any two elements in a list.",
384+
"code": [
385+
"def max_difference(lst):",
386+
" if not lst or len(lst) < 2:",
387+
" return 0",
388+
" return max(lst) - min(lst)",
389+
"",
390+
"# Usage:",
391+
"data = [10, 3, 5, 20, 7]",
392+
"print(max_difference(data)) # Output: 17"
393+
],
394+
"tags": ["python", "list", "difference", "utility"],
395+
"author": "axorax"
328396
}
329397
]
330398
},
@@ -655,6 +723,22 @@
655723
],
656724
"tags": ["python", "random", "string", "utility"],
657725
"author": "dostonnabotov"
726+
},
727+
{
728+
"title": "Convert Bytes to Human-Readable Format",
729+
"description": "Converts a size in bytes to a human-readable format.",
730+
"code": [
731+
"def bytes_to_human_readable(num):",
732+
" for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:",
733+
" if num < 1024:",
734+
" return f\"{num:.2f} {unit}\"",
735+
" num /= 1024",
736+
"",
737+
"# Usage:",
738+
"print(bytes_to_human_readable(123456789)) # Output: '117.74 MB'"
739+
],
740+
"tags": ["python", "bytes", "format", "utility"],
741+
"author": "axorax"
658742
}
659743
]
660744
},
@@ -904,6 +988,72 @@
904988
],
905989
"tags": ["python", "error-handling", "division", "utility"],
906990
"author": "e3nviction"
991+
},
992+
{
993+
"title": "Retry Function Execution on Exception",
994+
"description": "Retries a function execution a specified number of times if it raises an exception.",
995+
"code": [
996+
"import time",
997+
"",
998+
"def retry(func, retries=3, delay=1):",
999+
" for attempt in range(retries):",
1000+
" try:",
1001+
" return func()",
1002+
" except Exception as e:",
1003+
" print(f\"Attempt {attempt + 1} failed: {e}\")",
1004+
" time.sleep(delay)",
1005+
" raise Exception(\"All retry attempts failed\")",
1006+
"",
1007+
"# Usage:",
1008+
"def unstable_function():",
1009+
" raise ValueError(\"Simulated failure\")",
1010+
"",
1011+
"# Retry 3 times with 2 seconds delay:",
1012+
"try:",
1013+
" retry(unstable_function, retries=3, delay=2)",
1014+
"except Exception as e:",
1015+
" print(e) # Output: All retry attempts failed"
1016+
],
1017+
"tags": ["python", "error-handling", "retry", "utility"],
1018+
"author": "axorax"
1019+
},
1020+
{
1021+
"title": "Validate Input with Exception Handling",
1022+
"description": "Validates user input and handles invalid input gracefully.",
1023+
"code": [
1024+
"def validate_positive_integer(input_value):",
1025+
" try:",
1026+
" value = int(input_value)",
1027+
" if value < 0:",
1028+
" raise ValueError(\"The number must be positive\")",
1029+
" return value",
1030+
" except ValueError as e:",
1031+
" return f\"Invalid input: {e}\"",
1032+
"",
1033+
"# Usage:",
1034+
"print(validate_positive_integer('10')) # Output: 10",
1035+
"print(validate_positive_integer('-5')) # Output: Invalid input: The number must be positive",
1036+
"print(validate_positive_integer('abc')) # Output: Invalid input: invalid literal for int() with base 10: 'abc'"
1037+
],
1038+
"tags": ["python", "error-handling", "validation", "utility"],
1039+
"author": "axorax"
1040+
},
1041+
{
1042+
"title": "Handle File Not Found Error",
1043+
"description": "Attempts to open a file and handles the case where the file does not exist.",
1044+
"code": [
1045+
"def read_file_safe(filepath):",
1046+
" try:",
1047+
" with open(filepath, 'r') as file:",
1048+
" return file.read()",
1049+
" except FileNotFoundError:",
1050+
" return \"File not found!\"",
1051+
"",
1052+
"# Usage:",
1053+
"print(read_file_safe('nonexistent.txt')) # Output: 'File not found!'"
1054+
],
1055+
"tags": ["python", "error-handling", "file", "utility"],
1056+
"author": "axorax"
9071057
}
9081058
]
9091059
},
@@ -942,6 +1092,96 @@
9421092
],
9431093
"tags": ["python", "datetime", "utility"],
9441094
"author": "e3nviction"
1095+
},
1096+
{
1097+
"title": "Generate Date Range List",
1098+
"description": "Generates a list of dates between two given dates.",
1099+
"code": [
1100+
"from datetime import datetime, timedelta",
1101+
"",
1102+
"def generate_date_range(start_date, end_date):",
1103+
" if start_date > end_date:",
1104+
" raise ValueError(\"start_date must be before end_date\")",
1105+
"",
1106+
" current_date = start_date",
1107+
" date_list = []",
1108+
" while current_date <= end_date:",
1109+
" date_list.append(current_date)",
1110+
" current_date += timedelta(days=1)",
1111+
"",
1112+
" return date_list",
1113+
"",
1114+
"# Usage:",
1115+
"start = datetime(2023, 1, 1)",
1116+
"end = datetime(2023, 1, 5)",
1117+
"dates = generate_date_range(start, end)",
1118+
"for d in dates:",
1119+
" print(d.strftime('%Y-%m-%d'))",
1120+
"# Output: '2023年01月01日', '2023年01月02日', '2023年01月03日', '2023年01月04日', '2023年01月05日'"
1121+
],
1122+
"tags": ["python", "datetime", "range", "utility"],
1123+
"author": "axorax"
1124+
},
1125+
{
1126+
"title": "Determine Day of the Week",
1127+
"description": "Calculates the day of the week for a given date.",
1128+
"code": [
1129+
"from datetime import datetime",
1130+
"",
1131+
"def get_day_of_week(date):",
1132+
" days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']",
1133+
" try:",
1134+
" return days[date.weekday()]",
1135+
" except IndexError:",
1136+
" raise ValueError(\"Invalid date\")",
1137+
"",
1138+
"# Usage:",
1139+
"date = datetime(2023, 1, 1)",
1140+
"day = get_day_of_week(date)",
1141+
"print(day) # Output: 'Sunday'"
1142+
],
1143+
"tags": ["python", "datetime", "weekday", "utility"],
1144+
"author": "axorax"
1145+
},
1146+
{
1147+
"title": "Check if Date is a Weekend",
1148+
"description": "Checks whether a given date falls on a weekend.",
1149+
"code": [
1150+
"from datetime import datetime",
1151+
"",
1152+
"def is_weekend(date):",
1153+
" try:",
1154+
" return date.weekday() >= 5 # Saturday = 5, Sunday = 6",
1155+
" except AttributeError:",
1156+
" raise TypeError(\"Input must be a datetime object\")",
1157+
"",
1158+
"# Usage:",
1159+
"date = datetime(2023, 1, 1)",
1160+
"weekend = is_weekend(date)",
1161+
"print(weekend) # Output: True (Sunday)"
1162+
],
1163+
"tags": ["python", "datetime", "weekend", "utility"],
1164+
"author": "axorax"
1165+
},
1166+
{
1167+
"title": "Get Number of Days in a Month",
1168+
"description": "Determines the number of days in a specific month and year.",
1169+
"code": [
1170+
"from calendar import monthrange",
1171+
"from datetime import datetime",
1172+
"",
1173+
"def get_days_in_month(year, month):",
1174+
" try:",
1175+
" return monthrange(year, month)[1]",
1176+
" except ValueError as e:",
1177+
" raise ValueError(f\"Invalid month or year: {e}\")",
1178+
"",
1179+
"# Usage:",
1180+
"days = get_days_in_month(2023, 2)",
1181+
"print(days) # Output: 28 (for non-leap year February)"
1182+
],
1183+
"tags": ["python", "datetime", "calendar", "utility"],
1184+
"author": "axorax"
9451185
}
9461186
]
9471187
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /