Skip to content

Useful independent fragments of Python code

Notifications You must be signed in to change notification settings

devandtravel/fragments_python

Repository files navigation

Fragments of Python code

This folder contains useful independent fragments of Python code.
You can use this fragments in your applications to implement some pieces of functionality.

Contents

Folder name Description Usage

letcode

middle_node Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node
head = [1, 2, 3, 4, 5]
# [3, 4, 5]
Explanation:
The middle node of the list is node 3
has_cycle Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false
head = [3,2,0,-4], pos = 1
# true
Explanation:
There is a cycle in the linked list, where the tail
connects to the 1st node (0-indexed)
count_bits Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i
n = 2
# [0, 1, 1]
Explanation:
0 --> 0 1 --> 1 2 --> 10
sum_range Given an integer array nums, handle multiple queries of the following type:
1: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class:
- NumArray(int[] nums) Initializes the object with the integer array nums.
- int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
# [null, 1, -1, -3]
Explanation:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]) numArray.sumRange(0, 2)
# return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5)
# return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5)
# return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
max_sub_array Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array.
nums = [-2,1,-3,4,-1,2,1,-5,4]
# 6
Explanation:
[4,-1,2,1] has the largest sum = 6.
max_profit You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
prices = [7,1,5,3,6,4]
# 5
climb_stairs You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
n = 3
# 3
single_number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space
nums = [4,1,2,1,2]
# 4
find_dissapeared_numbers Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums
nums = [4, 3, 2, 7, 8, 2, 3, 1]
# [5, 6]
missing_number Returns missing number in given sequence of natural numbers
print(missingNumber([1, 7, 5, 2, 4, 3]))
# 6
contains_duplicate Returns True if given nums list contains duplicate or False if given nums list does not contains duplicate
print(containsDuplicate([x for x in range(42)]))
# False

algorithms

sort

sort_bubble
sort_bubble_primitive Bubble sort like a dumb
[1, 56, 32, 6, 56, 34, 86798, 23, 54]
# [1, 6, 23, 32, 34, 54, 56, 56, 86798]
sort_bubble Bubble sort
[1, 56, 32, 6, 56, 34, 86798, 23, 54]
# [1, 6, 23, 32, 34, 54, 56, 56, 86798]
pig_it Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched
pig_it('Pig latin is cool')
# igPay atinlay siay oolcay
pig_it('Hello world !')
# elloHay orldway !
find_repeating_symbols If symbols is repeated add "(" to return, else add ")" to return
print(find_repeating_symbols('qqQjaaaa'))
# ((()((((
array2phone Converts numbers array to phone number without verification
print(array2phone([9, 9, 9, 1, 2, 3, 4, 5, 6, 7]))
# (999) 123-4567
number2cells Converts number to cells without verification
Enter cells: 123456789
```
---------
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
---------
```
is_prime Is it number prime or not?
17
# This number is prime
8
# This number is not prime
calculator Simple calculator with support of "+", "-", "/", "*", "mod", "pow", "div" operators
17
45
*
# 765.0
vowel_and_consonant Defines vowels and consonants in a string
afrhnjil
``` vowel consonant consonant consonant consonant consonant vowel consonant ```
filling_list_by_iterator Creates a sheet from the entered lines until the entered line equals "."
aaaaaa
bbbbbb
cccccc
.
# ['aaaaaa', 'bbbbbb', 'cccccc']
get_random_menu Creates a random menu from given dictionaries with dishes and prices
appetizers =
{'country greens': 12, 'onion rings': 13, 'butterbrodt': 46} main_courses =
{'super potato': 612, 'soup': 143, 'curry': 436} desserts =
{'shugar': 1, 'donat': 8, 'cake': 4}
# ['butterbrodt', 'curry', 'cake'] [46, 436, 4] 486
input_int_number Reads a line until an integer or stop word is entered
Please enter an integer:
> g
You have entered the wrong type of data.
Enter an integer or the word "stop" to exit the program: > 6
Please enter an integer: > s You have entered the wrong type of data.
Enter an integer or the word "stop" to exit the program: > stop
show_time_of_pid Shows time of process id using regular expression parsing
show_time_of_pid(
"Jul 6 14:01:23 computer.name CRON[29440]: USER (good_user)")
# Jul 6 14:03:01 pid:29440
get_prime_numbers_list Returns prime numbers list from 0 to given number
number = 30
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
args_parser Returns list of ingredients provided by command line arguments
python args_parser.py -i1 pasta -i2 rice
-i3 potato -i4 carrot -i5 onion --salt --pepper True
# The ingredients you provided are:
['pasta', 'rice', 'potato', 'carrot',
'onion', 'salt', 'pepper']
is_sequence_unic Returns True if given sequence is unic of False if given sequence is not unic
print(is_sequence_unic([x for x in range(42)]))
# True
get_cumulative_sum_list Returns cumulative sum list from digits of given number
input a number
436546
# using numpy
[4, 7, 13, 18, 22, 28]
input a number 3456347 # using list comprehension [3, 7, 12, 18, 21, 25, 32]
hangman Game. Guess the word letter by letter and survive
H A N G M A N
Type "play" to play the game, "exit" to quit: play

Input a letter: g No such letter in the word


Input a letter: 6 It is not an ASCII lowercase letter


Input a letter: i No such letter in the word


Input a letter: p

p----- Input a letter: y

py---- Input a letter: h

py-h-- Input a letter: n

py-h-n Input a letter: o

py-hon Input a letter: t You guessed the word python! You survived!

Type "play" to play the game, "exit" to quit: exit

hangman_oop OOP realisation of the HANGMAN game
hangman_regex RegEx realisation of the HANGMAN game

About

Useful independent fragments of Python code

Topics

Resources

Stars

Watchers

Forks

Languages