blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7d7ac0d51758458af03015b2b016c7608d266232
fminor5/TonyGaddisCh13
/p13-7button_demo.py
849
4.28125
4
import tkinter import tkinter.messagebox class MyGUI: def __init__(self): self.main_window = tkinter.Tk() # Create a Button widget. The text 'Click Me!' should appear on the # face of the Button. The do_something method should be executed when # the user clicks the Button. self.my_button = tkinter.Button(self.main_window, text='Click Me!', command=self.do_something) # Pack button self.my_button.pack() # Enter the tkinter main loop tkinter.mainloop() # The do_something method is a callback function for the Button widget. def do_something(self): # Display an info dialog box. tkinter.messagebox.showinfo('Response', 'Thanks for clicking the button.') MyGUI()
true
7cdf5ba9b7c9cf90abcc0f0592cff859ecde851a
thangln1003/python-practice
/python/trie/208-implementTrie_I.py
2,294
4.125
4
""" 208. Implement Trie (Prefix Tree) (Medium) https://leetcode.com/problems/implement-trie-prefix-tree/ Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true !Note: !You may assume that all inputs are consist of lowercase letters a-z. !All inputs are guaranteed to be non-empty strings. """ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEnd = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = self._getNode() def _getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def _searchPrefix(self, prefix: str) -> TrieNode: node = self.root for level in range(len(word)): index = self._charToIndex(word[level]) if not node.children[index]: return None node = node.children[index] return node def insert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for level in range(len(word)): index = self._charToIndex(word[level]) if not node.children[index]: node.children[index] = self._getNode() node = node.children[index] node.isEnd = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self._searchPrefix(word) return node != None and node.isEnd def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self._searchPrefix(prefix) return node != None if __name__ == "__main__": word = "a" prefix = "app" obj = Trie() # obj.insert(word) param_2 = obj.search(word) # param_3 = obj.startsWith(prefix) print("Search result is {}".format(param_2)) # print("StartsWith result is {}".format(param_3))
true
a670acd7b46c33e6c19dbd4130be7b20860bc89e
thangln1003/python-practice
/python/1-string/438-findAllAnagrams.py
2,175
4.125
4
""" 438. Find All Anagrams in a String (Medium) https://leetcode.com/problems/find-all-anagrams-in-a-string/ Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. *Input: s: "cbaebabacd" p: "abc" *Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". *Input: s: "abab" p: "ab" *Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". """ from collections import Counter from typing import List class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: lengthP, lengthS = len(p), len(s) if not s or not p or lengthS < lengthP: return [] def checkAnagrams(arrS: [], arrP: []) -> bool: for i in range(len(arrP)): if arrP[i] != arrS[i]: return False return True arrS = [0]*26 # "cbaebabacd" arrP = [0]*26 # "abc" startWindow = 0 result = [] for i in range(lengthP): arrS[ord(s[i]) - ord('a')] += 1 for j in range(lengthP): arrP[ord(p[j]) - ord('a')] += 1 for endWindow in range(len(s)-1): if endWindow >= lengthP - 1: if checkAnagrams(arrS, arrP): result.append(startWindow) arrS[ord(s[startWindow]) - ord('a')] -= 1 arrS[ord(s[endWindow+1]) - ord('a')] += 1 startWindow += 1 if checkAnagrams(arrS, arrP): result.append(lengthS - lengthP) return result if __name__ == "__main__": # s, p = "cbaebabacd", "abc" s, p = "abab", "ab" solution = Solution() result = solution.findAnagrams(s, p) print(result)
true
3c5bc82862d3f05da5ce7d0807de1e5d0e735e7d
rasmiranjanrath/PythonBasics
/Set.py
521
4.25
4
#A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets. set_of_link={'google.com','facebook.com','yahoo.com','jio.com'} #loop through set def loop_through_set(): for links in set_of_link: print(links) loop_through_set() #check if item exists or not if 'google.com' in set_of_link: print('yes') #add an element to set set_of_link.add('example.com') loop_through_set() #add multiple items to set set_of_link.update(['random.com','gooje.com']) loop_through_set()
true
5b7543e3b0fc8cf24b22afb680da2e4f28a1b9ac
LeenaKH123/python3
/02_classes-objects-methods/02_04_classy_shapes.py
1,078
4.4375
4
# Create two classes that model a rectangle and a circle. # The rectangle class should be constructed by length and width # while the circle class should be constructed by radius. # # Write methods in the appropriate class so that you can calculate # the area of both the rectangle and the circle, the perimeter # of the rectangle, and the circumference of the circle. class Rectangle: def __init__(self, length, width): self.length = length self.width = width def __str__(self): return f"{self.length},{self.width}" def RectanglePerimeter(self): perimeter = 2 * (self.length + self.width) print(perimeter) class Circle: def __init__(self, circleradius): self.circleradius = circleradius def circumference(self): perimter = 2* 3.14 * self.circleradius print(perimter) def __str__(self): return f"{self.circleradius}" rectangle1 = Rectangle(3,4) print(rectangle1) rectangle1.RectanglePerimeter() circle1 = Circle(2) print(circle1) circle1.circumference()
true
f7fe24777d99688ce0f67c7f16ee4788d4c694d4
LeenaKH123/python3
/02_classes-objects-methods/02_06_freeform.py
695
4.125
4
# Write a script with three classes that model everyday objects. # - Each class should have an `__init__()` method that sets at least 3 attributes # - Include a `__str__()` method in each class that prints out the attributes # in a nicely formatted string. # - Overload the `__add__()` method in one of the classes so that it's possible # to add attributes of two instances of that class using the `+` operator. # - Create at least two instances of each class. # - Once the objects are created, change some of their attribute values. # # Be creative. Have some fun. :) # Using objects you can model anything you want: # Animals, paintings, card games, sports teams, trees, people etc...
true
0c9ff7275e96c309b823844d42ac93dcc4dd2082
halida/handout_6.00
/ps3a.py
704
4.125
4
#!/usr/bin/env python #-*- coding:utf-8 -*- """ module: ps3a """ from string import * def countSubStringMatch(target, key): i = 0 k = 0 while i != -1: i = find(target, key, i) if i < 0: break i += len(key) k += 1 return k def countSubStringMatchRecursive(target, key): i = find(target, key) if i >= 0: return 1 + countSubStringMatchRecursive(target[i+len(key):], key) else: return 0 def main(): """ >>> countSubStringMatch('abcdfaacc', 'a') == 3 True >>> countSubStringMatchRecursive('abcdfaacc', 'a') == 3 True """ import doctest doctest.testmod() if __name__=="__main__": main()
false
d9dcd1205b58e9f5502d6b2fb183b95ff6e24deb
arkoghoshdastidar/python-3.10
/14_for_loop.py
524
4.5
4
# for loop can be used to traverse through indexed as well as un-indexed collections. fruits = ["apple", "mango", "banana", "cherry"] for x in fruits: if x == "cherry": continue print(x) else: print("fruits list completely traverse!!") # range function range(starting_index, last_index, step) for x in range(1, 11, 2): print(x) else: # NOTE: The else block will not be executed if the loop is broken by break statement print("for loop traversed successfully!!")
true
f4fc56008cdb9d12034813951f4ae6673bb32b5d
arkoghoshdastidar/python-3.10
/19_iterator.py
899
4.15625
4
# All python collections have their own inbuilt iterators list1 = list(("apple", "banana", "cherry", "guava")) list_iter = list1.__iter__() print(next(list_iter)) print(next(list_iter)) print(next(list_iter)) print(next(list_iter)) tuple1 = tuple(("apple", "mango", "pineapple")) tuple_iter = tuple1.__iter__() print(next(tuple_iter)) print(next(tuple_iter)) print(next(tuple_iter)) # Creating iterator for user made data types class Count: def __init__(self): self.num = 1 def __iter__(self): return self def __next__(self): x = self.num self.num += 1 if x <= 10: return x else: raise StopIteration C1 = Count() Count_iter = iter(C1) print(next(Count_iter)) print(next(Count_iter)) print(next(Count_iter)) print(next(Count_iter)) print(next(Count_iter)) print(next(Count_iter)) print(next(Count_iter))
false
4ded74124b0a8a72d4f3ef553470bc01609be6b9
shireeny1/Python
/python_basics_104_lists.py
2,208
4.4375
4
# Lists in Python # Lists are ordered by index ## AKA --> Arrays or (confusingly) as objects in JavaScript # Syntax # Declare lists using [] # Separate objects using , # var_list_name = [0 , 1, 2, 3,..] --> index numbers crazy_x_landlords = ['Sr. Julio', 'Jane', 'Alfred', 'Marksons'] print(crazy_x_landlords) print(type(crazy_x_landlords)) # How to access record number 3 in the list: --> record number - 1 print(crazy_x_landlords[2]) # Accessing other location print(crazy_x_landlords[0]) print(crazy_x_landlords[-1]) # New list of places to live places_to_live = ['California', 'Rio de Janeiro', 'Melbourne', 'Manchester', 'Singapore'] # Re-assign an index places_to_live[3] = 'Hawaii' print(places_to_live[3]) # Method .append(object) print(len(places_to_live)) places_to_live.append('LA') print(len(places_to_live)) print(places_to_live) # .insert(index,,object) places_to_live.insert(0, 'Lisboa') print(places_to_live) # .pop(index) --> removes from list at specific index places_to_live.pop(3) print(places_to_live) # List slicing # This is used to manage lists # Prints from index to end of the list print(places_to_live[3:]) # Prints from index to the start of the list (not inclusive the index '3') print(places_to_live[:3]) # Print from specified index to second specified index (not inclusive of the index) print(places_to_live[0:3]) print(places_to_live[1:3]) # Skip slicing list_exp = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] print(list_exp) print(list_exp[2:10:3]) print(list_exp[::-1]) # Tuples --> Immutable lists # Syntax # Defined using (object, object) mortal_enemies = ('Mario', 'Sailormoon', 'MOON CAKE', 'Jerry', 'Berry') print(type(mortal_enemies)) # If you try re-assign it will break # print(mortal_enemies[0]) = 'Goku' # print(mortal_enemies) # Example of creating amazing list for end of the world survival list_of_kit = [] item_1 = input('What is your first item to keep? ') list_of_kit.append(item_1) item_2 = input('What is your second item to keep? ') list_of_kit.append(item_2) item_3 = input('What is your third item to keep? ') list_of_kit.append(item_3) print('Hey there, You have a lot of stuff!' + ' ' + str(list_of_kit))
true
5e7dbf191a2b1396cb23f1bdc870d8b1dbcbff7e
nirzaf/python_excersize_files
/section9/lecture_043.py
289
4.125
4
### Tony Staunton ### Working with empty lists # Empty shopping cart shopping_cart = ['pens'] if shopping_cart: for item in shopping_cart: print("Adding " + item + " to your cart.") print("Your order is complete.") else: print("You must select an item before proceeding.")
true
edb115e5a043e70668684de5ac215346c59df01b
nirzaf/python_excersize_files
/section9/9. Branching and Conditions/8.1 lecture_040.py.py
324
4.21875
4
### 28 / 10 / 2016 ### Tony Staunton ### Checking if a value is not in a list # Admin users admin_users = ['tony', 'frank'] # Ask for username username = input("Please enter your username?") # Check if user is an admin user if username not in admin_users: print("You do not have access.") else: print("Access granted.")
true
d4d7ddf9bac3658959f888dda9c75d49491fdfad
AnetaEva/NetPay
/NetPay.py
837
4.25
4
employee_name = input('Name of employee: ') weekly_work_hours = float(input('How many hours did you work this week?: ')) pay_rate = float(input('What is your hourly rate?: $')) #Net Pay without seeing the breakdown from gross pay and tax using the pay rate * work hours * (1 - 0.05) net_pay = pay_rate * weekly_work_hours * (1 - 0.05) print('Net Pay without breakdown.') print('- Net Pay: $', format(net_pay, '.2f'), sep='') #Net Pay with breakdown of gross pay, tax, and Net Pay using tax rate 0.05 tax_rate = 0.05 gross_pay = weekly_work_hours * pay_rate tax = gross_pay * tax_rate alternate_net_pay = gross_pay - tax print('Net Pay with breakdown.') print('- Gross Pay: $', format(gross_pay, '.2f'), sep='') print('- Tax: $', format(tax, '.2f'), sep='') print('- Alternate net pay: $', format(alternate_net_pay, '.2f'), sep='')
true
43b8107a49178ce617fa90e55b0b3d612be117bb
cornielleandres/Intro-Python
/src/day-1-toy/fileio.py
403
4.1875
4
# Use open to open file "foo.txt" for reading foo = open('foo.txt') # Print all the lines in the file for line in foo: print(line) # Close the file foo.close() # Use open to open file "bar.txt" for writing bar = open('bar.txt', 'w') # Use the write() method to write three lines to the file lines = ['first line\n', 'second line\n', 'third line'] bar.writelines(lines) # Close the file bar.close()
true
dc6c18763a5cdbb0e8ec0ddee339010e5ede0d7d
shuxianghuafu/IntroductionToAlgorithms
/chapter02/MERGE-SORT/mergeSort.py
1,443
4.1875
4
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """ author : xiaohai email : xiaohaijin@outlook.com """ def merge(left, right): """ 归并排序的辅助函数 """ array = [] left_cursor, right_cursor = 0, 0 """ 开始收集两个子‘数组’中的元素 """ while left_cursor < len(left) and right_cursor < len(right): if left[left_cursor] <= right[right_cursor]: array.append(left[left_cursor]) left_cursor += 1 else: array.append(right[right_cursor]) right_cursor += 1 """ 收集两个'数组'之中仍有残存元素的那个数组 """ for i in range(left_cursor, len(left)): array.append(left[i]) for i in range(right_cursor, len(right)): array.append(right[i]) """ 返回收集的两个子数组 """ return array def mergeSort(arr): """ 归并排序,实施递归调用进行解决 """ # 处理不用排序的情况即给出递归截止的条件 if len(arr) <= 1: return arr # 进行二分的处理 middle = int(len(arr)/2) """ 进行递归的调用 """ left = mergeSort(arr[:middle]) right = mergeSort(arr[middle:]) return merge(left, right) if __name__ == '__main__': import random arr = [] for i in range(20): arr.append(random.randrange(100)) print(arr) arr = mergeSort(arr) print(arr)
false
08138bc7d63a9cc15ec13c8cf33e60cce825d6da
VinidiktovEvgenijj/PY111-april
/Tasks/a0_my_stack.py
980
4.3125
4
""" My little Stack """ my_stack = [] def push(elem) -> None: """ Operation that add element to stack :param elem: element to be pushed :return: Nothing """ global my_stack my_stack.append(elem) return None def pop(): """ Pop element from the top of the stack :return: popped element """ global my_stack if my_stack == []: return None else: pop_elem = my_stack[-1] del my_stack[-1] return pop_elem def peek(ind=0): """ Allow you to see at the element in the stack without popping it :param ind: index of element (count from the top) :return: peeked element """ global my_stack if ind > len(my_stack) - 1: return None else: return my_stack[ind - 1] def clear() -> None: """ Clear my stack :return: None """ global my_stack my_stack = [] return None
true
40b0eab57ae17cdb77045d0156e53e0ba073abd2
Viiic98/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
352
4.15625
4
#!/usr/bin/python3 def inherits_from(obj, a_class): """ inherits_from Check if obj is a sub class of a_class Return: True if it is a subclass False if it is not a subclass """ if type(obj) is not a_class and issubclass(type(obj), a_class): return True else: return False
true
6e4f90c3dd486241de794f0d071a0601fcc1ea44
ysjwdaypm/study
/python/pyfiles/deco.py
510
4.4375
4
""" 问题: Python的函数定义中有两种特殊的情况,即出现*,**的形式。 如:def myfun1(username, *keys)或def myfun2(username, **keys)等。 解释: * 用来传递任意个无名字参数,这些参数会一个Tuple的形式访问。 **用来处理传递任意个有名字的参数,这些参数用dict来访问。* """ def deco(fun): def inner(*args,**kwargs): return fun(*args,**kwargs) return inner @deco def my_func(*args): print(args) my_func(1,2,3)
false
d15a5aa268e7d312cef56fdd19be4efe2a0b9fdc
dscottboggs/practice
/HackerRank/diagonalDifference/difference.py
1,391
4.5
4
from typing import List """The absolute value of the difference between the diagonals of a 2D array. input should be: Width/Height of the array on the first input line any subsequent line should contain the space-separated values. """ def right_diagonal_sum(arrays: List[List[int]]) -> int: """Sum the right diagonal of the given 2d array.""" outsum = 0 for index in range(len(arrays)): outsum += arrays[index][index] return outsum def left_diagonal_sum(arrays: List[List[int]]) -> int: """Sum the left diagonal of the given 2d array.""" outsum = 0 row = 0 column = len(arrays) - 1 while row < len(arrays): outsum += arrays[row][column] column -= 1 row += 1 return outsum def diagonal_difference(arrays: List[List[int]]) -> int: """Get the absolute value of the difference between the diagonals. @param arrays: must be a sqare matrix - i.e. an array of arrays where the number of arrays is the same as the number of values in each array. """ return abs(right_diagonal_sum(arrays) - left_diagonal_sum(arrays)) def main(): rows = int(input("Number of arrays to be specified.")) a = [ int(element) for element in [ input(f"Array #{row}: ").split(' ') for row in range(rows) ] ] print(diagonal_difference(a))
true
b4729ac8cb9c4d7ba23b8fb98149a734ef517a93
yawitzd/dsp
/python/q8_parsing.py
1,343
4.375
4
#The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. # The below skeleton is optional. You can use it or you can write the script with an approach of your choice. import csv def read_data(data): '''Returns 'fbd', a list of lists''' fb = open('football.csv') csv_fb = csv.reader(fb) fbd = [] for row in csv_fb: fbd.append(row) fb.close() return fbd def add_score_difference(parsed_data): '''Adds a column to the data for score difference''' d = parsed_data for i in range(len(d)): if i == 0: d[i].append('Score Difference') else: d[i].append(int(d[i][5]) - int(d[i][6])) return d def get_min_team(parsed_data): d = add_score_difference(parsed_data) diffs = [] teams = [] for row in d: if d.index(row) > 0: diffs.append(row[8]) teams.append(row[0]) i = diffs.index(min(diffs)) return teams[i]
true
b12125bfd87a14b9fba134333f933e0adf308bb6
talhahome/codewars
/Oldi2/Write_Number_in_Expanded_Form.py
612
4.3125
4
# You will be given a number and you will need to return it as a string in Expanded Form. For example: # # expanded_form(12) # Should return '10 + 2' # expanded_form(42) # Should return '40 + 2' # expanded_form(70304) # Should return '70000 + 300 + 4' # NOTE: All numbers will be whole numbers greater than 0. def expanded_form(num): z = '' while len(str(num)) > 1: x = num % 10**(len(str(num))-1) z = z + str(num - x) + ' + ' num = x if num != 0: z = z + str(num) else: z = z[:-3] print(z) return z expanded_form(70304) # Ans: '70000 + 300 + 4'
true
ea28dc883c613ace6f42e05c4bcd733df3482635
talhahome/codewars
/Number of trailing zeros of N!.py
580
4.3125
4
# Write a program that will calculate the number of trailing zeros in a factorial of a given number. # N! = 1 * 2 * 3 * ... * N # # Examples # zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero # # zeros(12) = 2 # # 12! = 479001600 --> 2 trailing zeros # Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros. def zeros(n): a = int(n/5) if a < 5: print(int(a)) return int(a) z = a while int(a/5) >= 1: z = z + int(a/5) a = int(a/5) print(z) return z zeros(10000)
true
3e27494fa5776ac2a3f8190bd688e6aacb5539c3
imayush15/python-practice-projects
/Learn/ListEnd.py
260
4.15625
4
print("Program to Print First and last Element of a list in a Seperate List :=\n") list1=['i',] x = int(input("Enter the Range of list : ")) for i in range(x): y = int(input("Enter the Value : ")) list1.append(y) print(list1[1], list1[-1])
true
3c28effd55d6948bfcd606a1e3466a2cbbc25218
imayush15/python-practice-projects
/Learn/Pythagorean_Triplet.py
311
4.1875
4
print("This is the program for thr Pythagoran triplet : ") h = int(input("Enter the Height : ")) b = int(input("Enter the Base : ")) p = int(input("Enter the Hypotaneus : ")) if (p*p)==(h*h)+(b*b): print("This is a Pythagorean Triplet :)") else: print("Sorry ! This is not a Pythagorean Triplet :(")
false
b1189fb8bb27a5ea03cfb834c376c30eae5c152d
Dyn0402/QGP_Scripts
/poisson_vs_binomial.py
523
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on May 14 10:47 AM 2020 Created in PyCharm Created as QGP_Scripts/poisson_vs_binomial @author: Dylan Neff, Dylan """ import numpy as np import matplotlib.pyplot as plt from scipy.stats import binom, poisson def main(): n = 60 p = 0.5 x = np.arange(60) plt.plot(x, binom.pmf(x, n, p), label='binomial') plt.plot(x, poisson.pmf(x, n * p), label='poisson') plt.legend() plt.show() print('donzo') if __name__ == '__main__': main()
false
78d0f11ae198c5115cee65f7646a1cc00472b497
piotrbelda/PythonAlgorithms
/SpiralTraverse.py
1,280
4.1875
4
# Write a function that takes in an n x m two-dimensional array # (that can be square-shaped when n==m) and returns a one-dimensional array of all the array's # elements in spiral order; Spiral order starts at the top left corner of the two-dimensional array, goes # to the right, and proceeds in a spiral pattern all the way until every element has been visited mat=[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]] # 1st, "pythonic" version def spiralTraverse(matrix): arr_to_sort=[] for element in matrix: arr_to_sort.extend(element) arr_to_sort.sort() return arr_to_sort print(spiralTraverse(mat)) # 2nd, with algorithmic approach def spiralTraverse(matrix): sC,eC,sR,eR=0,len(matrix[0])-1,0,len(matrix)-1 spiral_list=[] while len(matrix)*len(matrix[0]) != len(spiral_list): for x in range(sC,eC+1): spiral_list.append(matrix[sC][x]) for y in range(sR+1,eR+1): spiral_list.append(matrix[y][eC]) for z in range(eC-1,sC-1,-1): if sR==eR:break spiral_list.append(matrix[eR][z]) for k in range(eR-1,sR,-1): if sC==eC:break spiral_list.append(matrix[k][sC]) sC+=1 eC-=1 sR+=1 eR-=1 return spiral_list
true
209019237804db02fcb51e4001df53aaff1e45b0
kleutzinger/dotfiles
/scripts/magic.py
2,524
4.25
4
#!/usr/bin/env python3 """invoke magic spells from magic words inside a file magic words are defined thusly: (must be all caps) #__MAGICWORD__# echo 'followed by a shell command' put something of that format inside a file to set up running that command additionally, #__file__# will be substituted with the path of the file this is called on #__dir__# is the file's containing directory you can also call the script with a spell_idx argument `magic.py magic.py 0` TODO: if no args: look for other executables inside folder look for .MAGIC or MAGIC.txt inside folder? `magic.py % 0` is <leader>0 examples: #__PUSH__# gist -u ed85631bcb75846d950258eb19cb6b2a #__file__# #__RUN__# python ~/scripts/magic.py """ import os import re import sys import subprocess MAGIC_REGEX = re.compile(r"\s*#\s*__([A-Z0-9_]+)__#\s*(\S.*)") CAST_EMOJI = "(๑•ᴗ•)⊃━☆.*・。゚" def main(): if len(sys.argv) == 1: print(__doc__) exit() if len(sys.argv) >= 2: filename = sys.argv[1] if os.path.isfile(filename): with_arg(filename) else: print(f"no file {filename}") sys.exit(1) def with_arg(filename): spells = [] spell_counter = 0 with open(filename, "r") as fileobj: for line in fileobj: matches = MAGIC_REGEX.search(line) if matches: name, command = matches.group(1), matches.group(2) command = sub_magic(command, filename) spells.append((name, command)) spell_counter += 1 if spell_counter == 0: print(f"no spells found in {filename}") sys.exit(1) if len(sys.argv) >= 3: spell_idx = int(sys.argv[2]) else: spell_idx = choose_spell_idx(spells) name, command = spells[spell_idx] print(f"{CAST_EMOJI}{name}") process = subprocess.call(command, shell=True) def sub_magic(command, argfile): file_abs = os.path.abspath(argfile) file_dir = os.path.dirname(file_abs) command = command.replace("#__file__#", file_abs) command = command.replace("#__dir__#", file_dir) return command def choose_spell_idx(spells): idx = 0 for name, command in spells: print(f"{idx}.\t{CAST_EMOJI}{name}") print(f"{command}") print("-" * 5) idx += 1 inp = input("idx: ") if not inp: spell_idx = 0 else: spell_idx = int(inp) return spell_idx if __name__ == "__main__": main()
true
6369192c8d069bc4fd9f3b49e1e0cc94b1cc124a
nihaal-gill/Example-Coding-Projects
/Egyption Fractions/EgyptianFractions.py
1,000
4.28125
4
#Language: Python #Description: This program is a function that uses the greedy strategy to determine a set of distinct (i.e. all different) Egyptian #fractions that sum to numerator/denominator. The assumptions in this program are that the numerator and denominator are positive integers #as well as the numerator is less than or equal to denominator. The function 1) prints a readable "equation" showing the result and #2) returns a list of Egyptian fraction denominators. def egypt1(numerator,denominator): x = 2 result = [] print("{}/{} = ".format(numerator,denominator), end = " ") while(numerator != 0): if((numerator * x) >= denominator): result.append(x) numerator = (numerator * x) - denominator denominator = denominator * x x += 1 print("1/{} ".format(result[0]),end="") i = 1 while i < len(result): print("+ 1/{}".format(result[i]), end=" ") i += 1 print () return result
true
57060973638e77b4247be650fc3f065b3a06070c
BloodyInspirations/VSA2018
/proj01.py
2,321
4.375
4
# Name: # Date: # proj01: A Simple Program # Part I: # This program asks the user for his/her name and grade. #Then, it prints out a sentence that says the number of years until they graduate. # Part II: # This program asks the user for his/her name and birth month. # Then, it prints a sentence that says the number of days and months until their birthday # If you complete extensions, describe your extensions here! print "Hello there!" your_name = raw_input("What is your name?") date_of_grad = raw_input("What grade are you in?") print your_name + ", you will graduate in" + str(12 - int(date_of_grad)) + "years." print "Hi!" your_name = raw_input("What is your name?") your_name = your_name[0].upper() + your_name[1:100].lower() print your_name print "Hello!" your_name = raw_input("What is your name?") your_name = your_name[0:2].lower() + your_name[2].upper() + your_name[3:].lower() print your_name print "Hey there!" birth_month = int(raw_input("What is your birth month in a number?")) birth_day = int(raw_input("What is the date of when you were born?[Number]")) date_current = 11 month_current = 6 if birth_month >= month_current: print "Your birthday is in" + str(birth_month - month_current) elif month_current >= birth_month: print "Your birthday is in" + str(12-(month_current - birth_month)) print "months" print '/' if birth_day >= date_current: print str(birth_day - date_current) elif date_current >= birth_day: print str(30-(date_current - birth_day)) print "days." print "Hello" your_name = raw_input("What is your name?") print your_name + ", you are probably wondering what the highest ranking movie you are allowed to see is." age_limitation = int(raw_input("First of all how old are you?")) if age_limitation == 17 or age_limitation > 17: print "The highest ranking movie you can see would be R-rated." elif age_limitation == 13: print "The highest ranking movie you can see would be rated PG-13." if age_limitation == 14 or age_limitation == 16: print "The highest ranking movie you can see would be rated PG-13." elif age_limitation == 15: print "The highest ranking movie you can see would be rated PG-13." if age_limitation == 12 or age_limitation < 12: print "The highest ranking movie you can see would be rated PG or G."
true
65fb4afd1c43749106c02ed065d530e8bf3782b3
KeerthanaPravallika/DSA
/Patterns/Xpattern.py
558
4.28125
4
''' Write a program to take String if the length of String is odd print X pattern otherwise print INVALID. Input Format: Take a String as input from stdin. Output Format: print the desired Pattern or INVALID. Example Input: edyst Output: e t d s y d s e t ''' word = input() if len(word) % 2 == 0: print("INVALID") else: n = len(word) for i in range(n): for j in range(n): if(i == j) or (j == n-i-1): print(word[j],end='') else: print(' ',end='') print()
true
3a5e1b7ade252d9acc549f3d1177580ff9d9fd89
akuelker/intermediate_python_class
/Exercise 7/Exercise7_3.py
279
4.3125
4
import datetime year = int(input("Enter your Church Year: " )) today = datetime.date(year,1,1) # January 1st today += datetime.timedelta(days = 6 - today.weekday()) # First Sunday while today.year == year: print(today) today+= datetime.timedelta(days = 7)
false
488adf142b4eea5c71f5f3381b80935a33e47ebb
kayodeomotoye/Code_Snippets
/import csv.py
848
4.1875
4
import csv from io import StringIO def split_words_and_quoted_text(text): """Split string text by space unless it is wrapped inside double quotes, returning a list of the elements. For example if text = 'Should give "3 elements only"' the resulting list would be: ['Should', 'give', '3 elements only'] """ data = StringIO(text) reader = csv.reader(data, delimiter=' ') for row in reader: return row from shlex import split def split_words_and_quoted_text(text): """Split string text by space unless it is wrapped inside double quotes, returning a list of the elements. For example if text = 'Should give "3 words only"' the resulting list would be: ['Should', 'give', '3 words only'] """ return split(text)
true
a29a74255df46a2d0944a8389558cc294ed2eacb
kayodeomotoye/Code_Snippets
/running_mean.py
1,227
4.3125
4
from itertools import islice import statistics def running_mean(sequence): """Calculate the running mean of the sequence passed in, returns a sequence of same length with the averages. You can assume all items in sequence are numeric.""" avg_list=[] new_list = [] for num in sequence: new_list.append(num) avg = round(statistics.mean(new_list), 2) avg_list.append(avg) return avg_list #pybites from itertools import accumulate def running_mean_old(sequence): """Calculate the running mean of the sequence passed in, returns a sequence of same length with the averages. You can assume all items in sequence are numeric.""" if not sequence: return [] total = 0 running_mean = [] for i, num in enumerate(sequence, 1): total += num mean = round(total/i, 2) running_mean.append(mean) return running_mean def running_mean(sequence): """Same functionality as above but using itertools.accumulate and turning it into a generator""" for i, num in enumerate(accumulate(sequence), 1): yield round(num/i, 2) [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
true
e12ec0d529f890f1f46ead8feb24ce5ba1bef83a
rinoSantoso/Python-thingy
/Sorting.py
1,256
4.21875
4
def sort(unsorted): sorted = [] sorted.append(unsorted[0]) i = 1 while i < len(unsorted): for j in range(len(sorted)): if unsorted[i] < sorted[j]: sorted.insert(j, unsorted[i]) break elif j == len(sorted) - 1: sorted.insert(j + 1, unsorted[i]) i += 1 return sorted while True: # Status loop if the user wants to use the program status = str(input("Would you like to use the sorting program? (Y/N) ")) if status.upper() == "Y": numList = [] type = input("Would you like to do an ascending or descending sort? ") while True: # Input loop num = int(input("Please input the numbers you wish to sort (input '-1' to end input) ")) if num >= 0: numList.append(num) elif num == -1: break print ("The sorted list of numbers in ascending order is") if type.lower() == "ascending": print (sort(numList)) elif type.lower() == "descending": print(sort(numList)[::-1]) elif status.upper() == "N": print("Thank you for using this sorting program!") break
true
037ed9844747010a9a2d8da79c8ca973b6b278c2
DtjiAppDev/Python-Recursion-Tutorial
/recursive_fibonacci.py
406
4.28125
4
""" This file contains implementation of calculating the nth Fibonacci number using recursion Author: CreativeCloudAppDev2020 """ def fibonacci(n: int) -> int: if n < 0: return 0 elif n == 0 or n == 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2) # Test code print(fibonacci(3)) # 2 print(fibonacci(4)) # 3 print(fibonacci(5)) # 5
false
c0842c0917df268ba89c1d1fac5c46154ce24960
twhorley/twho
/matplotlib_tests.py
1,540
4.34375
4
""" Script to play around with how to make a variety of plots using matplotlib and numpy. I'll be using object-oriented interface instead of the pyplot interface to make plots because these are far more customizable. """ import matplotlib.pyplot as plt import numpy as np # Create a figure with 2 axes, both same scale, and plot a line fig, ax = plt.subplots() # creates a figure containing a single axes scale ax.plot([1,2,3,4], [4,1,3,2]) # plt.plot([1,2,3,4], [4,1,3,2]) <-- another way to make the same plot, but simpler # Easiest to make a new figure and axes with pyplot fig = plt.figure() # an empty figure with no Axes fig, ax = plt.subplots() # a figure with a single Axes, defaults scale 0 to 1 fig, axs = plt.subplots(2,2) # a figure with a 2x2 grid of plots, default scale 0-1 # Plot different equations on one figure x = np.linspace(0,2,100) # make array from 0 to 2 with 100 intervals between fig, ax = plt.subplots() # create a figure iwth an axes ax.plot(x, x, label='linear') # plot line x=y and name it 'linear' ax.plot(x, x**2, label='quadratic') # plot line x^2 and name it 'quadratic' ax.plot(x, x**3, label='cubic') # plot line x^3 and name it 'cubic' ax.set_xlabel('x label') # add an x-label to the axes ax.set_ylabel('y label') # add a y-label to teh axes ax.set_title("Simple Plot") # add a title to the axes ax.legend() # add a legend; I think this adds the 'label's made in the ax.plot() lines # Show all the plots (made with 'plt') made up to this point plt.show()
true
a98813061b478d0d7be602d6ba503f33ed228863
LaKeshiaJohnson/python-fizz-buzz
/challenge.py
664
4.3125
4
number = int(raw_input("Please enter a number: ")) # values should be stored in booleans # If the number is divisible by 3, print "is a Fizz number" # If the number is divisible by 5, print "is a Buzz number" # If the number is divisible by both 3 and 5, print is a FizzBuzz number" # Otherwise, print "is neither a fizzy or buzzy number" is_fizz = number % 3 == 0 is_buzz = number % 5 == 0 if (is_fizz and is_buzz): print("{} is a FizzBuzz number.".format(number)) elif (is_fizz): print("{} is a Fizz number.".format(number)) elif (is_buzz): print("{} is a Buzz number.".format(number)) else: print("{} is neither a fizzy or buzzy number.".format(number))
true
a6b7095bdf942c083324dc7d49dc2835d651bdb9
RileyMathews/nss-python-exercises-classes
/employees.py
1,597
4.1875
4
class Company(object): """This represents a company in which people work""" def __init__(self, company_name, date_founded): self.company_name = company_name self.date_founded = date_founded self.employees = set() def get_company_name(self): """Returns the name of the company""" return self.company_name # Add the remaining methods to fill the requirements above def get_employees(self): print(f'Employee report for {self.company_name}') for employee in self.employees: employee.print_information() def hire_employee(self, employee): self.employees.add(employee) class Employee: """ this class represent the people which work at companies """ def __init__(self, fn, ln, job_title, start_date): self.first_name = fn self.last_name = ln self.job_title = job_title self.start_date = start_date def print_information(self): print(f'{self.first_name} {self.last_name} started working as {self.job_title} on {self.start_date}') # create a company galactic_empire = Company("The Galactic Empire", "-10 BBY") # declare employee objects vader = Employee("Darth", "Vader", "Sith Lord", "-10 BBY") sidious = Employee("Darth", "Sidious", "Emperor", "-10 BBY") thrawn = Employee("Mithrando", "Thrawn", "Admiral", "-6 BBY") # add employees to galactic empire galactic_empire.hire_employee(vader) galactic_empire.hire_employee(sidious) galactic_empire.hire_employee(thrawn) # call employee report for galactic empire galactic_empire.get_employees()
true
eec5d6c8cb0b850addb2f043eb56b93787cb123f
peterjoking/Nuevo
/Ejercicios_de_internet/Ejercicio_22_Readfile.py
897
4.53125
5
""" Opening a file for reading is the same as opening for writing, just using a different flag: with open('file_to_read.txt', 'r') as open_file: all_text = open_file.read() Note how the 'r' flag stands for “read”. The code sample from above reads the entire open_file all at once into the all_text variable. But, this means that we now have a long string in all_text that can then be manipulated in Python using any string methods you want. Another way of reading data from the file is line by line: with open('file_to_read.txt', 'r') as open_file: line = open_file.readline() while line: print(line) line = open_file.readline() """ """with open('Docuprueba.txt', 'r') as open_file: all_text = open_file.read() print(all_text) """ ruta = '/Users/Pedro/Nuevo/fichero1.txt' with open(ruta, 'r') as open_file: all_text = open_file.read() print(all_text)
true
6cb4981ac678cc3bca8a2d9f19eb6972e08bad81
tomi8a/algoritmosyestructuradedatos
/CLASE 13/indexacion_numerica_1.py
960
4.1875
4
# Recordemos el manejo de índices y slicing # con strings var = 'Algoritmos y estructura de datos' print('La primera letra es: ' + var[0]) print('La última letra es: ' + var[-1]) print('Las primeras 3 letras son: ' + var[0:3]) print('Las primeras 3 letras son: ' + var[:3]) print('Las últimas 3 letras son: ' + var[-3:]) # con listas var2 = [10, 20, 40, 80, 160, 320, 640, 1280] print('Con listas:') print(var2[0]) print(var2[-1]) print(var2[0:3]) print(var2[:3]) print(var2[-3:]) # con una lista transformada en ndarray var2 = [10, 20, 40, 80, 160, 320, 640, 1280] import numpy as np var2 = np.array(var2) print('Con ndarray a partir de listas:') print(var2[0]) print(var2[-1]) print(var2[0:3]) print(var2[:3]) print(var2[-3:]) # con un ndarray de Numpy a partir de arange var3 = np.arange(-10, 11, 1) print('Con ndarray:') print(var3) print(var3[0]) print(var3[-1]) print(var3[0:3]) print(var3[:3]) print(var3[-3:])
false
f3b36b0d425a27a84edce61bd93de52c69ec90fe
ceejtayco/python_starter
/longest_strings.py
455
4.125
4
#Given an array of strings, return another array containing all of its longest strings. def longest_string(inputList): newList = list() longest = len(inputList[0]) for x in range(len(inputList)-1): if longest < len(inputList[x+1]): longest = len(inputList[x+1]) for x in inputList: if len(x) == longest: newList.append(x) return newList print(longest_string(["aba", "ab", "ababa", "ab"]))
true
eab7db0160e4e7dfc0da0690f114d51b49cbd69a
Haris-HH/CP3-Haris-Heamanunt
/Exercise_5_2_Haris_Heamanunt.py
262
4.28125
4
distance = int(input("Distance (km) : ")) time = int(input("Time (h) : ")) if(distance < 1): print("Distance can not be less than 1 km") elif(time < 1): print("Time can not be less than 1 hour") else: result = distance / time print(result,"km/h")
true
383cd867c393b32c6655c8c5bfbbd8baba60ad6a
LeilaRzazade/python_projects
/guess_number.py
802
4.1875
4
#This is random number generator program. #You should guess the random generated number. import random random_num = random.randint(1,100) user_input = int(input("Guess the number: ")) if (user_input == random_num): print("Congratulations! Guessed number is: ", user_input) while(user_input != random_num): if(user_input == random_num): print("Congratulations! Guessed number is right.") break else: if(user_input > random_num): print("Your number is not right. It's too high.") user_input = int(input(("Enter a new number: "))) else: print("Your number is not right. It's too low.") user_input = int(input(("Enter a new number: "))) print("Congratulations! Guessed number is: ", user_input)
true
4f8686f815a0f47d40b96cd5d9f6491d490a6159
jlast35/hello
/python/data_structures/queue.py
1,905
4.34375
4
#! /usr/bin/env python # Implementation of a Queue data structure # Adds a few non-essential convenience functions # Specifically, this is a node intended for a queue class Node: def __init__(self, value): self.value = value self.nextNode = None class Queue: def __init__(self): self.head = None self.tail = None def enq(self, value): # Create an empty node node = Node(value) # If it's the first node, make it the head if self.tail == None: self.head = node # Make its next node the current tail of the queue node.nextNode = self.tail # Update the tail to now be the new node self.tail = node def deq(self): # Special case: Empty if self.is_empty(): #print "Deq empty!" pass # There is at least one node else: #print "Deq", self.head.value # Special case: only one node if self.is_singleton(): # After we deq, head and tail are None self.tail = None self.head = None # There is more than one node else: penult = self.tail while penult.nextNode != self.head: penult = penult.nextNode #print "Penult is", penult.value penult.nextNode = None del self.head self.head = penult self.print_q() # ----- Convenience functions for testing ------- def print_q(self): if self.tail == None: #print "Empty queue!" pass else: current = self.tail while current != None: print current.value, current = current.nextNode print def from_list(self, qList): for node in qList: self.enq(node) self.print_q() def is_empty(self): if (self.head == None) and (self.tail == None): return True else: return False def is_singleton(self): if (self.head == self.tail) and (self.head != None): return True else: return False def deq_all(self): while not self.is_empty(): self.deq() # ---------- TEST ---------------- q = Queue() q.from_list(range(10)) q.deq_all()
true
2bb03b26a4554f78c897815138c6bf675ddfe96e
YuliiaAntonova/leetcode
/reverse integer.py
786
4.125
4
# Given a signed 32-bit integer x, return x with its digits reversed. # If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. class Solution(object): def reverse(self,n): y = str(abs(n)) # Create a variable and convert the integer into a string y = y.strip() #Strip all the leading zeros y = y[::-1] #reversed str rev = int(y) #Input reverse as an integer if rev >= 2 **31 -1 or rev <= -2**31: #check the conditions return 0 elif n < 0: #display negative numbers return -1 * rev else: return rev if __name__ == '__main__': solution = Solution() print(solution.reverse(-123)) print(solution.reverse(1234))
true
29a891c4b6e33cdc6dcbc0d8a17345d08990f332
zhaozongzhao/learngit
/arithmeticstudent/paint/pentagram_v4.0.py
1,877
4.21875
4
'''' 作者:赵宗召 功能:绘制五角星 版本:v3.0 时间:2017.11.19 功能:turtle库常用函数 V1.1 新增功能:使用循环画五角星 v1.2 将画五角星封装成函数 V2.0 设置画笔的颜色和宽度 V3.0 循环和函数的结合,递归 v4.0 树形图 ''' import turtle def tree_pentagram(distance): if distance > 5: # 绘制右侧树枝 if distance < 20: turtle.pencolor("green") #画右侧 turtle.forward(distance) print('向前',distance) turtle.right(20) print('向右20度') tree_pentagram(distance-10) print('向前', distance-10 ) #左侧 turtle.left(40) print('向左20度') tree_pentagram(distance - 10) print('向前', distance-10) #回到之前的位置 turtle.right(20) print('向右20度') turtle.backward(distance) else: turtle.pencolor("green") # 画右侧 turtle.forward(distance) print('向前', distance) turtle.right(20) print('向右20度') tree_pentagram(distance - 10) print('向前', distance - 10) # 左侧 turtle.left(40) print('向左20度') tree_pentagram(distance - 10) print('向前', distance - 10) # 回到之前的位置 turtle.right(20) print('向右20度') turtle.backward(distance) def main(): """ 主函数 """ turtle.left(90) turtle.penup() turtle.backward(200) turtle.pendown() turtle.pensize(5) turtle.pencolor("red") tree_pentagram(100) turtle.exitonclick() if __name__ == '__main__': main()
false
cc54a0283f674a4091d9d3a26f3b70459245119e
JaffarA/ptut
/python-4.py
1,626
4.4375
4
# introduction to python # 4 - io, loops & functions cont.. # functions can take multiple arguments, default arguments and even optional arguments (part of *args) def introduce(name='slim shady', age, hobby='fishing'): return print(f'Hi, my name is {name}. Hi, my age is {age}. Hi, i like this "{hobby}"') # this code will by default work with only 1 variable passed. introduce(8) # we can even be explicit and say exactly what we want to pass introduce(age=23, hobby='tacos') # for-based iteration, previously we used while-based iteration but this option is more popular # a for loop iterates a finite amount of times in what is called a count-controlled loop # below are two examples of types of for-loops items = ['eggs', 'cheese', 'milk'] for i in items: # we can iterate over a list object using each element as the i value print(f'Buying {i}\n') # \n adds a newline # fixed-length for loop for i in range(1, 100): # range technically creates a list object with every number between two points print(i, end='\n') # exercise 1 # fill in the blanks (#) below to make the code run 3 times and stop if the password is correct with a for loop def password_program(password): for # insert an i control statement if get_name('Please enter the password: ') == password: print('Access Granted') # fill this in to say 'Access Granted after {i} attempts' break # escape from the for loop else: print() # fill this in to say 'Access Denied. {i}/3 attempts left' password_program('cheese') # exercise 2 # write a function which asks for someone's name and uses a default greeting parameter
true
07899e72ed5eb012e3734e2bd01b0afd3dc4e698
karenlopez-13/Curso-de-Python-main
/funcionEjecucion.py
1,038
4.1875
4
#Metodos especiales y cuando hay 1 o 2 guiones bajos son metodos privados nombre = "Karen Lopez" print("Primero") print(nombre[2:4:2]) #strip quita los espacios de una cadena de texto ejemplo: "blusa azul" pasa a "blusaazul" #no jalo el strip así que pusimos en su lugar "replace" #lower lo hace minuscula def valida_palindromo(palabra): palabra = str(palabra).replace(" ", "").lower() return(palabra == palabra[::-1]) #corta la palabra desde el inicio hasta el fin y vete en pasos de -1 [inicial:final:pasos] def palindromo(palabra): palabra = palabra.replace("", "") palabra = palabra.lower() palabra_invertida = palabra[::-1] if palabra == palabra_invertida: return True else: return False def run(): palabra = input("Escribe una palabra: ") es_palindromo = valida_palindromo(palabra) if(es_palindromo): print(f'La palabra {palabra} es un palindromo') else: print(f'La palabra {palabra} no es un palindromo') #Entry point if __name__ == '__main__': run()
false
f9f86abfd5bab24edac6d6149fefd15b451f438e
anvarknian/preps
/Heaps/min_heap.py
2,621
4.1875
4
import sys # defining a class min_heap for the heap data structure class min_heap: def __init__(self, sizelimit): self.sizelimit = sizelimit self.cur_size = 0 self.Heap = [0] * (self.sizelimit + 1) self.Heap[0] = sys.maxsize * -1 self.root = 1 # helper function to swap the two given nodes of the heap # this function will be needed for heapify and insertion to swap nodes not in order def swapnodes(self, node1, node2): self.Heap[node1], self.Heap[node2] = self.Heap[node2], self.Heap[node1] # THE MIN_HEAPIFY FUNCTION def min_heapify(self, i): # If the node is a not a leaf node and is greater than any of its child if not (i >= (self.cur_size // 2) and i <= self.cur_size): if (self.Heap[i] > self.Heap[2 * i] or self.Heap[i] > self.Heap[(2 * i) + 1]): if self.Heap[2 * i] < self.Heap[(2 * i) + 1]: # Swap the node with the left child and then call the min_heapify function on it self.swapnodes(i, 2 * i) self.min_heapify(2 * i) else: # Swap the node with right child and then call the min_heapify function on it self.swapnodes(i, (2 * i) + 1) self.min_heapify((2 * i) + 1) # THE HEAPPUSH FUNCTION def heappush(self, element): if self.cur_size >= self.sizelimit: return self.cur_size += 1 self.Heap[self.cur_size] = element current = self.cur_size while self.Heap[current] < self.Heap[current // 2]: self.swapnodes(current, current // 2) current = current // 2 # THE HEAPPOP FUNCTION def heappop(self): last = self.Heap[self.root] self.Heap[self.root] = self.Heap[self.cur_size] self.cur_size -= 1 self.min_heapify(self.root) return last # THE BUILD_HEAP FUNCTION def build_heap(self): for i in range(self.cur_size // 2, 0, -1): self.min_heapify(i) # helper function to print the heap def Print(self): for i in range(1, (self.cur_size // 2) + 1): print(" PARENT : " + str(self.Heap[i]) + " LEFT CHILD : " + str(self.Heap[2 * i]) + " RIGHT CHILD : " + str(self.Heap[2 * i + 1])) def __repr__(self): return str(self.Heap[1:]) minHeap = min_heap(10) minHeap.heappush(15) minHeap.heappush(7) minHeap.heappush(9) minHeap.heappush(4) minHeap.heappush(13) print(minHeap) # minHeap.Print() minHeap.heappop() print(minHeap)
true
643bb8a4c5100d1f22dbd60132317b66f6fb3b06
Vinaypatil-Ev/aniket
/1.BASIC PROGRAMS/4.fahrenheit_to_degree.py
286
4.40625
4
# WAP to convert Fahrenheit temp in degree Celsius def f_to_d(f): return (f - 32) * 5 / 9 f = float(input("Enter Fahrenheit temprature: ")) x = f_to_d(f) print(f"{f} fahreheit is {round(x, 3)} degree celcius") # round used above is to round the decimal values upto 3 digits
true
3211aaae0cdbca9324479483fb2206519ccf8ca2
TonyPwny/cs440Ass1
/board.py
1,614
4.1875
4
# Thomas Fiorilla # Module to generate a Board object import random #import random for random generation def valid(i, j, size): roll = random.randint(1, max({(size - 1) - i, 0 + i, (size - 1) - j, 0 + j})) return roll # function to generate the board and place the start/end points # returns the built board and its size class Board: def __init__(self, boardSize): # checks to see if the user input board size is valid; if not... # generate a random number between 1 and 4, map 1:5, 2:7, 3:9, assign the boardSize variable # if 4 or any other number not 1,2,3, catch and map as 11 # also assigns boardMax, which is the maximum number that will fit in ANY tile if int(boardSize) > 4: roll = int(boardSize) else: roll = random.randint(0,3) if roll == 0: self.boardSize = 5 elif roll == 1: self.boardSize = 7 elif roll == 2: self.boardSize = 9 elif roll == 3: self.boardSize = 11 else: self.boardSize = roll self.boardBuilt = [[0 for x in range(self.boardSize)] for y in range(self.boardSize)] # create a 2D array of size "size"x"size" all initialised to 0 i = 0 j = 0 # code to generate the board, starting with iterating through each row while (i < self.boardSize): # iterates through each column of one row, rolling dice and checking if there are too many walls while (j < self.boardSize): if (i == self.boardSize-1) and (j == self.boardSize-1): self.boardBuilt[i][j] = 'G' break else: roll = valid(i, j, self.boardSize) self.boardBuilt[i][j] = roll j += 1 j = 0 i += 1
true
bd30e544beabc8a27f9dc2397b1395c233d8c583
rotuloveio/CursoEmVideoPython
/Mundo3/Aula21/ex104.py
507
4.1875
4
# Crie um programa que tenha a função leiaint(), que vai funcionar de forma semelhante à função input() do Python, só # que fazendo a validação para aceitar apenas um valor numérico. def leiaint(msg): while True: num = str(input(msg)) if num.isnumeric(): return int(num) break else: print('\033[31mDigite um número inteiro válido.\033[m') print(f'Você acabou de digitar o número {leiaint("Digite um número: ")}.')
false
68edf05eacc3113f09a101c78825ce260ba82ce9
rotuloveio/CursoEmVideoPython
/Mundo3/Aula21/ex101.py
601
4.15625
4
# Crie um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de nascimento de uma pessoa, # retornando um valor literal indicando se a pessoa tem voto NEGADO, OPCIONAL ou OBRIGATÓRIO nas eleições. from datetime import date def voto(ano): idade = date.today().year - ano resp = f'Com {idade} anos: ' if idade < 16: resp += 'NÃO VOTA' elif idade < 18 or idade >= 65: resp += 'VOTO OPCIONAL' else: resp += 'VOTO OBRIGATÓRIO' return resp print(f'{voto(int(input("Em que ano você nasceu? ")))}')
false
30b85504154a9a22042c416955ca643818f45e63
psarangi550/PratikAllPythonRepo
/Python_OOS_Concept/Monkey_Pathching_In_Python.py
2,149
4.4375
4
#changing the Attribute of a class dynamically at the runtime is called Monkey Patching #its a common nature for dynamically typed Language #lets suppose below example class Test:#class Test def __init__(self):#constructor pass#nothing to initialize def fetch_Data(self):#instance method #remeber that function is also a object and function name is the variable which been pointing to the function object that #that means:-function object has some id and function name variable pointing to that function object #address of function object and function reference variable being same as of now print("lets suppose its been fetching the data from DB") #after this data Fetched from DB we want to perform some activity using another function def f1(self):#instance method self.fetch_Data()#calling the instance method #now we realized that we should not deal with the live DB but we have to pre store test dat with which we need to test #which is def fetch_new_data(x):#here we are taking x as args as it will replace the ond live DB Data and we know self is not a keyword hence we cantake any args and PVM will provide the value for the same print("lets suppose its been fetching the data from Test DB") #so we can change the data fetching from the old DB to the New DB Using the Monkey Patching at runtime #we can write as below:- Test.fetch_Data=fetch_new_data #here the fetch_new_data function object referred by variable fetch_new_data same like fetch_data #as function is the object and which is referred by the function reference variable #here you can see we are not calling the method we are assigning the reference variable fetch_new_data reference to # fetch data reference #now the fetch_data is now not refer its old function object but its now pointing to the new function object as we assign the fetch_new_Data reference variable to fetch_data #now if we try to access the fetch_data it will provide the new Fetch_new_Data info Test().fetch_Data()#creating Test class Object and calling the instance method #lets suppose its been fetching the data from Test DB
true
1bbc38978d15042164c2a458952ea34ba30853db
yuliia11882/CBC.Python-Fundamentals-Assignment-1
/Yuliia-py-assignment1.py
1,380
4.21875
4
#Canadian Business College. # Python Fundamentals Assignment 1 #PART 1:------------------------------- #enter how many courses did he/she finish # the input value (which is string) is converted into number with int() num_of_courses = int(input("How many courses have you finished? ")) print(num_of_courses) #Declare an empty list course_marks = [] #while loop count = 1 while count <= num_of_courses: # the append() method used to add user's input into course_marks = [] course_marks.append (int(input("Enter your MARK for the COURSE #{count} is: "))) #increment the loop count count += 1 print(course_marks) #PART 2:------------------------- #find the total of all the courses marks inside the list with loop total = 0 for number in course_marks : total += number # find the average for all the courses for numb in course_marks : average = total / num_of_courses print(f"The average of your {num_of_courses} is: {average}")) #PART 3:------------------------ if average >= 90 and average <=100: print("your grade is A+") if average >= 80 and average <=89: print("your grade is B") if average >= 70 and average <=79: print("your grade is C") if average >= 60 and average <=69: print("your grade is D") if average < 60: print("your grade is F")
true
6e3568a6057b0d88393120ad65238b14834d53ba
samiCode-irl/programiz-python-examples
/Native_Datatypes/count_vowels.py
273
4.125
4
# Python Program to Count the Number of Each Vowel vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' sent = ip_str.casefold() count = {}.fromkeys('vowels', 0) for letter in sent: if letter in count: count[letter] += 1 print(count)
true
2bcc3c8c44bb0e4d435fd96c44e10293d88e4dcb
carv-silva/cursoemvideo-python
/Mundo03/exercsMundo03/exerc075.py
1,213
4.21875
4
'''Desenvolva um programa que leia quatros valores pelo teclado e guarde-os em uma tupla. No final mostre: A) quantos vezes aparece o valor 9. B) em que posição foi digitado o primeiro valor 3 C) quais foram os numeros pares.''' tupla = tuple(int(input('Digite um numero: '))for i in range(0, 4)) print(tupla) print(f'O valor 9 aparece {tupla.count(9)}vezes') if (3 in tupla) == True: print(f'O valor 3 aparece na {tupla.index(3) + 1 } Posicao') else: print('O valor 3 nao foi digitado em nenhuma posicao') for i in tupla: if i % 2 == 0: lista = [] lista.append(i) for pares in lista: if pares != None: lista_pares = [] lista_pares.append(pares) lista_pares_format = *lista_pares, sep=',' print(f"Os valores pares digitados sao:{lista_pares_format}") #lista_pares_format = "".join(map(str,lista_pares)) #print(lista_pares_format, end=',') #lista.append(pares).join(map(int, lista)) #lista = "".join(map(str, lista) #print(lista) #print(tuple(tupla)) #print(f'Os valores pares digitados sao: {pares}')
false
90ae4b0ff81699ca43a31b2c89c41eb345db6ed3
carv-silva/cursoemvideo-python
/Mundo01/exercsMundo01/ex017.py
518
4.1875
4
'''Faca um programa que leia o comprimento do cateto aposto e do cateto adjacente de um triangulo retangulo, calcule e mostre o comprimento da hipotenusa''' from math import sqrt a = float(input('Entre com o cateto: ')) b = float(input('Entre com o cateto aposto: ')) h = sqrt(a**2+b**2) print(f'A hipotenusa é: {h:.2f}') ## 2 metodo from math import hypot ca = float(input('Entre com o cateto: ')) co = float(input('Entre com o cateto aposto: ')) hip = hypot(ca, co) print(f'A hipotenusa é: {hip:.2f}')
false
a7c1d52f39a6b061c082067f05f451f3833f55bc
carv-silva/cursoemvideo-python
/Mundo01/exercsMundo01/ex018.py
787
4.34375
4
'''Faca um programa que leia um angulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse angulo ''' import math a = float(input('Digite um angulo: ')) r = math.radians(a) ## --> tranforma o angulo em radiando para poder fazer a conta print(f'O angulo de {a} tem o Seno de {(math.sin(r)):.2f}') ## o :.2f --> serve para deixar 2 digito dps da virgula print(f'O angulo de {a} tem o Cosseno de {math.cos(r):.2f}') print(f'O angulo de {a} tem o Tangente de {math.tan(r):.2f}') ## segundo metodo an = float(input('Digite um angulo: ')) print(f'O angulo de: {an} tem o Seno de:{math.sin(math.radians(an)):.2f}') print(f'O angulo de: {an} tem o Cosseno de:{math.cos(math.radians(an)):.2f}') print(f'O angulo de: {an} tem o Tangente de:{math.tan(math.radians(an)):.2f}')
false
2bd75ae280198f305db856b68e869fbf0bc1bfbe
carv-silva/cursoemvideo-python
/Mundo02/exercsMundo02/ex060.py
803
4.25
4
from math import factorial '''Faca um programa que leia um numero qualquer e o mostre o seu fatorial EX: 5! 5X4X3X2X1 = 120''' ''' n = int(input('Digite um numero inteiro qualquer: ')) fat = 1 i = 1 while i <= n: fat *= i i += 1 print(fat) resultado = 1 numero = int(input('Digite um numero inteiro qualquer: ')) for n in range(1, numero + 1): resultado *= n print(resultado)''' '''Metodo guanabara''' '''n = int(input('Digite um numero para calcular seu fatorial: ')) f = factorial(n) print(f'O fatorial de {n} é {f}') ''' '''Outro metodo''' n = int(input('Digite um numero para calcular seu fatorial: ')) c = n soma = 1 print(f'calculando {n}! =') while c > 0: print(f'{c}', end='') print(' x ' if c > 1 else ' = ', end='') soma *= c c -=1 print(f'{soma}')
false
7b7ef605632efa89f4d1de71edeeb3e78c933199
carv-silva/cursoemvideo-python
/Mundo01/exercsMundo01/ex035.py
882
4.5
4
''' Desenvolva um programa que leia o comprimento de tres retas e diga ao usuario se elas podem ou nao formar um trinagulo ''' '''a = float(input('Insira o comprimento 1: ')) b = float(input('Insira o comprimento 2: ')) c = float(input('Insira o comprimento 3: ')) if a + b + c == 180: print('Tringulo formado') else: print('Tringulo nao formado')''' '''para formar o trinagulo tem que a primeira reta tem que ser menor que a soma do 2 e 3 a segunda reta tem que ser menor que a soma do 3 e do 1 e o 3 reta tem que ser menor que a soma do 1 e 2''' #metodo do guanabara ---> o meu esta errado a = float(input('Insira o comprimento 1: ')) b = float(input('Insira o comprimento 2: ')) c = float(input('Insira o comprimento 3: ')) if a < b + c and b < a + c and c < a + b: print('Tringulo pode ser formado') else: print('Tringulo nao pode ser formado')
false
f19151fce2c14be35efad14a418a87e724286aa0
bryanlie/Python
/HackerRank/lists.py
1,198
4.46875
4
''' Consider a list (list = []). You can perform the following commands: insert i e: Insert integer at position . print: Print the list. remove e: Delete the first occurrence of integer . append e: Insert integer at the end of the list. sort: Sort the list. pop: Pop the last element from the list. reverse: Reverse the list. Initialize your list and read in the value of n followed by n lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list. No switch case in Python... ''' if __name__ == '__main__': n = int(input()) arr = [] for _ in range(n): line = list(input().split()) if line[0] == 'insert': arr.insert(int(line[1]), int(line[2])) elif line[0] == 'print': print(arr) elif line[0] == 'remove': arr.remove(int(line[1])) elif line[0] == 'append': arr.append(int(line[1])) elif line[0] == 'sort': arr.sort() elif line[0] == 'pop': arr.pop() elif line[0] == 'reverse': arr.reverse() else: break
true
89c8504779287cad8e9f3d65cebd28b62845bb88
FriggD/CursoPythonGGuanabara
/Mundo 2/Desafios/Desafio#37.py
584
4.15625
4
#Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão num = int(input('Digite um número inteiro: ')) escolha = int(input(''' Para conversão Para BINÁRIO: 1 Para OCTAL: 2 Para HEXADECIMAL: 3 ''')) if escolha == 1: print('O numero {} em binário é: {}'.format(num,bin(num)[2:])) elif escolha == 2: print('O numero {} em octal é: {}'.format(num, hex(num)[2:])) elif escolha == 3: print('O numero {} em hexadecimal é: {}'.format(num, oct(num)[2:])) else: print('escolha um numero inteiro entre 1 e 3')
false
66c0aeb6aed01f7e4887108de381d5e823d12fe1
FriggD/CursoPythonGGuanabara
/Mundo 1/Desafios/Desafio#22.py
562
4.21875
4
#Crie um programa que leia o nome completo de uma pessoa e mostre: #1. O nome com todas as letras maiúsculas; #2. O nome com todas as letras minúsculas; #3. Quantas letras tem sem contar os espaços; #4. Quantas letras tem o primeiro nome nome = input('Digite seu nome completo: ') print('1. Nome em maiúsculo: {}'.format(nome.upper())) print('2. Nome em minúsculo: {}'.format(nome.lower())) nome1 = nome.split() print('3. Quantidade de letras: {}'.format(len(nome)-nome.count(' '))) print('4. Quantas letras tem o primeiro nome: {}'.format(len(nome1[0])))
false
36fa0d82a540296a84fcfedc10e2c229aeaf60b3
FriggD/CursoPythonGGuanabara
/Mundo 3/Desafios/Desafio#75.py
721
4.15625
4
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: # A) Quantas vezes apareceu o valor 9. # B) Em que posição foi digitado o primeiro valor 3. # C) Quais foram os números pares. # Variáveis simples dentro de () formam as tuplas num = ( int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')) ) print(f'Voce digitou os numeros {num}') print(f'O valor 9 apareceu {num.count(9)}x') if 3 in num: print(f'O número 3 está na posição {num.index(3)+1}.') else: print('Não existe o numero 3') for n in num: if n%2 == 0: print('Números pares: {}'.format(n))
false
c270f4865da343415ea72349627c690b2bd5ad54
dipikakhullar/Data-Structures-Algorithms
/coding_fundamentals.py
772
4.125
4
def simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator function for value in simpleGeneratorFun(): print(value) import queue # From class queue, Queue is # created as an object Now L # is Queue of a maximum # capacity of 20 L = queue.Queue(maxsize=20) # Data is inserted into Queue # using put() Data is inserted # at the end L.put(5) L.put(9) L.put(1) L.put(7) # get() takes data out from # the Queue from the head # of the Queue print(L.get()) print(L.get()) print(L.get()) print(L.get()) #OUTPUT: """ 5 9 1 7 """ L.put(9) L.put(10) print("Full: ", L.full()) print(L.get()) print(L.get()) print(L.get()) # Return Boolean for Empty # Queue print("Empty: ", L.empty())
true
d39fc9f7c2504fd3122a243ecc48a9e74c76a1fb
matioli254/practice.py
/differentlists.py
1,316
4.3125
4
#list challenge 7 Different Types of Lists Program print("\n\t\t\tSummary Table") #Define list num_strings = ["15", "100", "55", "42"] num_ints = [15, 100, 55, 42] num_floats = [4.5, 10.5, 16.3, 34.3] num_lists = [[1,2,3],[4,5,6],[7,8,9]] # A summary of each variable (or list) print("\nThe variable num_strings is a " + str((type(num_strings)))) print("It contains the elements: " + str(num_strings)) print("The element 15 is a " + str(type(num_strings[0]))) print("\nThe variable num_ints is a " + str(type(num_ints))) print("It contains the elements: " + str(num_ints)) print("The element 15 is a " + str(type(num_ints[0]))) print("\nThe variable num_floats is a " + str(type(num_floats))) print("It contains the elements: " + str(num_floats)) print("The element 4.5is a " + str(type(num_floats[0]))) print("\nThe variable num_lists is a " + str(type(num_lists))) print("It contains the elements: " + str(num_lists)) print("The element[1, 2, 3] is a " + str(type(num_lists[0]))) #Permanently sort num_strings and num_ints. print("\nNow sorting num_strings and num_ints...") num_strings.sort() num_ints.sort() print("Sorted num_strings: " + str(num_strings)) print("Sorted num_ints: " + str(num_ints)) print(num_ints) print("\nStrings are sorted alphabeticaly while integers are sorted numericaly!!!")
false
28a982b392e5a1c3e5ecc287f78d63b506349c2a
Aparna768213/Best-Enlist-task-day3
/day7task.py
794
4.34375
4
def math(num1,num2): print("Addition of two numbers",num1+num2) print("Subtraction of two numbers",num1-num2) print("Multiplication of two numbers",num1*num2) print("Division of two numbers",num1/num2) num1 = float(input("Enter 1st number:")) num2 = float(input("Enter 2nd num:")) math(num1,num2) #Create a function covid()& it should accept patient name ,and body temperature ,by default the body temparature should be 98 degree. def covid(patient_name, body_temperature): if body_temperature < str(0): default=str(98) print("Patient name is",patient_name," Body temperature is",default) else: print("Patient name is",patient_name," Body temperature is",body_temperature) covid("Aparna","") covid("Aparna","99")
true
c28bc62bc1b7a68b6a73b36cceada5cf8f07cd0c
rishikumar69/all
/average.py
239
4.21875
4
num = int(input("Enter How Many Number you want:")) total_sum = 0 for i in range(num): input = (input("Enter The Number:")) total_sum += input ans = total_sum/num line = f"Total Average of {total_sum}is{ans}" print(line)
true
6a56ceb00fb302373d36dd1854e6775cba83b7c5
Gaurav716Code/Python-Programs
/Tuples/creating tuples.py
952
4.5
4
def createTuple(): # Different types of tuples # Empty tuple my_tuple = () print("Empty : ",my_tuple) # Tuple having integers my_tuple1 = (1, 2, 3) print("Integer : ",my_tuple1) # tuple with mixed datatypes my_tuple2 = (1, "Hello", 3.4) print("Mixed : ",my_tuple2) # nested tuple my_tuple3 = ("mouse", [8, 4, 6], (1, 2, 3)) print("Nested : ",my_tuple3) #Having one element within parentheses is not enough. #We will need a trailing comma to indicate that it is, in fact, a tuple my_tuple4 = ("hello") print(type(my_tuple4)) # <class 'str'> print(my_tuple4) # Creating a tuple having one element my_tuple5 = ("hello",) print(type(my_tuple5)) # <class 'tuple'> print(my_tuple5) # Parentheses is optional my_tuple6 = "hello", print(type(my_tuple6)) # <class 'tuple'> print(my_tuple6) createTuple()
false
d6ab91f6579ec619a681ab8f0d6f31240773a194
Gaurav716Code/Python-Programs
/if else if/ph value..py
288
4.125
4
def phvalue(): num = float(input("Enter number : ")) if num > 7 : print(num," is acidic in nature.") elif num<7: print(num," is basic in nature.") else: print(num,"is neutral in nature.") print("~~~~ End of Program ~~~~~~") phvalue()
true
d22f4ce6a9cff8d04db8fca268a56a52bb2092e3
ridwan098/Python-Projects
/multiplication table.py
220
4.21875
4
# This program displays the multiplication table loop = 1 == 1 while loop == True: n= input('\nenter an integer:') for i in range(1, 13): print ("%s x %s = %s" %(n, i, i*int(n)))
true
e4d00925b6e7d22f3f36a97fe670119419ffc614
ridwan098/Python-Projects
/fibonacci sequence(trial 1).py
361
4.15625
4
# This program prints out the fibonacci sequence(up to 100) loop = 1 == 1 while loop == True: number = 1 last = 0 before_last = 0 num = int(input("\nHow many times should it list? ")) for counter in range(0, num): before_last = last last = number number = before_last + last print(number)
true
26f0f0fdbbe45e57831f01a07ccdcf501e11515c
kelleyparker/Python
/grades.py
512
4.3125
4
print("This program calculates the averages of five students' grades.\n\n") # Define a list of tuples containing the student names and grades students = [] for i in range(5): name = input(f"Insert student {i+1}'s name: ") grade = float(input(f"Insert {name}'s grade: ")) students.append((name, grade)) # Calculate the average grade total = sum([grade for name, grade in students]) average = total / len(students) # Print the results print(f"The class average for the five students is {average}.")
true
19387fd2d7095b98e0492d1e93bd8f98001d8cf1
MaiShantanuHu/Coursera-Python-3-Programming
/Python-Basics/Week-2/Lists and Strings.py
1,622
4.21875
4
'''Q-1: What will the output be for the following code?''' let = "z" let_two = "p" c = let_two + let m = c*5 print(m) #Answer: # pzpzpzpzpz '''Q-2: Write a program that extracts the last three items in the list sports and assigns it to the variable last. Make sure to write your code so that it works no matter how many items are in the list.''' sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] last=sports[-3:] print(last) '''Q-3: Write code that combines the following variables so that the sentence “You are doing a great job, keep it up!” is assigned to the variable message. Do not edit the values assigned to by, az, io, or qy.''' by = "You are" az = "doing a great " io = "job" qy = "keep it up!" message=by+" "+az+io+","+" "+qy print(message) '''Q-4: What will the output be for the following code? ls = ['run', 'world', 'travel', 'lights', 'moon', 'baseball', 'sea'] new = ls[2:4] print(new)''' #Answer : # ['travel', 'lights'] '''Q-5: What is the type of m? l = ['w', '7', 0, 9] m = l[1:2]''' #Answer : # list '''Q-6: What is the type of m? l = ['w', '7', 0, 9] m = l[1]''' #Answer : # string '''Q-7: What is the type of x? b = "My, what a lovely day" x = b.split(',')''' #Answer : # list '''Q-8: What is the type of a? b = "My, what a lovely day" x = b.split(',') z = "".join(x) y = z.split() a = "".join(y)''' #Answer : # string
true
88aa8d4f5e4c0db6bc03e01b37b1b81e5419b3fa
dtulett15/5_digit_seperator
/3digit_seperator.py
300
4.28125
4
#seperate three digits in a three digit number entered by user #get number from user num = int(input('Enter a 3 digit number: ')) #set hundreds digit num1 = num // 100 #set tens digit num2 = num % 100 // 10 #set ones digit num3 = num % 10 #seperate digits print(num1, ' ', num2, ' ', num3)
true
9c2987a4dc6565034ae0ee703a4af1175d409d22
shahzeb-jadoon/Euclids-Algorithm
/greatest_common_divisor.py
691
4.375
4
def greatest_common_divisor(larger_num, smaller_num): """This function uses Euclid's algorithm to calculate the Greatest Common Divisor of two non-negative integers pre: larger_num & smaller_num are both non-negative integers, and larger_num > smaller_num post: returns the greatest common divisor of larger_num & smaller_num """ while smaller_num != 0: remainder = larger_num % smaller_num larger_num, smaller_num = smaller_num, remainder return larger_num def main(): larger_num = 60 smaller_num = 24 print(greatest_common_divisor(larger_num, smaller_num)) if __name__ == "__main__": main()
true
873a3801db68683d1551df016016074821335284
Meghna-U/posList.py
/posList.py
215
4.125
4
list=[] s=int(input("Enter number of elements in list:")) print("Enter elements of list:") for x in range(0,s): element=int(input()) list.append(element) for a in list: if a>0: print(a)
true
b088d63f6224b4081924db231b5f058b78498171
aastha2008/C1-Turtle
/main.py
1,993
4.59375
5
''' 03/22/2021 Introduction to Turtle # 1. Import turtle library import turtle # 2. Create a pen/turtle variable=turtle.Turtle() # 3. Create a paper/screen variable2 = turtle.Screen() # 4. Movements a. Move forward variable1.forward(DISTANCE) variable1.fd(DISTANCE) b. Move backward variable1.backward(DISTANCE) variable1.bk(DISTANCE) c. Turn right variable1.right(ANGLE) d. Turn left variable1.left(ANGLE) e. Pen up variable1.penup() f. Pen down variable1.pendown() g. Go to home(origin 0,0) variable1.home() h. Go to a specific point variable1.goto(X,Y) ''' ''' import turtle pen = turtle.Turtle() #Origin (0,0) pen.forward(100) #(100,0) pen.backward(200) #(-100,0) pen.left(90) pen.right(180) pen.left(1800) #DRAW a Window ------------------------------ | | | | | | | | | | | | | | | | | | | ------------------------------ ''' ''' import turtle pen = turtle.Turtle() pen.forward(300) pen.right(90) pen.forward(150) pen.right(90) pen.forward(150) pen.right(90) pen.forward(150) pen.left(180) #pen.backward(150) pen.forward(150) pen.right(90) pen.forward(150) pen.right(90) pen.forward(150) ''' #DRAW a house import turtle pen = turtle.Turtle() pen.forward(100) pen.left(90) pen.forward(100) pen.left(45) pen.forward(100) pen.left(90) pen.forward(100) pen.left(135) pen.forward(142) #pen.left(180) pen.backward(145) pen.right(90) pen.forward(100) pen.left(90) pen.forward(50) pen.left(90) pen.forward(70) pen.right(90) pen.forward(40) pen.right(90) pen.forward(70) pen.penup() pen.backward(70) pen.left(90) pen.forward(30) #pen.penup() pen.pendown() pen.right(45) pen.forward(25) pen.right(90) pen.forward(25) pen.right(90) pen.forward(25) pen.right(90) pen.forward(25) #pen.penup() #pen.goto(0,0) #pen.home()
false
7e97f790d96abf42d0220cb1fe537834a50d0796
shikhaghosh/python-assigenment1
/assignment2/question10.py
284
4.15625
4
print("enter the length of three side of the triangle:") a,b,c=int(input()),int(input()),int(input()) if a==b and a==b and a==c: print("triangle is equilateral") elif a==b or b==c or a==c: printf("triangle is a isoscale") else: printf("triangle is a scalene")
true
e22b05a76b97dc275f3092a23404a3b7263f0f24
shikhaghosh/python-assigenment1
/assignment2/question7.py
268
4.21875
4
print("enter three numbers:") a1,a2,a3=int(input()),int(input()),int(input()) if(a1<a2<a3 or a3<a2<a1): print(a2,"is the second smallest") elif(a2<a3<a1 or a1<a3<a2): print(a3,"is the second smallest") else: print(a1,"is the second smallest")
false
143f78b793a0772073bcc3239ce361d2735339d4
IbroCalculus/Python-Codes-Snippets-for-Reference
/Set.py
1,592
4.21875
4
#Does not allow duplicate, and unordered, but mutable. #It is faster than a list #Python supports the standard mathematical set operations of # intersection, union, set difference, and symmetric difference. #DECLARING EMPTY SET x= set() #NOTE: x = {} is not an empty set, rather an empty dictionary s = {10,10,10,3,2} print(s, end='\n\n') L = ['Ibrahim','Ibrahim','Ibrahim',"Musa"] print(L,end='\n') S = set(L) print(S) #Counting characters using set testT = "Ibrahim Musa Suleiman" print(f'CHARACTERS PRESENT: {set(testT)}, NUMBER OF CHARACTERS: {len(set(testT))}') #Add elements to a set y = set() y.add("One") y.add("Two") y.add("Three") y.add("Four") print(y) print(f'ADDED ELEMENT: {y}') #Remove element from a set y.remove("Three") #OR y.discard("Three") print(f'ROM0VED ELEMENT: {y}') #y.pop() removes the last element in the tuple, but tuple is unordered, ie: removes any element #Clear a set y.clear() #Delete a tuple del y #JOIN TWO SETS #Assume Set1 and Set2 are defined, use the Set1.update(Set2). print(Set1) #SET OPERATIONS #UNION A|B #INTERSECTION A&B #SET DIFFERENCE A-B ELEMENTS IN A BUT NOT IN B #SYMETRIC DIFFERENCE A^B ELEMENTS IN A OR B, BUT NOT IN BOTH #Check reference for more A = {"IBRAHIM", "IBRAHIM", "MUSA"} B = {"SULEIMAN", "20s", "IBRAHIM"} print(f'THE UNION: {A|B}') print(f'THE INTERSECT: {A&B}') print(f'THE DIFFERENCE: {A-B}') print(f'THE SYMETRIC DIFFERENCE: {A^B}') x = (A|B) - (A&B) print(f'SIMILARLY: {x}') #SET QUANTIFICATION WITH ALL AND ANY #Check reference
true
b27175e1a40f491c0ef12308615e1fc946b694e6
IbroCalculus/Python-Codes-Snippets-for-Reference
/Regex2.py
902
4.4375
4
import re #REGULAR EXPRESSIONS QUICK GUIDE ''' ^ - Matches the beginning of a line $ - Matches the end of a line . - Matches any character \s - Matches whitespace \S - Matches any non-whitespace character * - Repeats a character zero or more times *? - Repeats a character zero or more times (non-greedy) + - Repeats a character one or more times. +? - Repeats a character one or more times (non-greedy) [aeiou] - Matches a single character in the listed set [^XYZ] - Matches a single character not in the listed set [a-z0-9] - The set of characters can include a range ( - Indicates where string extraction is to start ) - Indicates where String extraction is to end ''' st = "This is a string statement, this is a this is which is a this. Just for testing regex" #USING re.find and re.search if re.search("is", st): print("Match found") print(f'{re.search("is", st)}')
true
43c3fddb4167b616b765b692e7c4a02d36f2e32f
IbroCalculus/Python-Codes-Snippets-for-Reference
/Dictionary.py
1,766
4.3125
4
#CREATE A DICTIONARY: 2 METHODS cars = {"Benz": 2, "Corola": 1} cars2 = dict(fname="Ibrahim", mname="Musa", sname="Suleiman") print(f'The number of Benz cars are: {cars["Benz"]}') print(f'You are welcome Mr {cars2["fname"]} {cars2["mname"]} {cars2["sname"]}') #Copy a dictionary cars2 = dict(fname="Ibrahim", mname="Musa", sname="Suleiman") cars2_copy = cars2.copy() #Add element cars['Toyota'] = 5 print(cars) #Access keys and values print(f'The keys of the dictionary are: {cars.keys()}') print(f'The values of the dictionary are: {cars.values()}') for i in (cars.keys()): print(f'The number of {i} cars are: {cars.get(i)} OR {cars[i]}') #of cars[i] print("\n") for i,j in (cars.items()): print(f'The number of {i} cars are {j}') print('\n') #Update a dictionary dict1 = dict(fname="One", sname="Two", email="someone@email.com", phone=41234) dict2 = dict(fname="One", sname="Three", email="nobody@email.com", phone=98765, address="My home address") dict1.update(dict2) print(f'DICT_MERGE: {dict1}') #Dictionary from lists keyList = ['cat', 'Dog', 'Fish', 'Hen'] valueList = [2,4,8,3] for i in zip(keyList, valueList): print(i) print('\n') for i,j in zip(keyList, valueList): print(f'The number of {i} are {j}') print('\n') animals = dict(zip(keyList, valueList)) for i in animals: print(f'The value of {i} are {animals[i]}') print('\n') #Deleting Elements print(animals) del animals['Dog'] print(animals.items()) print(animals) print('\n') #cars.pop('Benz') #Remove the Benz key value pair #cars.popitem() #Removes the last inserted element in the dictionary #Clear elements from the dictionary animals.clear() print(animals) print('\n') #Delete a dictionary print(cars) del cars print(f'After del, Cars = ', end='') print(cars)
false
1f7f8ee6ed425bc86dba4a171d6c5da109035b5a
santospat-ti/Python_ExListas
/ex10.py
318
4.125
4
"""Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos elementos do vetor.""" num = [] soma = 0 for n in range(10): num.append(int(input('Digite um número: '))) soma += (num[len(num) - 1] ** 2) print('A soma dos quadrados do vetor são', soma)
false
d13a82fd3c12c780d64089c05e1e3387c3d5ab39
santospat-ti/Python_ExListas
/ex07.py
826
4.21875
4
"""Faça um Programa que leia duas listas com 10 elementos cada. Gere uma terceira lista de 20 elementos, cujos valores deverão ser compostos pelos elementos intercalados das duas outras listas.""" lista_um = [] lista_dois = [] lista_tres = [] lista_inter = [] for n in range(10): print('Lista um') lista_um.append(int(input(f'Digite o {n + 1}º elemento: '))) for c in range(10): print('Lista dois') lista_dois.append(int(input(f'Digite o {c + 1}º elemento: '))) for x in range(10): print('Lista três') lista_tres.append(int(input(f'Digite o {x + 1}º elemento: '))) for m in range(10): lista_inter.append(lista_um[m]) lista_inter.append(lista_dois[m]) lista_inter.append(lista_tres[m]) print(lista_um) print(lista_dois) print(lista_tres) print(lista_inter)
false
fd9adb7ebb5603760577526aa16ab7d83555be5d
ParulProgrammingHub/assignment-1-mistryvatsal
/Program8.py
241
4.15625
4
# WPP TO TAKE INPUT BASE AND HEIGHT OF THE TRIANGLE AND PRINT THE AREA OF THE TRIANGLE base = int(input('ENTER THE BASE OF THE TRIANGLE :')) height = int(input('ENTER THE HEIGHT OF THE TRIANGLE :')) print('AREA IS : ', 0.5 * height * base)
true
c26f6b50cf1d5469dbd3cc97838e12ec9893e8ba
johnlev/coderdojo-curriculum
/Week2/activity.py
633
4.34375
4
# We are going to be making a guessing game, where the user guesses your favorite number # Here we define a variable guess which holds the user's response to the question # The input function asks the user the question and gives back the string the user types in. # The int(...) syntax converts the string into an integer if it can guess = int(input("What is my favorite number? ")) # ======================= # You write the following my_favorite_number = 42 # If the guess is less than your favorite number, tell the user # If the guess is more than your favorite number, ... # If the guess is your favorite number, ...
true
f83050b30754d73714f4382103ec3499635b7eb2
GiantPanda0090/Cisco_Toolbox
/regex/remove_dup_words.py
695
4.46875
4
################################################### # Duplicate words # The students will have to find the duplicate words in the given text, # and return the string without duplicates. # ################################################### import re def demo(): print(remove_duplicates("the bus bus will never be a bus bus in a bus bus bus")) def remove_duplicates(text): #write here exression_0=r"\b(\w+)(?!\s+\1)\b" text_with_no_dup_list=re.findall(exression_0,text) text_with_no_dup="" for word in text_with_no_dup_list: text_with_no_dup=text_with_no_dup+" "+word return text_with_no_dup ##main class trigger if __name__ == "__main__": demo()
true
7b23940e3907b14467adeec77e52d3713ae5ad87
jtylerroth/euler-python-solutions
/1-100/14.py
1,219
4.125
4
# The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. # Dictionary will hold all the known answers to speed up calculations lengths = {} def collatzSequence(n): length = 1 while n != 1: if n % 2 == 0: # even n = n/2 else: # odd n = 3*n+1 length += 1 if n in lengths: length += lengths[n] break # already solved return length # Question example # print(collatzSequence(13)) max_n = 1 max_val = 1 for i in range(1,1000000): seq = collatzSequence(i) lengths[i] = seq # Save the answer if seq > max_val: max_n = i max_val = seq print("Longest chain: {0} with length {1}".format(max_n,max_val))
true
f8ba737f5a10bd6f8d3bdc7edb17545ed95c78fb
Monamounika/Python
/Functions/Var_len_arg.py
734
4.3125
4
''' The variable length argv is an argv that can accept any no.of values. The variable length argv is written with * before variable in fn definition. ''' def totalcost(x,*y): sum=0 for i in y: sum+=i print(x+sum) #print(sum) totalcost(100,200) totalcost(122,576,8) totalcost(67) def totalmul(x,*y): mul=1 for i in y: mul*=i print(x*mul) totalmul(10,20) totalmul(122,576,8) #here x=122 and y=576,8(stored in tuple). totalmul(90) #keyword length argument Internally it represents like a dict object. def kwargs(**kw): print(kw) kwargs(id=8,name="monu") kwargs(id=9,name="maha",quali="BCA") #kwargs(6,"kill") TypeError: kwargs() takes 0 positional arguments but 2 were given
false
7c54831f8c3e6f351e963513424ee7cc89c52ee6
fsaraos27/Codigos_Varios
/Multiplicar.py
413
4.15625
4
print("") print("Multiplica ") print("") print("Ingresa un numero a multiplicar ") num1 = int(input()) print("Ingresaste el numero", num1) print("") print("Ingresa el segundo numero a multiplicar ") num2 = int(input()) print("Ingresaste ", num2) print("Presiona enter para multiplicar ") enter = input() print("La multiplicacion entre ", num1, " y ", num2, " es ", num1 * num2) print("") print("FIN MULTIPLICAR ")
false
a9e34edfcc8e1aae24613a2e286a6e34ef0ec5d5
marslwxc/read-project
/Python高级编程和异步IO并发编程/Chapter08/metaclass_test.py
968
4.125
4
# 类也是对象,type是创建类的类 def create_class(name): if name == 'user': class User: def __str__(self): return "user" return User elif name == "company": class Company: def __str__(self): return "company" return Company # type动态创建类 class BaseClass: def answer(self): return 'i am baseclass' def say(self): return 'i am {}'.format(self.name) User = type('user', (BaseClass,), {'name':"user", 'say':say}) # 元类是创见类的类,对象<-class(对象)<-type class MetaClass(type): pass class User(metaclass=MetaClass): pass # Python中类的实例化过程,会首先寻找metaclass属性,通过metaclass去创建类 # type创建类对象,实例 if __name__ == "__main__": # MyClass = create_class('user') # my_obj = MyClass() # print(type(my_obj)) my_obj = User() print(my_obj.answer())
false
086a9d173ed3e63778658acb1b08f31c5adacf90
leo-sandler/ICS4U_Unit_4_Algorithms_Leo_Sandler
/Lesson_4.1/4.1_Recursion_and_Searching.py
1,826
4.21875
4
import math # Pseudo code for summing all numbers from one to 100. # Initialize count variable, at 1 # for 101 loops # Add loop number to the count, with reiterating increase # Real code count = 0 for x in range(101): count += x # print(count) # Recursion is calling the same function within itself. # Recursion pseudo code def recursionexample(tracker): if tracker > 4: return True else: return recursionexample(tracker + 1) # Increases forever, automatically returning True. print("\nRecursive programming: ") print(recursionexample(6)) # If higher than 4, it returns True. print(recursionexample(-992)) # If lower than 4, continually adds up until it is bigger than four, then returns True. # Searches can be done in binary, or through linear searching. # Linear searching: # pseudo code below. # define function # search data is set to 12 # for loop, number in numbers(which is a list of numbers) # if searchdata is number then # Return true def list_searching(numbers): # Pseudo code in python searchdata = 12 for number in numbers: if searchdata == number: return True return False print("\nList searching: ") print(list_searching([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) print(list_searching([2, 4, 6, 8, 10, 12, 14])) # Binary is faster, but data must be sorted first. # Binary will be slower for extremely large lists. # The list is split into halves, which are searched. The list cuts from the middle. def binarySearch(a, value, left, right): if right < left: return False mid = math.floor((right - left) / 2) if a[mid] == value: return value if value < a[mid]: return binarySearch(a, value, left, mid-1) else: return binarySearch(a, value, left+1, right)
true
83971e63972f9a21edf9f355529cab109502a54d
sanketha1990/python-basics
/pythonHelloWorld/com/python/learner/ComparisionOperatorInPython.py
410
4.46875
4
temperature=30 if temperature > 30: # == , !=, print('its hot day !') else: print('it is not hot day !') print('=============================================') name=input('Please enter your name .. ') name_len=len(name) if name_len <= 3: print('Name should be gretter thant 3 charecter !') elif name_len >=50: print('Name length should be less than 50') else: print('Name looks Good !!!')
true
07c5d362279a97b82ea87639ceefc126938d9535
bijayofficial/College_webDev
/college/class 6/uc_lc.py
208
4.125
4
a=input("enter the character") if(a>'A' and a<='Z'): print("upper case") elif(a>'a' and a<='z'): print("lower case") elif(a>='0' and a<='9'): print("number") else: print("Symbols")
false
bc0237b5b7ad679068c608b10a522c79423ca44a
alexisfaison/Lab1
/Programming Assignment 1.py
1,021
4.1875
4
# Name: Alexis Faison # Course: CS151, Prof. Mehri # Date: 10/5/21 # Programming Assignment: 1 # Program Inputs: The length, width, and height of a room in feet. # Program Outputs: The area and the amount of paint and primer needed to cover the room. import math #initialize variables width_wall = 0.0 length_wall = 0.0 height_wall = 0.0 print("\nPaint your room! Enter the dimensions of the room in feet.") length_wall = float(input("\n\tEnter desired length:")) width_wall = float(input("\n\tEnter desired width:" )) height_wall = float(input("\n\tEnter desired height:" )) #Calculate the area, gallons of primer & gallons of paint area = (length_wall + width_wall) + 2 * ((length_wall * height_wall) + (width_wall * height_wall)) primer = math.ceil(area/200) paint = math.ceil(area/350) print("\nThe total area of the four walls and ceiling is", area, "feet.") print("\nThe gallons of primer needed to coat the area is", primer, "gallons.") print("\nThe gallons of paint needed to cover the area is", paint, "gallons.")
true
c566f5a501c3836a02acec1ecdbbdebad233eee3
AAKANSHA773/Basic-of-python
/6.dictionary.py
742
4.15625
4
d2=dict() print("empty dictionary",d2) d1={} print("empty dictionary repersant",d1) d={'1':"one"} print("key and value",d) d3={'1':"one",'2':"two",'3':"third",'4':"string"} print(d3) d3['1']='100'#chnage the value of index one element print(d3) d3[1]=[1,2,3] #give value in the from of list print(d3) print("two" in d3.values()) # check value are present or not in this dictinary #dict = key: values dict1={1:"akku",2:"ammu",3:"aadi"} print(dict1) print(dict1.items()) #print key value in the form of set k=dict1.keys()# for print keys for i in k: print(i) v=dict1.values() # print values for i in v: print(i) print(dict1[1]) # dictionary index start with 1. del dict1[2] # delete specific index key-value print(dict1)
false
0f662c6750f4e56b67eb4c73f495dc70b96c1bf7
pallavibhagat/Problems
/problem2.py
376
4.4375
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Write a program to find the sum of all the multiples of 3 or 5 below 1000. """ def multiple(): sum = 0 for i in range(1,1000): if i%3==0 or i%5==0: sum +=i print sum if __name__ == '__main__': multiple()
true
2133af4c52bba08fd49755539e15512f1ee865e5
DipakTech/Python-basic
/app.py
2,827
4.15625
4
# print('hello world') # python variables # one=1 # two=2 # some_number=1000 # print(one,two,some_number) # booleans # true_boolean=True # false_boolean=False # # string # my_name='diapk' # # float # book_price=12.3 # print(true_boolean,false_boolean,my_name,book_price) # if True: # print('Hello python learners:') # if 3>1: # print('3 is greater than 1') # control flow and conditional statements # if 1>2: # print('1 is greater than 2') # elif 2>1: # print('2 is greater than 1') # else: # print('1 is equal to 2') # looping and iterator # num=1 # while num<=100: # print(num) # num+=1 # another basic bit of code to better understand it : # loop_condition=True # while loop_condition: # print('loop condition keeps: %s' %(loop_condition)) # loop_condition=False # for looping # for i in range(1,11): # print(i) # list collection |array and data structure # my_integers=[1,2,3,4,5,6,7,8,9] # print(my_integers[0]) # print(my_integers[2]) # print(my_integers[3]) # print(my_integers[5]) # print(my_integers[4]) # print(my_integers[6]) # relatives_names=[ # 'bipana', # 'dipak', # 'jagat', # 'ananda', # 'premlal', # 'saraswati' # ] # for i in range(0,len(relatives_names)): # print(relatives_names[i]) # appending the list in to the empty array # book_list=[] # book_list.append('The effective enginners') # book_list.append('money heist') # book_list.append('the mekemoney dev') # book_list.append('the python study') # book_list.append('the javascript learners') # print(book_list[4]) # for i in range(0,len(book_list)): # print(book_list[i]) # dictoionary_example # dictoionary_example={ # "key1":"value1", # "key2":"value2", # "key3":"value3" # } # print(dictoionary_example) # print(dictoionary_example["key1"]) # print(dictoionary_example["key2"]) # printting the dictoionary in the formatted way # dictoionary_tk={ # "name":"DIPAK", # "age":21, # "education":"bachelore" # } # dictoionary_tk["age"]=23; # print(dictoionary_tk) # bookshef=[ # "the effective engineer", # "The 4 hours of social network", # "zero to mestry", # "the Hero" # ] # for book in bookshef: # print(book) # dictionary = { "some_key": "some_value" } # for key in dictionary: # print("%s --> %s" %(key, dictionary[key])) # dictionary = { "some_key": "some_value" } # for key, value in dictionary.items(): # print("%s --> %s" %(key,value)) # dictoionary_tk={ # "name":"DIPAK", # "age":21, # "education":"bachelore" # } # for attribute, value in dictoionary_tk.items(): # print('my %s is %s' %(attribute,value))
true