blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a0e4c3feb2b27548e37c583aa5c091110329d73a
logan-ankenbrandt/LeetCode
/RemoveVowels.py
1,043
4.21875
4
def removeVowels(s: str) -> str: """ 1. Goal - Remove all vowels from a string 2. Example - Example #1 a. Input i. s = "leetcodeisacommunityforcoders" b. Output i. "ltcdscmmntyfcfgrs" - Example #2 a. Input i. s = "aeiou" b. Output i. "" 3. Implementation - Steps a. Initialize a list of the characters in the s string and a list of the vowels b. Iterate through the values in the vowels list, c. Write a while loop that will remove the vowels while they are still in the vowels list """ s_arr = list(s) vowels = list("aAeEiIoOuU") for vowel in vowels: while vowel in s_arr: s_arr.remove(vowel) return ''.join(s_arr) print(removeVowels("leetcodeisacommunityforcoders"))
true
e696cb31e3dd97c552b6b3206798e74a29027b0d
logan-ankenbrandt/LeetCode
/MajorityElement.py
1,072
4.40625
4
from collections import Counter from typing import List def majorityElement(self, nums: List[int]) -> int: """ 1. Goal a. Return the most frequent value in a list 2. Examples a. Example #1 - Input i. nums = [3, 2, 3] - Output i. 3 3. Implementation a. Summary - Use counter to count the frequency, find the max of the values in the dict, loop through the dict, if a value equals the max value, return the key b. Steps - Count the frequency of the numbers in the list w the Counter() module and set it to a variable - Set the max of the values to a variable - Loop through the items in the dictionary - Write a conditional to check if the values in the dict are equal to the max - If it does, return the key """ c = Counter(nums) m = max(c.values()) for key, values in c.items(): if values == m: return key
true
150c6c8f6e603b1ab89367e04150829b11c31df3
logan-ankenbrandt/LeetCode
/MostCommonWord.py
1,404
4.125
4
from typing import List from collections import Counter import re def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: """ 1. Goal - Return the most common word in a string that is not banned 2. Examples - Example #1 a. Input i. paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"] b. Output i. "ball" 3. Implementation - Steps a. Convert all of the characters in the paragraph string to lowercase and set it to the varaible p b. Use the re module to find only words in the p string c. Initialize a Counter() variable to count the frequency of words in the list d. Loop through the words in the banned array i. If it is in the dictionary, delete it e. Return the key with the greatest value in the dictionary - Summary a. Use the re module to find only words, loop through a counter dictionary to remove the banned words, return the key with the greatest value """ p = paragraph.lower() l = re.findall(r'[\w]+', p) c = Counter(l) for i in banned: if i in c: del c[i] return max(c, key=c.get)
true
441be31aa36e6c446bc891e5cb84e0ee9abdb924
logan-ankenbrandt/LeetCode
/CountSubstrings.py
1,979
4.28125
4
import itertools import snoop @snoop def countSubstrings(s: str) -> int: """ 1. Goal - Count the number of substrings that are palindromes. 2. Examples - Example #1 a. Input i. "abc" b. Output i. 3 c. Explanation - The palindromes are "a", "b", and "c". 3. Implementation - Steps a. Initialize a count variable b. Loop over the indexes of the string c. Set two variables, left and right, to the indexes d. Write a function that: i. Contains a while loop that: - Runs while a. Left is greater than 0 and right is less than the length of the string b. And the value at the left index is equal to the value at the right index c. This ensures that it is a palindrome - Increments the count variable by 1 - Decrements left variable to the left by 1 a. This is to ensure that the left index is always less than the right index - Increments right variable to the right by 1 i. Set the l variable to the index and set the r variable to the index plus one e. Return the count variable - Summary a. Each char in str as middle and expand outwards, do same for pali of even len; maybe read up on manachers alg """ count = 0 for i in range(len(s)): count += countPalindrome(s, i, i) count += countPalindrome(s, i, i + 1) return count def countPalindrome(s, l, r): count = 0 while l >= 0 and r < len(s) and s[l] == s[r]: count += 1 l -= 1 r += 1 return count print(countSubstrings("abc"))
true
a3ae007c55ee2cfe220cd9094b4eaa38822ded38
CountTheSevens/dailyProgrammerChallenges
/challenge001_easy.py
803
4.125
4
#https://www.reddit.com/r/dailyprogrammer/comments/pih8x/easy_challenge_1/ # #create a program that will ask the users name, age, and reddit username. have it tell them the information back, #in the format: your name is (blank), you are (blank) years old, and your username is (blank) #for extra credit, have the program log this information in a file to be accessed later. name = input("What is your name? ") age = input("How old are you? ") if age is not int: age = input("Please enter a numeric value for your age. ") redditName = input("What's your Reddit username? ") f = open('challenge001_easy_output.txt', 'a') print('Your name is', name,', you\'re', age, 'years old, and your Reddit username is', redditName, '.') out = name,age, redditName f.write(str(out)) f.write('\n') f.close()
true
199cc666d97a3fdc6e1afc98ec06c33f005ae051
iSkylake/Algorithms
/Tree/ValidBST.py
701
4.25
4
# Create a function that return True if the Binary Tree is a BST or False if it isn't a BST class Node: def __init__(self, val): self.val = val self.left = None self.right = None def valid_BST(root): inorder = [] def traverse(node): nonlocal inorder if not node: return traverse(node.left) inorder.append(node.val) traverse(node.right) traverse(root) if sorted(inorder) == inorder: return True else: return False a = Node(5) b = Node(2) c = Node(7) d = Node(4) e = Node(9) a.left = b a.right = c c.left = d c.righ = e print(valid_BST(a)) a = Node(5) b = Node(2) c = Node(7) d = Node(4) e = Node(9) a.left = b b.right = d a.right = c c.righ = e print(valid_BST(a))
true
92803502bd1d37d5c73015816ba141e760938491
iSkylake/Algorithms
/Linked List/LinkedListReverse.py
842
4.15625
4
# Function that reverse a Singly Linked List class Node: def __init__(self, val=0): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, val): new_node = Node(val) if self.length == 0: self.head = new_node else: self.tail.next = new_node self.tail = new_node self.length += 1 # First Attempt def reverse_list(node): previous = None current = node next_node = node.next while current != None: current.next = previous previous = current current = next_node if current != None: next_node = current.next # Cleaner def reverse_list(node): previous = None current = node next_node = node.next while current != None: next_node = current.next current.next = previous previous = current current = next_node
true
0824e7d93385a87358503bc289e984dfeae38f8c
hShivaram/pythonPractise
/ProblemStatements/EvenorOdd.py
208
4.4375
4
# Description # Given an integer, print whether it is Even or Odd. # Take input on your own num = input() # start writing your code from here if int(num) % 2 == 0: print("Even") else: print("Odd")
true
7f77696fcdae9a7cef174f92cb12830cde16b3cb
hShivaram/pythonPractise
/ProblemStatements/AboveAverage.py
1,090
4.34375
4
# Description: Finding the average of the data and comparing it with other values is often encountered while analysing # the data. Here you will do the same thing. The data will be provided to you in a list. You will also be given a # number check. You will return whether the number check is above average or no. # # ---------------------------------------------------------------------- # Input: # A list with two elements: # The first element will be the list of data of integers and # The second element will be an integer check. # # Output: # True if check is above average and False otherwise # Take input here # we will take input using ast sys import ast from functools import reduce input_str = input() input_list = ast.literal_eval(input_str) # Remember how we took input in the Alarm clock Question in previous Session? # Lets see if you can finish taking input on your own data = input_list[0] check = input_list[1] s = 0 # start writing your code to find if check is above average of data s = int(reduce(lambda x, y: x + y, data)) avg = s / len(data) print(check > avg)
true
63a055bb9ee454b6c6ad68defb6b540b6cb74323
Hosen-Rabby/Guess-Game-
/randomgame.py
526
4.125
4
from random import randint # generate a number from 1~10 answer = randint(1, 10) while True: try: # input from user guess = int(input('Guess a number 1~10: ')) # check that input is a number if 0 < guess < 11: # check if input is a right guess if guess == answer: print('Correct, you are a genius!') break else: print('Hey, are you insane! I said 1~10') except ValueError: print('Please enter number')
true
233b8e8cc6295adad5919285230971a293dfde80
abhaydixit/Trial-Rep
/lab3.py
430
4.1875
4
import turtle def drawSnowFlakes(depth, length): if depth == 0: return for i in range(6): turtle.forward(length) drawSnowFlakes(depth - 1, length/3) turtle.back(length) turtle.right(60) def main(): depth = int(input('Enter depth: ')) drawSnowFlakes(depth, 100) input('Close the graphic window when done.') turtle.mainloop() if __name__ == '__main__': main()
true
df273e0b1a4ec97f7884e64e0fe1979623236fb2
bdjilka/algorithms_on_graphs
/week2/acyclicity.py
2,108
4.125
4
# Uses python3 import sys class Graph: """ Class representing directed graph defined with the help of adjacency list. """ def __init__(self, adj, n): """ Initialization. :param adj: list of adjacency :param n: number of vertices """ self.adj = adj self.size = n self.clock = 1 self.post = [0 for _ in range(n)] self.visited = [0 for _ in range(n)] def previsit(self): self.clock += 1 def postvisit(self, v): self.post[v] = self.clock self.clock += 1 def explore(self, v): self.visited[v] = 1 self.previsit() for u in self.adj[v]: if not self.visited[u]: self.explore(u) self.postvisit(v) def deepFirstSearch(self): """ Visits all nodes and marks their post visit indexes. Fills list post[]. """ for v in range(self.size): if not self.visited[v]: self.explore(v) def acyclic(self): """ Checks whether graph has edge in that post visit index of source vertex is less than its end vertex post index. If such edge exists than graph is not acyclic. :return: 1 if there is cycle, 0 in other case. """ self.deepFirstSearch() for v in range(self.size): for u in self.adj[v]: if self.post[v] < self.post[u]: return 1 return 0 if __name__ == '__main__': """ Input sample: 4 4 // number of vertices n and number of edges m, 1 <= n, m <= 1000 1 2 // edge from vertex 1 to vertex 2 4 1 2 3 3 1 Output: 1 // cycle exists: 3 -> 1 -> 2 -> 3 """ input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) adj = [[] for _ in range(n)] for (a, b) in edges: adj[a - 1].append(b - 1) graph = Graph(adj, n) print(graph.acyclic())
true
3bd0c70f91a87d98797984bb0b17502eac466972
nguyenl1/evening_class
/python/labs/lab18.py
2,044
4.40625
4
""" peaks - Returns the indices of peaks. A peak has a lower number on both the left and the right. valleys - Returns the indices of 'valleys'. A valley is a number with a higher number on both the left and the right. peaks_and_valleys - uses the above two functions to compile a single list of the peaks and valleys in order of appearance in the original data. # """ data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] noindex= [0, 1, 2, 3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13,14,15,16,17,18,19,20] def peaks(): length = len(data) middle_index = length//2 first_half = data[:middle_index] second_half = data[middle_index:] # peak = first_half.index('P') peak = data.index(max(first_half)) peak_2 = data.index(max(second_half)) print(f"The index of the peak on the left is {peak}") print(f"The index of the peak on the right is {peak_2}") # peaks() def valleys(): valleys = [] for i in noindex[1:]: if data[i] <= data[i-1] and data[i] <= data[i+1]: valleys.append(i) # return valleys print(f"The indices of the valleys are {valleys}") # valleys() def peaks_and_valleys(): peaks() valleys() peaks_and_valleys() def p_v(): for i in data: print ("x" * i) p_v() #jon's ex: """ def get_data(): data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] return data def get_valleys(data): valleys = [] index_list = list(range(len(data))) for i in index_list: if (i-1) in index_list and (i+1) in index_list: # makes the index start at 1 so the indexing is not out of range? if data[i] <= data[i-1] and data[i] <= data[i+1]: valleys.append(i) return valleys def get_peaks(data): peaks = [] index_list = list(range(len(data))) for i in index_list: if (i-1) in index_list and (i+1) in index_list: if data[i] >= data [i-1] and data [i] >= data [i+1]: peaks.append(i) return peaks """
true
39c5729b31befc2a988a0b3ac2672454ae99ea9a
krsatyam20/PythonRishabh
/cunstructor.py
1,644
4.625
5
''' Constructors can be of two types. Parameterized/arguments Constructor Non-parameterized/no any arguments Constructor __init__ Constructors:self calling function when we will call class function auto call ''' #create class and define function class aClass: # Constructor with arguments def __init__(self,name,id): self.name=name self.id=id #print(self.id) #print(self.name) #simple function def show(self): print("name=%s id= %d "%(self.name,self.id)) #call a class and passing arguments obj=aClass("kumar",101) obj2=aClass("rishave",102) obj.show() obj2.show() #second ExAMPLE class Student: def __init__(self,name,id,age): self.name = name; self.id = id; self.age = age #creates the object of the class Student s = Student("John",101,22) #s = Student() TypeError: __init__() missing 3 required positional arguments: 'name', 'id', and 'age' print("*************befoer set print***********") print(getattr(s,'name')) print(getattr(s,'id')) print(getattr(s,'age')) print("**********After set print***********") setattr(s,'age',23) print(getattr(s,'age')) setattr(s,'name','kumar') print(getattr(s,'name')) # Constructor - non parameterized print("************ Non parameters ***********") class Student: def __init__(self): print("This is non parametrized constructor") def show(self,name): print("Hello",name) student = Student() #student.show("Kuldeep")
true
f2744631653064a83857180583c831b187a8f53c
TiwariSimona/Hacktoberfest-2021
/ajaydhoble/euler_1.py
209
4.125
4
# List for storing multiplies multiplies = [] for i in range(10): if i % 3 == 0 or i % 5 == 0: multiplies.append(i) print("The sum of all the multiples of 3 or 5 below 1000 is", sum(multiplies))
true
0211584a0d5087701ee07b79328d4eb6c101e962
pintugorai/python_programming
/Basic/type_conversion.py
438
4.1875
4
''' Type Conversion: int(x [,base]) Converts x to an integer. base specifies the base if x is a string. str(x) Converts object x to a string representation. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple. list(s) Converts s to a list. set(s) Converts s to a set. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. and So on ''' x="5" xint = int(x); print("xint = ",xint)
true
3597f00172708154780a6e83227a7930e034d166
csu100/LeetCode
/python/leetcoding/LeetCode_225.py
1,792
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 10:37 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-stack-using-queues/ 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 empty() -- 返回栈是否为空 2.实现过程: """ from queue import Queue class MyStack: def __init__(self): """ Initialize your data structure here. """ self.stack = Queue() def push(self, x): """ Push element x onto stack. """ if self.stack.empty(): self.stack.put(x) else: temp = Queue() temp.put(x) while not self.stack.empty(): temp.put(self.stack.get()) while not temp.empty(): self.stack.put(temp.get()) def pop(self): """ Removes the element on top of the stack and returns that element. """ if self.stack.empty(): raise AttributeError("stack is empty!") return self.stack.get() def top(self): """ Get the top element. """ if self.stack.empty(): raise AttributeError("stack is empty!") a=self.stack.get() self.push(a) return a def empty(self): """ Returns whether the stack is empty. """ return True if self.stack.empty() else False if __name__ == '__main__': mystack = MyStack() print(mystack.empty()) for i in range(4): mystack.push(i * i) print(mystack.empty()) while not mystack.empty(): print(mystack.pop())
true
d57b48fe6ebac8c1770886f836ef17f3cadf16c7
alma-frankenstein/Grad-school-assignments
/montyHall.py
1,697
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #to illustrate that switching, counterintuitively, increases the odds of winning. #contestant CHOICES are automated to allow for a large number of test runs, but could be #changed to get user input import random DOORS = ['A', 'B', 'C'] CHOICES = ["stay", "switch"] def main(): num_runs = 100 monty(num_runs) def monty(num_runs): switchAndWin = 0 #times winning if you switch stayAndWin = 0 #times winning if you stay runs = 0 while runs <= num_runs: prize = random.choice(DOORS) picked_door = random.choice(DOORS) #Monty open a door that was neither chosen nor containing the prize for door in DOORS: if door != prize and door != picked_door: openedDoor = door break #the contestant can either stay with picked_door or switch to the other unopened one stayOrSwitch = random.choice(CHOICES ) if stayOrSwitch == "stay": final = picked_door if final == prize: stayAndWin += 1 else: #switch for door in DOORS: if door != openedDoor and door != picked_door: final = door if final == prize: switchAndWin += 1 break runs += 1 percentSwitchWin = (switchAndWin/num_runs) * 100 percentStayWin = (stayAndWin/num_runs) * 100 print("Odds of winning if you stay: " + str(percentStayWin)) print("Odds of winning if you switch: " + str(percentSwitchWin)) if __name__ == '__main__': main()
true
8b8644a5fbc3a44baff3a5ad1156c5a644b60f56
drod1392/IntroProgramming
/Lesson1/exercise1_Strings.py
1,026
4.53125
5
## exercise1_Strings.py - Using Strings # # In this exercise we will be working with strings # 1) We will be reading input from the console (similar to example2_ReadConsole.py) # 2) We will concatenate our input strings # 3) We will convert them to upper and lowercase strings # 4) Print just the last name from the "name" variable # 5) EXTRA - Use proper capitalization on first and last name print("Section 1 - Read input\n") # Prompt the user to enter first and last name seperately # Use two input() commands to read first and last name seperately. # Use variable names "first" and "last" to store your strings print("\nSection 2 - Concatenate") # Concatenate first and last name together in variable "name" # Print out the result print("\nSection 3 - Upper and Lower") # Print "name" in all uppercase # Print "name" in all lowercase print("\nSection 4 - Only Last Name") # Print just the last name from "name" print("\nSection 5 - Capitalization") # Extra - use proper capitalization on first and last name
true
df9cea82395dfc4c540ffe7623a0120d2483ea9e
imyogeshgaur/important_concepts
/Python/Exercise/ex4.py
377
4.125
4
def divideNumber(a,b): try: a=int(a) b=int(b) if a > b: print(a/b) else: print(b/a) except ZeroDivisionError: print("Infinite") except ValueError: print("Please Enter an Integer to continue !!!") num1 = input('Enter first number') num2 = input('Enter second number ') divideNumber(num1,num2)
true
2d95e7c4a3ff636c2ec5ff400e43d273bc479f48
akshitha111/CSPP-1-assignments
/module 22/assignment5/frequency_graph.py
829
4.40625
4
''' Write a function to print a dictionary with the keys in sorted order along with the frequency of each word. Display the frequency values using “#” as a text based graph ''' def frequency_graph(dictionary): if dictionary == {'lorem': 2, 'ipsum': 2, 'porem': 2}: for key in sorted(dictionary): print(key, "-", "##") elif dictionary == {'This': 1, 'is': 1, 'assignment': 1, '3': 1,\ 'in': 1, 'Week': 1, '4': 1, 'Exam': 1}: for key in sorted(dictionary): print(key, "-", "#") elif dictionary == {'Hello': 2, 'world': 1, 'hello': 2, 'python': 1, 'Java': 1, 'CPP': 1}: for key in sorted(dictionary): print(key, "-", dictionary[key]) def main(): dictionary = eval(input()) frequency_graph(dictionary) if __name__ == '__main__': main()
true
f0995f652df181115268c78bbb649a6560108f47
ciciswann/interview-cake
/big_o.py
658
4.25
4
''' this function runs in constant time O(1) - The input could be 1 or 1000 but it will only require one step ''' def print_first_item(items): print(items[0]) ''' this function runs in linear time O(n) where n is the number of items in the list if it prints 10 items, it has to run 10 times. If it prints 1,000 items, we have to print 1,000 times''' def print_all_items(items): for item in items: print(item) ''' Quadratic time O(n^2)''' def print_all_possible_ordered_pairs(items): for first_item in items: for second_item in items: print(first_item, second_item) print_all_possible_ordered_pairs([0,6,8,9])
true
d0249ae72e0a0590cffda71a48c5df0993d1ee18
zongxinwu92/leetcode
/CountTheRepetitions.py
788
4.125
4
''' Created on 1.12.2017 @author: Jesse '''''' Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc". On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”. You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 &le; n1 &le; 106 and 1 &le; n2 &le; 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1. Example: Input: s1="acb", n1=4 s2="ab", n2=2 Return: 2 " '''
true