blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
d5c1e62a45a8f54b456a5222850a37b3b0575df8
|
atehortua1907/Python
|
/MasterPythonUdemy/10-EjerciciosBloque2/10.1-Ejercicio1.py
| 967
| 4.46875
| 4
|
"""
Hacer un programa que tenga una lista de
8 numeros enteros y haga lo siguiente:
- Recorrer la lista y mostrarla
- Hacer funcion que recorra listas de numeros y devuelva un string
- Ordenarla y mostrarla
- Mostrar su longitud
- Busca algun elemento (que el usuario pida por teclado)
"""
listNum = [8,3,5,1,7,2,6,4]
print("Esta es la lista: ")
for num in listNum:
print(num)
def getStringList(lista):
stringNum = ""
for num in lista:
stringNum = f"{num},{stringNum}"
return stringNum
print("\nLista de números en string: ")
print(getStringList(listNum))
print("\nLista de números ordenada: ")
listNum.sort()
print(listNum)
print(f"La lista tiene una longitud de: {len(listNum)}")
searchElement = int(input("Ingresa un número a buscar: "))
if searchElement in listNum:
print(f"El número {searchElement} se encuentra en la lista ")
else:
print(f"El número {searchElement} no esta en la lista")
| false
|
dcdbd68cea46053d4c116d19d5ed64f0d26eca1f
|
obaodelana/cs50x
|
/pset6/mario/more/mario.py
| 581
| 4.21875
| 4
|
height = input("Height: ")
# Make sure height is a number ranging from 1 to 8
while (not height.isdigit() or int(height) not in range(1, 9)):
height = input("Height: ")
# Make range a number
height = int(height)
def PrintHashLine(num):
# Print height - num spaces
print(" " * int(height - num), end="")
# Print num amount of hashes
print("#" * num, end="")
# Print two spaces
print(" ", end="")
# Print num amount of hashes
print("#" * num, end="")
# Print a new line
print("")
for i in range(1, height + 1):
PrintHashLine(i)
| true
|
014130aa0b43faecfbb0737cb47bf66bbf6bd318
|
carriekuhlman/calculator-2
|
/calculator.py
| 2,425
| 4.25
| 4
|
"""CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# loop for an input string
# if q --> quit
# otherwise: tokenize it
# look at first token
# do equation/math for whatever it corresponds to
# return as a float number
while True:
input_string = input("Write an equation > ")
tokens = input_string.split(' ')
valid_tokens = {"+": 3, "-": 3, "*": 3, "/": 3, "square": 2, "cube": 2, "pow": 3, "mod": 3}
if input_string == "q":
break
# elif tokens[0] not in valid_tokens:
# print("Invalid input")
elif len(tokens) != valid_tokens[tokens[0]]:
print("Invalid input")
# elif tokens[0] in valid_tokens:
# for i in range(1,len(tokens)):
# try:
# int(tokens[i])
# except:
# print("Input not valid.")
# break
for i in range(len(tokens)):
if i == 0:
if tokens[0] not in valid_tokens:
print("Invalid input.")
break
else:
try:
int(tokens[i])
except:
print("Input not valid")
break
else:
#create valid tokens list
#iterate through tokens (using range of len)
#if tokens[0] is not in our operator list
#print error message
#else:
#try to convert the passed string to integer
#exception would be a print statement with an error message
if tokens[0] == "+":
answer = (add(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "-":
answer = (subtract(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "*":
answer = (multiply(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "/":
answer = (divide(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "square":
answer = (square(int(tokens[1])))
elif tokens[0] == "cube":
answer = (cube(int(tokens[1])))
elif tokens[0] == "pow":
answer = (power(int(tokens[1]), int(tokens[2])))
elif tokens[0] == "mod":
answer = (mod(int(tokens[1]), int(tokens[2])))
print(float(answer))
| true
|
61d8cb65ed02a9dbd905897290709080c49ba886
|
benjiaming/leetcode
|
/validate_binary_search_tree.py
| 1,596
| 4.15625
| 4
|
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
"""
#%%
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.checkBST(root)
def checkBST(self, node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
if node.val <= lower or node.val >= upper:
return False
if not self.checkBST(node.left, lower, node.val):
return False
if not self.checkBST(node.right, node.val, upper):
return False
return True
solution = Solution()
# 2
# / \
# 1 3
tree = TreeNode(2)
tree.left = TreeNode(1)
tree.right = TreeNode(3)
print(solution.isValidBST(tree)) # True
# 5
# / \
# 1 4
# / \
# 3 6
tree = TreeNode(5)
tree.left = TreeNode(1)
tree.right = TreeNode(4)
tree.right.left = TreeNode(3)
tree.right.right = TreeNode(6)
print(solution.isValidBST(tree)) # False
#%%
| true
|
f7c50862b43c8c0386195cd4b01419c0ac6f7b21
|
benjiaming/leetcode
|
/find_duplicate_subtrees.py
| 1,636
| 4.125
| 4
|
"""
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4
The following are two duplicate subtrees:
2
/
4
and
4
Therefore, you need to return above trees' root in the form of a list.
"""
#%%
# Definition for a binary tree node.
from collections import Counter
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self.val)
class Solution(object):
def findDuplicateSubtrees(self, root):
result = []
freq = Counter()
def preorder_traversal(node):
if not node:
return '#'
path = [str(node.val)]
path.append(preorder_traversal(node.left))
path.append(preorder_traversal(node.right))
serialized = ','.join(path)
freq[serialized] += 1
if freq[serialized] == 2:
result.append(node)
return serialized
preorder_traversal(root)
return result
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
root.right.left.left = TreeNode(4)
root.right.right = TreeNode(4)
solution = Solution()
print(solution.findDuplicateSubtrees(root))
| true
|
f2d07b36bb42c0d8b1ec205cb3fa338d18719363
|
benjiaming/leetcode
|
/rotate_image.py
| 1,571
| 4.1875
| 4
|
#!/bin/env python3
"""
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
"""
#%%
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
Runs in O(n^2).
"""
lm = len(matrix)
if not lm or lm != len(matrix[0]):
return
for r in range(lm//2):
first = r
last = lm - 1 - r
for i in range(first, last):
offset = i - first
top = matrix[first][i]
matrix[first][i] = matrix[last-offset][first]
matrix[last-offset][first] = matrix[last][last-offset]
matrix[last][last-offset] = matrix[i][last]
matrix[i][last] = top
solution = Solution()
input = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
solution.rotate(input)
print(input)
#%%
| true
|
31f07756faaa6a84752cc672f676c44554821b74
|
Developer-Student-Club-Bijnor/Data_Structure_and_Algorithm
|
/DataStructure.py/Queue.py
| 1,529
| 4.21875
| 4
|
class Queue(object):
"""
Queue Implementation: Circular Queue.
"""
def __init__(self, limit=5):
self.front = None
self.rear = None
self.limit = limit
self.size = 0
self.que = []
def is_empty(self):
return self.size <= 0
def enQueue(self, item):
if self.size >= self.limit:
print("Queue Overflow..!!")
return
self.que.append(item)
if self.front == None:
self.front = self.rear = 0
else:
self.rear = self.size
self.size += 1
print("Queue after enQueue:", self.que)
def deQueue(self):
if self.size <= 0:
print("Queue underflow..!!! ")
return
self.que.pop(0)
self.size -= 1
if self.size == 0:
self.front = self.rear = None
else:
self.rear = self.size - 1
print("Queue after deQueue: ", self.que)
def queueRear(self):
if self.rear == None:
print("Sorry the queue is Empty.")
raise IndexError
return self.que[self.rear]
def queueFront(self):
if self.front == None:
print("Sorry the queue is Empty.")
raise IndexError
return self.que[self.front]
def size(self):
return self.size
if __name__ == "__main__":
q = Queue()
q.enQueue("first")
q.enQueue("second")
q.enQueue("third")
q.deQueue()
print(q.queueFront())
print(q.queueRear())
| false
|
b048988bbaa1a55c3010042e642d232d7e1e4698
|
SDSS-Computing-Studies/004c-while-loops-hungrybeagle-2
|
/task2.py
| 520
| 4.21875
| 4
|
#! python3
"""
Have the user enter a username and password.
Repeat this until both the username and password match the
following:
Remember to use input().strip() to input str type variables
username: admin
password: 12345
(2 marks)
inputs:
str (username)
str (password)
outputs:
Access granted
Access denied
example:
Enter username: fred
Enter password: password
Access denied
Enter username: admin
Enter password: password
Access denied
Enter username: admin
Enter password: 12345
Access granted
"""
| true
|
7779633f0c8bf9a73c3eafcc06e21beed0200332
|
Nivedita01/Learning-Python-
|
/swapTwoInputs.py
| 967
| 4.28125
| 4
|
def swap_with_addsub_operators(x,y):
# Note: This method does not work with float or strings
x = x + y
y = x - y
x = x - y
print("After: " +str(x)+ " " +str(y))
def swap_with_muldiv_operators(x,y):
# Note: This method does not work with zero as one of the numbers nor with float
x = x * y
y = x / y
x = x / y
print("After: " +str(x)+ " " +str(y))
def swap_with_builtin_method(x,y):
# Note: This method works for string, float and integers
x,y = y,x
print("After: " +x+ " " +y)
x = raw_input("Enter first input: ")
y = raw_input("Enter second input: ")
print("Before: " +x+ " " +y)
swap_with_addsub_operators(int(x), int(y))
swap_with_muldiv_operators(int(x), int(y))
swap_with_builtin_method(x, y)
| true
|
43927a3adcc76846309985c0e460d64849de0fa7
|
Nivedita01/Learning-Python-
|
/guess_game.py
| 560
| 4.21875
| 4
|
guess_word = "hello"
guess = ""
out_of_attempts = False
guess_count = 0
guess_limit = 3
#checking if user entered word is equal to actual word and is not out of guesses number
while(guess != guess_word and not(out_of_attempts)):
#checking if guess count is less than guess limit
if(guess_count < guess_limit):
guess = raw_input("Enter guess word: ")
guess_count += 1
else:
out_of_attempts = True
if out_of_attempts:
print "Sorry! You couldn't guess"
else:
print "You win!"
| true
|
12f9dbff51caec4d245d00d5d6cc71d0c3c88b5f
|
rdumaguin/CodingDojoCompilation
|
/Python-Oct-2017/PythonFundamentals/Lists_to_Dict.py
| 1,020
| 4.21875
| 4
|
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def zipLists(x, y):
zipped = zip(x, y)
# print zipped
newDict = dict(zipped)
print newDict
return newDict
zipLists(name, favorite_animal)
# Create a function that takes in two lists and creates a single dictionary where the first list contains keys and the second values. Assume the lists will be of equal length.
#
# Your first function will take in two lists containing some strings. Here are two example lists:
#
# name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
# favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
# Here's some help starting your function.
#
# def make_dict(arr1, arr2):
# new_dict = {}
# # your code here
# return new_dict
# Hacker Challenge:
# If the lists are of unequal length, the longer list should be used for the keys, the shorter for the values.
| true
|
503355cdd49fa7399ed1062a112b8de55f1c0654
|
tme5/PythonCodes
|
/Daily Coding Problem/PyScripts/Program_0033.py
| 926
| 4.25
| 4
|
'''
This problem was asked by Microsoft.
Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle numbers.
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
2
1.5
2
3.5
2
2
2
Created on 03-Jul-2019
@author: Lenovo
'''
def median(arr):
temp_arr=[]
for i in arr:
temp_arr.append(i)
temp_arr.sort()
if len(temp_arr)==1:
print(temp_arr[0])
elif len(temp_arr)%2==0:
mid=round(len(temp_arr)/2)
print((temp_arr[mid]+temp_arr[mid-1])/2)
else:
mid=round(len(temp_arr)/2)-1
print(temp_arr[mid])
def main():
median([2, 1, 5, 7, 2, 0, 5])
if __name__ == '__main__':
main()
| true
|
42716bcb27499c2079a9eda6925d9ae969217adf
|
tme5/PythonCodes
|
/CoriolisAssignments/pyScripts/33_file_semordnilap.py
| 1,780
| 4.53125
| 5
|
#!/usr/bin/python
'''
Date: 19-06-2019
Created By: TusharM
33) According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. For example, if "stressed" and "desserts" is part of the word list, the the output should include the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome!
'''
def in_file_semordnilap(file):
'''prints the semordnilap pairs present in the file
Time complexity of the function is O(n)'''
with open(file,'r') as f:
f_rd=f.readlines()
f_cl=[x.strip() for x in f_rd]
ref_set=[]
list(map(lambda x: ref_set.extend(x.split(' ')), f_cl))
for inp in ref_set:
rev_inp=inp[::-1]
if rev_inp in ref_set:
print(inp,rev_inp)
if __name__=='__main__':
in_file_semordnilap('palindrome_input_1.txt')
# SWAP PAWS
# STEEL LEETS
# LEETS STEEL
# PEELS SLEEP
# SERIF FIRES
# FIRES SERIF
# SLEEP PEELS
# STRESSED DESSERTS
# DEVIL LIVED
# LIVED DEVIL
# DESSERTS STRESSED
# DELIVER REVILED
# PAWS SWAP
# REDIPS SPIDER
# DEBUT TUBED
# DEEPS SPEED
# SPEED DEEPS
# TUBED DEBUT
# SPIDER REDIPS
# REVILED DELIVER
# DIAPER REPAID
# DRAWER REWARD
# LOOTER RETOOL
# RETOOL LOOTER
# MURDER REDRUM
# REDRUM MURDER
# REWARD DRAWER
# REPAID DIAPER
# ANIMAL LAMINA
# DEPOTS STOPED
# STOPED DEPOTS
# LAMINA ANIMAL
| true
|
9801097af0d4a761dc1f96039b2cf86cac257c26
|
tme5/PythonCodes
|
/CoriolisAssignments/pyScripts/21_char_freq.py
| 1,200
| 4.40625
| 4
|
#!/usr/bin/python
'''
Date: 18-06-2019
Created By: TusharM
21) Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
'''
def char_freq(inp):
'''Returns a dictionary of frequency of occurence of characters in the input string, considers only characters
Time complexity of this function in worst condition is O(n)'''
if type(inp)==str:
unq=set(x for x in inp if x.isalpha())
unq=sorted(unq,reverse=False)
ret_dict={x:0 for x in unq}
#print(temp)
lst=[x for x in inp if x.isalpha()]
for char in lst:
ret_dict[char]=ret_dict.get(char)+1
else:
raise Exception('Input expected string')
return ret_dict
if __name__=='__main__':
print(char_freq("abbabcbdbabdbdbabababcbcbab"))
#{'a': 7, 'b': 14, 'c': 3, 'd': 3}
print(char_freq('merry christmas and happy new year'))
#{'a': 4, 'c': 1, 'd': 1, 'e': 3, 'h': 2, 'i': 1, 'm': 2, 'n': 2, 'p': 2, 'r': 4, 's': 2, 't': 1, 'w': 1, 'y': 3}
| true
|
f869321ad3d5a053c4e10c8c0e84c83d25b33974
|
tme5/PythonCodes
|
/CoriolisAssignments/pyScripts/30_translate_to_swedish.py
| 1,031
| 4.15625
| 4
|
#!/usr/bin/python
# -*- coding: latin-1 -*-
'''
Date: 19-06-2019
Created By: TusharM
30) Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"r"} and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate() that takes a list of English words and returns a list of Swedish words.
'''
def translate_to_swedish(inp):
'''Converts the English Christmas card message to Swedish using small biligual lexicon Python dictionary
Time complexity of this function in worst condition is O(1)'''
trans_dict={'merry':'god', 'christmas':'jul', 'and':'och', 'happy':'gott', 'new':'nytt', 'year':'r'}
return ' '.join(list(map(lambda word: (trans_dict.get(word)) if word in trans_dict.keys() else word,inp.split(' '))))
if __name__=='__main__':
print(translate_to_swedish('merry christmas and happy new year'))
| true
|
34bf5628fe0ba8ef8d65065cfb3172b781f6ae08
|
jonathanjchu/algorithms
|
/fibonacci.py
| 997
| 4.4375
| 4
|
import math
# comparison of different methods of calculating fibonacci numbers
def fibonacci_iterative(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
# slows down after around n=30
def fibonacci_recursive(n):
if n < 2:
return n
elif n < 3:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# in python, only accurate to around n=75, after that floating point errors cause inaccuracies
sqrt5 = math.sqrt(5)
phi = (1 + sqrt5) / 2
psi = (1 - sqrt5) / 2
def fibonacci_binet(n):
fib = int((phi ** n - psi ** n) / sqrt5)
return fib
def display_fib(i):
fib_i = fibonacci_iterative(i)
fib_r = fibonacci_recursive(i)
fib_b = fibonacci_binet(i)
print(f"{i:3}: {fib_i:10} {fib_r:12} {fib_b:14}")
print(" n Iterative Recursive Binet's Formula")
print("-----------------------------------------------")
display_fib(10)
display_fib(20)
display_fib(30)
display_fib(40)
| false
|
46bcbbe3a779b19a3c021be114ebb33846785e49
|
thien-truong/learn-python-the-hard-way
|
/ex15.py
| 617
| 4.21875
| 4
|
from sys import argv
script, filename = argv
# A file must be opened before it can be read/print
txt = open(filename)
print "Here's your file {}:".format(filename)
# You can give a file a command (or a function/method) by using the . (dot or period),
# the name of the command, and parameteres.
print txt.read() # call a function on txt. "Hey txt! Do your read command with no parameters!"
# it is important to close files when you are done with them
txt.close()
print "I'll also ask you to type it again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt_again.close()
| true
|
8a745e216a89e5a3f6c9d4111ea2bc38d37e4eb7
|
thien-truong/learn-python-the-hard-way
|
/ex18.py
| 1,209
| 4.59375
| 5
|
# Fuctions: name the pieces of code the way ravirables name strings and numbers.
# They take arguments the way your scripts take argv
# They let you make "tiny commands"
# this one is like your scripts with argv
# this function is called "print_two", inside the () are arguments/parameters
# This is like your script with argv
# The keyword def introduces a function definition. It must be followed by the
# function name and the parenthesized list of formal parameters. The statements that
# form the body of the function start at the next line, and must be indented.
def print_two(*args):
"""print 2 arguments.""" # This is a docstring or documentation string. It should concisely sumarize the object's purpose
arg1, arg2 = args
print "arg1: {}, arg2: {}".format(arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: {}, arg2: {}".format(arg1, arg2)
# This just takes one argument
def print_one(arg1):
print "arg1: {}".format(arg1)
# This one takes no arguments:
def print_none():
print "I got nothing'."
print_two("zed","shaw")
print_two_again("zed","shaw")
print_one("First!")
print_none()
| true
|
4a98b19419c953a3b12a1df262c3674a6b3a8967
|
kahuroA/Python_Practice
|
/holiday.py
| 1,167
| 4.53125
| 5
|
"""#Assuming you have a list containing holidays
holidays=['february 14', 'may 1', 'june 1', 'october 20']
#initialized a list with holiday names that match the holidays list
holiday_name=['Valentines', 'Labour Day', 'Mashujaa']
#prompt user to enter month and date
month_date=input('enter month name and date')
#check if the entered string is in our list of holidays
if month_date in holidays:
#get the index of the month date in holiday list
idx=holidays.index(month_date)
#use that index to get the holiday name from holiday_name list
print(holiday_name[idx])
else:
print('entered month and date do not correspond to a holiday')"""
holidays=['02-14','05-1','10-20']
holiday_name=['Valentines', 'Labour Day', 'Mashujaa']
#prompt user to enter month and date
month_date=input('enter month name and date')
#check if the entered string is in our list of holidays
if month_date in holidays:
#get the index of the month date in holiday list
idx=holidays.index(month_date)
#use that index to get the holiday name from holiday_name list
print(holiday_name[idx])
else:
print('entered month and date do not correspond to a holiday')
| true
|
3987d9b65bb9e9e5555e92c42bcdde97b3464e18
|
linxiaoru/python-in-action
|
/examples/basic/function_default.py
| 435
| 4.21875
| 4
|
"""
⚠️
只有那些位于参数列表末尾的参数才能被赋予默认参数值,意即在函数的参数列表中拥有默认参数值的参数不能位于没有默认参数值的参数之前。
这是因为值是按参数所处的位置依次分配的。举例来说,def func(a, b=5) 是有效的,但 def func(a=5, b) 是无效的。
"""
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5)
| false
|
ec3010b56ca544f4910d38d6bf5c5dc8e61ff30e
|
l-ejs-l/Python-Bootcamp-Udemy
|
/Lambdas/filter.py
| 883
| 4.15625
| 4
|
# filter(function, iterable)
# returns a filter object of the original collection
# can be turned into a iterator
num_list = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, num_list))
print(evens)
users = [
{"username": "Samuel", "tweets": ["IO love cake", "IO love cookies"]},
{"username": "Katie", "tweets": ["IO love my cat"]},
{"username": "Jeff", "tweets": []},
{"username": "Bob123", "tweets": []},
{"username": "doggo_luvr", "tweets": ["dogs are the best"]},
{"username": "guitar_gal", "tweets": []}
]
# FILTER AND MAP TOGETHER
filtered_mapped = list(map(lambda user: user["username"].upper(),
filter(lambda u: not u["tweets"], users)))
print(filtered_mapped)
# Same as above
filtered_mapped_list_comp = [user["username"].upper() for user in users if not user["tweets"]]
print(filtered_mapped_list_comp)
| true
|
c59e167d00e927e6ca41268b9490b3eb6722ad3d
|
l-ejs-l/Python-Bootcamp-Udemy
|
/Iterators-Generators/generator.py
| 410
| 4.1875
| 4
|
# A generator is returned by a generator function
# Instead of return it yields (return | yield)
# Can be return multiple times, not just 1 like in a normal function
def count_up_to(max_val):
count = 1
while count <= max_val:
yield count
count += 1
# counter now is a generator and i can call the method next(counter)
counter = count_up_to(5)
for i in count_up_to(5):
print(i)
| true
|
d3b10c9fdd390fdf8068c1e343da8c334c034437
|
l-ejs-l/Python-Bootcamp-Udemy
|
/Lambdas/zip.py
| 437
| 4.4375
| 4
|
# zip(iterable, iterable)
# Make an iterator that agregate elements from each of the iterables.
# Returns an iterator of tuples, where the i'th tuple contains the i'th element from each of the of the argument
# sequences or iterables.
# The iterator stops when the shortest input iterable is exhausted
first_zip = zip([1, 2, 3], [4, 5, 6])
print(list(first_zip)) # [(1, 4), (2, 5), (3, 6)]
print(dict(first_zip)) # {1: 4, 2: 5, 3: 6}
| true
|
74e0cdcdf5b7d6c141295e055200eadec3a8619c
|
victoorraphael/wppchatbot
|
/maisOpção_Joao.py
| 1,401
| 4.1875
| 4
|
def saudacao():
print('Olá, digite seu nome: ')
nome = input()
while(True):
print('{}, digite o numero referente a opção desejada:'.format(nome))
print('\n')
print('1 - Novo pedido')
print('2 - Alteração de pedido')
print('3 - Mais opções')
op = int(input())
if(op == 1):
return novo_pedido()
elif(op == 2):
return alteracao_pedido()
elif (op == 3):
return mais_opcoes()
else:
print('Essa opção não existe')
def novo_pedido():
print('Essa é a opção novo pedido')
def alteracao_pedido():
print('Essa é a opção alteração pedido')
def mais_opcoes():
print('Essa é a opção mais opções')
#saudacao()
def mais_opcoes():
print('Mais Opções')
print('\n')
while(True):
print('digite o numero referente a opção desejada:')
print('\n')
print('1 - Falar com Atendente Humana')
print('2 - Voltar para as opções')
op = int(input())
if(op == 1):
print('Essa opção - fala com a Atendente Humana')
return saudacao()
elif(op == 2):
return saudacao()
else:
print('Essa opção não é válida')
return mais_opcoes()
mais_opcoes()
| false
|
448784979c9edc5a47e210b51f3eb317f81dad70
|
rajeshpandey2053/Python_assignment_3
|
/merge_sort.py
| 939
| 4.1875
| 4
|
def merge(left, right, arr):
i = 0
j =0
k = 0
while ( i < len(left) and j < len(right)):
if (left[i] <= right[j]):
arr[k] = left[i]
i = i + 1
else:
arr[k] = right[j]
j = j + 1
k = k + 1
# if remaining in left
while(i < len(left)):
arr[k] = left[i]
i = i +1
k = k + 1
# if remaining in right
while(i < len(right)):
arr[k] = right[i]
i = i +1
k = k + 1
def merge_sort(arr):
if len(arr)<2:
return
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
merge(left, right,arr)
#main function
arr = list()
num = int(input("Enter the number of elements in the list"))
for _ in range(num):
arr.append(int(input("Enter item: ")))
merge_sort(arr)
print("The sorted list through merge sort is : ", arr)
| false
|
fae187d17f928d0791df8d0f4f7d5f678d09c5cd
|
AnanyaRao/Python
|
/tryp10.py
| 224
| 4.28125
| 4
|
def factorial(num):
fact=1;
i=1;
for i in range(i,num+1):
fact=fact*i;
return fact;
num=int(input('Enter the number:'))
fact=factorial(num);
print('The factorial of the number is:',fact)
| true
|
bf5ca4a2000a7d1ffa895ec758308b80ef1cb93a
|
calwoo/ppl-notes
|
/wengert/basic.py
| 1,831
| 4.25
| 4
|
"""
Really basic implementation of a Wengert list
"""
# Wengert lists are lists of tuples (z, g, (y1,...)) where
# z = output argument
# g = operation
# (y1,...) = input arguments
test = [
("z1", "add", ["x1", "x1"]),
("z2", "add", ["z1", "x2"]),
("f", "square", ["z2"])]
# Hash table to store function representations of operator names
G = {
"add" : lambda a, b: a + b,
"square": lambda a: a*a}
# Hash table to store initialization values
val = {
"x1": 3,
"x2": 7}
print("x1 -> {}, x2 -> {}".format(val["x1"], val["x2"]))
# Evaluation function
def eval(f, val):
for z, g, inputs in f:
# Fetch operation
op = G[g]
# Apply to values
args = list(map(lambda v: val[v], inputs))
val[z] = op(*args)
return val[z]
print("eval(test) -> {}".format(eval(test, val)))
# To do backpropagation of the Wengert list, we need the derivatives
# of each of the primitive operators.
DG = {
"add" : [(lambda a, b: 1), (lambda a, b: 1)],
"square": [lambda a: 2*a]}
# We then go through the Wengert list in reverse, accumulating gradients
# when we pass through an operation.
def backpropagation(f, vals):
# Initialize gradient tape
delta = {"f": 1} # df/df = 1
# Go through Wengert list in reverse order
for z, g, inputs in reversed(f):
args = list(map(lambda v: vals[v], inputs))
for i in range(len(inputs)):
# Get gradient
dop = DG[g][i]
yi = inputs[i]
if yi not in delta:
delta[yi] = 0
# Apply chain rule
delta[yi] += delta[z] * dop(*args)
return delta
delta = backpropagation(test, val)
print("df/dx1 -> {}, df/dx2 -> {}".format(delta["x1"], delta["x2"]))
| true
|
d3b6d836f217cfc764986f9873ab9d2dd92deb4c
|
wolfblunt/DataStructure-and-Algorithms
|
/Sorting/BubbleSort.py
| 336
| 4.125
| 4
|
def bubble_sort(nums):
for i in range(len(nums)-1):
for j in range(0,nums-1-i,1):
if nums[j] > nums[j+1]:
swap(nums, j ,j+1)
return nums
def swap(nums, i ,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
if __name__ == '__main__':
nums = [12,34,23,1,5,0,56,22,-1,-56,-34,88,97,57]
bubble_sort(nums)
print(nums)
| false
|
936ce5e1d8181e03d394ba350ef26c10ee575bb6
|
sonias747/Python-Exercises
|
/Pizza-Combinations.py
| 1,614
| 4.15625
| 4
|
'''
On any given day, a pizza company offers the choice of a certain
number of toppings for its pizzas. Depending on the day, it provides
a fixed number of toppings with its standard pizzas.
Write a program that prompts the user (the manager) for the number of
possible toppings and the number of toppings offered on the standard
pizza and calculates the total number of different combinations of toppings.
Recall that the number of combinations of k items from n possibilities
is given by the formula nCk = n!/k!(n−k)!.
'''
'''
prompt user for number of possible toppings x
prompt user for number of toppings on standard pizza y
get factorial of x
get factorial of y
if y = x
print possible combinations 1
if y is greater than x
print possible combinations 0
if y is 1
print possible combinations y
else use binomial coefficient to get possible combinations
print possible combinations
'''
x = int(input('Enter number of possible toppings: '))
y = int(input('Enter number of toppings on standard pizza: '))
if x == 0:
xfact = 1
elif x == 1:
xfact = 1
else:
xfact = 1
for i in range(1, x + 1):
xfact *= i
continue
if y == 0:
yfact = 1
elif x == 1:
yfact = 1
else:
yfact = 1
for i in range(1, y + 1):
yfact *= i
continue
import sys
if y == x :
print('Possible Combinations: 1')
sys.exit()
if y > x:
print('Possible Combinations: 0')
sys.exit()
if y == 1:
print('Possible Combinations: ', x)
else:
posscomb = xfact // (yfact*(x-y))
print('Possible Combinations:', posscomb)
| true
|
62021b456a4f6fbaeed24422fa09429698a7459d
|
ethanschreur/python-syntax
|
/words.py
| 346
| 4.34375
| 4
|
def print_upper_words(my_list, must_start_with):
'''for every string in my_list, print that string in all uppercase letters'''
for word in my_list:
word = word.upper()
if word[0] in must_start_with or word[0].lower() in must_start_with:
print(word)
print_upper_words(['ello', 'hey', 'yo', 'yes'], {"h", "y"})
| true
|
b5887edb1d489421105fe45ca7032fb136c479df
|
KenMatsumoto-Spark/100-days-python
|
/day-19-start/main.py
| 1,614
| 4.28125
| 4
|
from turtle import Turtle, Screen
import random
screen = Screen()
#
# def move_forwards():
# tim.forward(10)
#
#
# def move_backwards():
# tim.backward(10)
#
#
# def rotate_clockwise():
# tim.right(10)
#
#
# def rotate_c_clockwise():
# tim.left(10)
#
#
# def clear():
# tim.penup()
# tim.clear()
# tim.home()
# tim.pendown()
#
#
# screen.listen()
# screen.onkey(key="w", fun=move_forwards)
# screen.onkey(key="s", fun=move_backwards)
# screen.onkey(key="d", fun=rotate_clockwise)
# screen.onkey(key="a", fun=rotate_c_clockwise)
# screen.onkey(key="c", fun=clear)
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race?")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-75, -45, -15, 15, 45, 75]
all_turtles = []
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[turtle_index])
new_turtle.penup()
new_turtle.goto(x=-230, y=y_positions[turtle_index])
all_turtles.append(new_turtle)
is_race_on = False
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You've Won! The {winning_color} turtle is the winner!")
else:
print(f"You Lost! The {winning_color} turtle is the winner!")
rand_dist = random.randint(0, 10)
turtle.forward(rand_dist)
screen.exitonclick()
| true
|
d3145d494d82b2757f415946e7240c3171d39dcb
|
ARSimmons/IntroToPython
|
/Students/SSchwafel/session01/grid.py
| 2,264
| 4.28125
| 4
|
#!/usr/bin/python
#characters_wide_tall = input('How many characters wide/tall do you want your box to be?: ')
##
## This code Works! - Commented to debug
##
#def print_grid(box_dimensions):
#
# box_dimensions = int(box_dimensions)
#
# box_dimensions = (box_dimensions - 3)/2
#
# print box_dimensions
#
# if box_dimensions % 2 == 0 and box_dimensions != 2:
#
# print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+'
#
# for i in range(box_dimensions):
#
# print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
#
# print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+'
#
# for i in range(box_dimensions):
#
# print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
#
# print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+'
#
# #return True
#
# else:
#
# print "That's an even number, but the box must have an odd-numbered dimension"
#
# return
#
#</ End working chunk>
#
#
user_dimensions = raw_input("Please enter how many characters wide you'd like your 3x3 grid: ")
def print_3x3_grid(box_dimensions):
box_dimensions = int(user_dimensions)
box_dimensions = box_dimensions
print box_dimensions
if box_dimensions % 3 == 0 and box_dimensions != 3:
box_dimensions = (box_dimensions - 1) / 3
print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+','- ' * box_dimensions,'+'
for i in range(box_dimensions):
print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+','- ' * box_dimensions,'+'
for i in range(box_dimensions):
print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+','- ' * box_dimensions,'+'
for i in range(box_dimensions):
print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+','- ' * box_dimensions,'+'
print_3x3_grid(user_dimensions)
| false
|
c56d992234d558fd0b0b49aa6029d6d287e90f2a
|
ARSimmons/IntroToPython
|
/Students/Dave Fugelso/Session 2/ack.py
| 2,766
| 4.25
| 4
|
'''
Dave Fugelso Python Course homework Session 2 Oct. 9
The Ackermann function, A(m, n), is defined:
A(m, n) =
n+1 if m = 0
A(m-1, 1) if m > 0 and n = 0
A(m-1, A(m, n-1)) if m > 0 and n > 0.
See http://en.wikipedia.org/wiki/Ackermann_funciton
Create a new module called ack.py in a session02 folder in your student folder.
In that module, write a function named ack that performs Ackermann's function.
Write a good docstring for your function according to PEP 257.
Ackermanns function is not defined for input values less than 0. Validate inputs to your function and return None if they are negative.
The wikipedia page provides a table of output values for inputs between 0 and 4. Using this table, add a if __name__ == "__main__": block to test your function.
Test each pair of inputs between 0 and 4 and assert that the result produced by your function is the result expected by the wikipedia table.
When your module is run from the command line, these tests should be executed. If they all pass,
print All Tests Pass as the result.
Add your new module to your git clone and commit frequently while working on your implementation. Include good commit messages that explain concisely both what you are doing and why.
When you are finished, push your changes to your fork of the class repository in GitHub. Then make a pull request and submit your assignment in Canvas.
'''
#Ackermann function
def ack(m, n):
'''
Calculate the value for Ackermann's function for m, n.
'''
if m < 0 or n < 0: return None
if m == 0: return n+1
if n == 0: return ack(m-1, 1)
return ack (m-1, ack (m, n-1))
class someClass (object):
def __init__(self):
self.setBody('there')
def afunc (self, a):
print a, self.getBody()
def getBody(self):
return self.__body
def setBody(self, value):
self.__body = value
body = property(getBody, setBody, None, "Body property.")
if __name__ == "__main__":
'''
Unit test for Ackermann function. Print table m = 0,4 and n = 0,4.
'''
#Print nicely
print 'm/n\t\t',
for n in range(0,5):
print n, '\t',
print '\n'
for m in range (0,4):
print m,'\t',
for n in range(0,5):
print '\t',
print ack(m, n),
print
# for the m = 4 row, just print the first one (n = 0) otherwise we hit a stack overflow (maximum resursion)
m = 4
print m,'\t',
for n in range(0,1):
print '\t',
print ack(m, n),
print '\t-\t-\t-\t-'
print 'All Tests Pass'
s = someClass ()
s.afunc('hello')
s.body = 'fuck ya!'
s.afunc('hello')
s.body = 'why not?'
| true
|
d5071d9e6bac66ad7feae9c7bdaafb086c562f0f
|
ARSimmons/IntroToPython
|
/Students/SSchwafel/session01/workinprogress_grid.py
| 1,630
| 4.28125
| 4
|
#!/usr/bin/python
#characters_wide_tall = input('How many characters wide/tall do you want your box to be?: ')
##
## This code Works! - Commented to debug
##
#def print_grid(box_dimensions):
#
# box_dimensions = int(box_dimensions)
#
# box_dimensions = (box_dimensions - 3)/2
#
# print box_dimensions
#
# if box_dimensions % 2 == 0 and box_dimensions != 2:
#
# print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+'
#
# for i in range(box_dimensions):
#
# print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
#
# print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+'
#
# for i in range(box_dimensions):
#
# print '| ',' ' * box_dimensions,'| ',' ' * box_dimensions,'| '
#
# print '+ ','- ' * box_dimensions,'+ ','- ' * box_dimensions,'+'
#
# #return True
#
# else:
#
# print "That's an even number, but the box must have an odd-numbered dimension"
#
# return
#
#</ End working chunk>
#
#
how_many_boxes = input("Please enter how many boxes wide you'd like your grid: ")
def print_3x3_grid(how_many_boxes):
how_many_boxes = int(how_many_boxes)
for i in range(how_many_boxes):
print '+ ',
print '- ',
print '- ',
print '- ',
print '- ',
print '- ',
print '+'
for i in range(5):
print '| ',' ' * 7 ,'|'
print '+ ',
print '- ',
print '- ',
print '- ',
print '- ',
print '- ',
print '+'
print_3x3_grid(how_many_boxes)
| false
|
688ede91119829d5ec4b75452ef18a5a29d6bd29
|
akidescent/GWC2019
|
/numberWhile.py
| 1,018
| 4.25
| 4
|
#imports the ability to get a random number (we will learn more about this later!)
from random import *
#Generates a random integer.
aRandomNumber = randint(1, 20) #set variable aRandomNumber to random integer (1-20)
#can initialize any variable
# For Testing: print(aRandomNumber)
numGuesses = 0
while True: #set a forever loop
guess = input("You have 20 tries. Guess a number between 1 and 20 (inclusive): ") #getting user input, a string
if not guess.isnumeric(): # checks if a string is only digits 0 to 20
print("That's not a positive whole number, try again!")
continue
else:
guess = int(guess)
numGuesses += 1
if aRandomNumber == guess:
print("Congradulations, you guessed the right number!")
print(aRandomNumber)
break
elif (aRandomNumber < guess):
print("Sorry your guess is too high, that's not it.")
elif (aRandomNumber > guess):
print("Sorry your guess is too low, that's not it.")
if numGuesses >= 20: #number of tries >=2
print("Sorry, you ran out of tries.")
break
| true
|
694c11011b30fe791dcc3dda50955d0a3610380f
|
Diogo-Miranda/Curso-Python-3
|
/exercicios/exercicio001-func.py
| 1,161
| 4.28125
| 4
|
"""""
1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome
"""""
def saudacao(saudacao="Seja bem-vindo", nome="Diogo"):
print(f'{saudacao} {nome}')
saudacao("Olá", "Erika")
"""""
2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre eles
"""""
def sum(n1=0, n2=0, n3=0):
return n1+n2+n3
print(sum(2,3,4))
"""""
3 - Crie uma função que receba 2 números. O primeiro é um valor e o segundo um percentual
Retorne o valor do primeiro número somado do aumento do percentual do mesmo
"""""
def sumPercent(n1, percent):
return n1*(1+(percent/100))
result = sumPercent(100, 30)
print(result)
"""""
4 - Fizz Buzz - Se o parâmetro da função for divisível por 2, retorn fizz,
se o parâmetro da função for divisível por 5, retorne buzz.
Se o parâmetro da função for divisível por 5 e por 3, retorne FizzBuzz,
caso contrário, retorne o númetro enviado
"""""
def fizzBuzz(n):
result = n
if n % 2 == 0 and n % 5 == 0:
result = 'FizzBuzz'
elif n % 2 == 0:
result = 'Fizz'
elif n % 5 == 0:
result = 'Buzz'
return result
print(fizzBuzz(11))
| false
|
4ff2b4316f03556cd8ef992efc1121b7e6c4fe18
|
wiecodepython/Exercicios
|
/Exercicio 2/AdrianneVer/Exercicio_Apostila.py
| 1,244
| 4.5625
| 5
|
# >> Python como Calculadora
from math import pi, pow, sqrt
print("Hello, world!")
# Hello, world
#------------------Operadores matemáticos---------------#
# Operador Soma (+)
print(3 + 5)
print(9 + 12)
print(7 + 32)
print(4.5 + 7.3)
print(7.9 + 18.2)
print(3.6 + 34.1)
# Operador Subtração (-)
print(9-7)
print(15-20)
print(45-74)
# Operador Mutliplicação (*)
print(2 * 5)
print(4 * 9)
print(10 * 10)
print(2 * 2 * 2)
# Operador divisão (/)
print(45 / 5)
print(100 / 20)
print(9 / 3)
print(10 / 3)
# Divisao inteira (//)
print(10 // 3)
print(11 // 2)
print(100 // 6)
# Resto da divisão ( % )
print(10 % 2)
print( 15 % 4)
print(100 % 6)
# Potenciação/Exponenciação ( ** )
print(2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 )
print(2 ** 10)
print(10 ** 3)
print((10 ** 800 + 9 ** 1000) * 233)
# Raiz quadrada
print(4 ** 0.5)
print(sqrt(16))
# Número pi
print(pi)
#------------------ Expressões Númericas-------------------#
print(3 + 4 * 2)
print (7 + 3 * 6 - 4 ** 2)
print((3 + 4) * 2)
print((8 / 4) ** (5 - 2))
# Notação Cientifica
print(10e6)
print(1e6)
print(1e-5)
print(1E6)
# Comentário
print(3 + 4) # operador soma
# operadores lógicos
print(2 < 10)
print(2 > 11 )
print(10 > 10 )
print(10 >= 10)
print(42 == 25)
| false
|
6e53d955acd35f5f1da0fcdde636fa234e57bfcb
|
snail15/CodingDojo
|
/Python/week3/Dictionary/dictionary.py
| 227
| 4.375
| 4
|
dict = {
"name": "Sungin",
"country of birth": "Korea",
"age": 30,
"favorite language": "Korean"
}
def printdict(dict):
for key in dict:
print("My {0} is {1}".format(key, dict[key]))
printdict(dict)
| false
|
42f6e8a1a8cbd172c92d6ba4ad7a115ac3982bb7
|
EugeneStill/PythonCodeChallenges
|
/open_the_lock.py
| 2,132
| 4.125
| 4
|
import unittest
import collections
# https://www.geeksforgeeks.org/deque-in-python/
class OpenTheLock(unittest.TestCase):
"""
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0' through '9'.
The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'.
Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes,
the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock,
return the minimum total number of turns required to open the lock, or -1 if it is impossible.
"""
def open_the_lock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
dead_set = set(deadends)
queue = collections.deque([('0000', 0)])
visited = set('0000')
while queue:
(wheel_state, turns) = queue.popleft()
if wheel_state == target:
return turns
elif wheel_state in dead_set:
continue
for i in range(4):
# for each slot in wheel, move down 1, up 1 to get new combos
digit = int(wheel_state[i])
for move in [-1, 1]:
new_digit = (digit + move) % 10
new_combo = wheel_state[:i]+str(new_digit)+wheel_state[i+1:]
if new_combo not in visited:
visited.add(new_combo)
queue.append((new_combo, turns+1))
return -1
def test_open_lock(self):
self.assertEqual(self.open_the_lock(["0201","0101","0102","1212","2002"], "0202"), 6)
self.assertEqual(self.open_the_lock(["8888"], "0009"), 1)
self.assertEqual(self.open_the_lock(["8887","8889","8878","8898","8788","8988","7888","9888"], "8888"), -1)
| true
|
3ea411d749f483c8fd5c63ad0ac7fd8a5c8c0a01
|
EugeneStill/PythonCodeChallenges
|
/rotting_oranges.py
| 2,767
| 4.125
| 4
|
import unittest
from collections import deque
class OrangesRotting(unittest.TestCase):
"""
You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return minimum number of minutes that must pass until no cell has a fresh orange. If this is impossible, return -1.
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: Bottom left corner (row 2, column 0) is never rotten, bc rotting only happens 4-directionally.
"""
def oranges_rotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# Time complexity: O(rows * cols) -> each cell is visited at least once
# Space complexity: O(rows * cols) -> in the worst case if all the oranges are rotten they will be added to the queue
rows = len(grid)
if rows == 0: # check if grid is empty
return -1
EMPTY, FRESH, ROTTEN = 0, 1, 2
cols, fresh_cnt, minutes_passed, rotten = len(grid[0]), 0, 0, deque()
# visit each cell in the grid & update fresh count & rotten queue
for r in range(rows):
for c in range(cols):
if grid[r][c] == ROTTEN:
rotten.append((r, c))
elif grid[r][c] == FRESH:
fresh_cnt += 1
# If there are rotten oranges in the queue and there are still fresh oranges in the grid keep looping
while rotten and fresh_cnt > 0:
# update the number of minutes for each level pass
minutes_passed += 1
# process rotten oranges on the current level
for _ in range(len(rotten)):
row, col = rotten.popleft()
# visit all the valid adjacent cells
for new_row, new_col in [(row-1,col), (row+1,col), (row,col-1), (row,col+1)]:
if not 0 <= new_row < rows or not 0 <= new_col < cols or grid[new_row][new_col] != FRESH:
continue
# update the fresh count, mark cell rotten and add to queue
fresh_cnt -= 1
grid[new_row][new_col] = ROTTEN
rotten.append((new_row, new_col))
return minutes_passed if fresh_cnt == 0 else -1
def test_ro(self):
grid1 = [[2,1,1],[1,1,0],[0,1,1]]
grid2 = [[2,1,1],[0,1,1],[1,0,1]]
self.assertEqual(self.oranges_rotting(grid1), 4)
self.assertEqual(self.oranges_rotting(grid2), -1)
| true
|
59a8864a5f317ead31eb8d93246776eed2342fec
|
EugeneStill/PythonCodeChallenges
|
/word_break_dp.py
| 1,621
| 4.125
| 4
|
import unittest
class WordBreak(unittest.TestCase):
"""
Given a string s and a dictionary of strings wordDict, return true if s can be segmented
into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
"""
def word_break(self, s, words):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False] * len(s)
for i in range(len(s)):
for w in words:
# does current word end at i
# (AND dp[idx_before_word] is True (meaning a valid word ended right before this word)
# OR idx_before_word == -1 (meaning its ok that there was no valid word before it))
idx_before_word = i - len(w)
if w == s[idx_before_word + 1:i + 1] and (dp[idx_before_word] or idx_before_word == -1):
dp[i] = True
return dp[-1]
def test_word_break(self):
words = ["cats","dog","sand","and","cat", "pen", "apple"]
good_string = "applepenapple"
bad_string = "catsandog"
self.assertTrue(self.word_break(good_string, words))
self.assertFalse(self.word_break(bad_string, words))
| true
|
26d1d171bfa5feab074dd6dafef2335befbc4ca7
|
EugeneStill/PythonCodeChallenges
|
/unique_paths.py
| 2,367
| 4.28125
| 4
|
import unittest
import math
class UniquePaths(unittest.TestCase):
"""
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]).
The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]).
The robot can only move either down or right at any point in time.
Given 2 integers m and n, return the number of unique paths that the robot can take to reach the bottom-right corner
The test cases are generated so that the answer will be less than or equal to 2 * 109.
"""
# 2. Math solution
# Note, that we need to make overall n + m - 2 steps, and exactly m - 1 of them need to be right moves and n - 1 down steps. By definition this is numbef of combinations to choose n - 1 elements from n + m - 2.
# Complexity: time complexity is O(m+n), space complexity is O(1).
def unique_paths(self, rows, cols):
dp = [1] * cols
print("\n" + str(dp))
for row in range(1, rows):
print("CHECKING ROW {}".format(row))
for col in range(1, cols):
dp[col] = dp[col - 1] + dp[col]
print(str(dp))
return dp[-1] if rows and cols else 0
# 2. Math solution
# Note, that we need to make overall n + m - 2 steps, and exactly m - 1 of them need to be right moves
# and n - 1 down steps. By definition this is number of combinations to choose n - 1 elements from n + m - 2.
# Complexity: time complexity is O(m+n), space complexity is O(1).
def unique_paths_math(self, m, n):
print("FACT MN {}".format(math.factorial(m+n-2)))
print("FACT M {}".format(math.factorial(m -1)))
print("FACT N {}".format(math.factorial(n - 1)))
return math.factorial(m+n-2)//math.factorial(m-1)//math.factorial(n-1)
def test_unique_paths(self):
print(self.unique_paths(3, 7))
# LOGGING
# [1, 1, 1, 1, 1, 1, 1] # INIT ARRAY FOR ROW 0 with 1's
# CHECKING ROW 1 # FROM HERE OUT, ADD COL[COL-1] TO COL TO UPDATE EACH COL VALUE
# [1, 2, 1, 1, 1, 1, 1]
# [1, 2, 3, 1, 1, 1, 1]
# [1, 2, 3, 4, 1, 1, 1]
# [1, 2, 3, 4, 5, 1, 1]
# [1, 2, 3, 4, 5, 6, 1]
# [1, 2, 3, 4, 5, 6, 7]
# CHECKING ROW 2
# [1, 3, 3, 4, 5, 6, 7]
# [1, 3, 6, 4, 5, 6, 7]
# [1, 3, 6, 10, 5, 6, 7]
# [1, 3, 6, 10, 15, 6, 7]
# [1, 3, 6, 10, 15, 21, 7]
# [1, 3, 6, 10, 15, 21, 28]
| true
|
fdd5987f684a90e78ba5622fd37919c43951bd20
|
EugeneStill/PythonCodeChallenges
|
/course_prerequisites.py
| 2,711
| 4.34375
| 4
|
import unittest
import collections
class CoursePrereqs(unittest.TestCase):
"""
There are a total of num_courses courses you have to take, labeled from 0 to num_courses - 1.
You are given an array prerequisites where prerequisites[i] = [ai, bi]
meaning that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses.
If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Input: num_courses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
"""
def get_order(self, num_courses, prerequisites):
"""
:type num_courses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
# map courses to preqs and preqs to courses
course_preq_dic = {course: set() for course in range(num_courses)}
preq_course_dic = collections.defaultdict(set)
for course, preq in prerequisites:
course_preq_dic[course].add(preq)
preq_course_dic[preq].add(course)
# add any courses without preqs to new taken_q
taken_q = collections.deque([])
for course, preq in course_preq_dic.items():
if len(preq) == 0:
taken_q.append(course)
# go through q to see if we can take expected num of courses
taken = []
while taken_q:
course = taken_q.popleft()
taken.append(course)
if len(taken) == num_courses:
return taken
# use preq_course_dic to check every dependent course that had the course we just took as a preq
for dependent in preq_course_dic[course]:
# remove the taken course from the course_preq_dic for any dependent courses
course_preq_dic[dependent].remove(course)
# if dependent course no longer has any preqs then we can add it as course to take
if not course_preq_dic[dependent]:
taken_q.append(dependent)
return False
def test_prereqs(self):
prereqs = [[1,0],[2,0],[3,1],[3,2]]
acceptable_results = [[0,1,2,3], [0,2,1,3]]
self.assertIn(self.get_order(len(prereqs), prereqs), acceptable_results)
| true
|
57d16b965de6e4f82979f42656042af956145410
|
EugeneStill/PythonCodeChallenges
|
/reverse_polish_notation.py
| 2,516
| 4.21875
| 4
|
import unittest
import operator
class ReversePolishNotation(unittest.TestCase):
"""
AKA Polish postfix notation or simply postfix notation
The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.
"""
def reverse_polish_notation(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': 'custom'
}
stack = []
for t in tokens:
if t not in ops:
stack.append(int(t))
continue
r, l = stack.pop(), stack.pop()
if t == '/':
stack.append(int(l/r))
else:
stack.append(ops[t](l, r))
return stack.pop()
#
#
# stack = []
# print("\n" + str(tokens))
# for t in tokens:
# if t not in "+-*/":
# stack.append(int(t))
# else:
# r, l = stack.pop(), stack.pop()
# if t == "+":
# stack.append(l+r)
# elif t == "-":
# stack.append(l-r)
# elif t == "*":
# stack.append(l*r)
# else:
# stack.append(int(float(l)/r))
# print(str(stack))
# return stack.pop()
def test_rpn(self):
input1 = ["2","1","+","3","*"]
input2 = ["4","13","5","/","+"]
input3 = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
self.assertEqual(self.reverse_polish_notation(input1), 9)
self.assertEqual(self.reverse_polish_notation(input2), 6)
self.assertEqual(self.reverse_polish_notation(input3), 22)
# LOGGING
# ['2', '1', '+', '3', '*']
# [2]
# [2, 1]
# [3]
# [3, 3]
# [9]
#
# ['4', '13', '5', '/', '+']
# [4]
# [4, 13]
# [4, 13, 5]
# [4, 2]
# [6]
#
# ['10', '6', '9', '3', '+', '-11', '*', '/', '*', '17', '+', '5', '+']
# [10]
# [10, 6]
# [10, 6, 9]
# [10, 6, 9, 3]
# [10, 6, 12]
# [10, 6, 12, -11]
# [10, 6, -132]
# [10, 0]
# [0]
# [0, 17]
# [17]
# [17, 5]
# [22]
| true
|
47656bdd5d6b6f46cb957f38ecc32184198f9829
|
MariamBilal/python
|
/List.py
| 1,008
| 4.65625
| 5
|
# Making and Printing list
my_list = ['fish','dog','cat','horse','frog','fox','parrot','goat']
print(my_list)
#Using Individual Values from a List
for i in my_list:
print(i)
#Accessing elements in a List
print(my_list[0])
#To title the the items in list.
print(my_list[2].title())
#To print last character from the list.
print(my_list[-1])
#Modifying Elements in a List
my_list[0] = 'jelly fish'
print(my_list)
#Adding Elements to the end of a List
my_list.append('sparrow')
print(my_list)
#Inserting Elements into a List
my_list.insert(0,'kingfisher')
print(my_list)
#removing an Item Using the del Statement
del my_list[0]
print(my_list)
#removing an Item Using the pop() Method
pop_item = my_list.pop(3)
print(my_list)
print(pop_item)
#removing an Item by Value.
my_list.remove('frog')
print(my_list)
#Sorting List:
my_list.sort()
print(my_list)
#Printing a List in Reverse Order
my_list.reverse()
print(my_list)
#Finding the Length of a List
len_of_list = len(my_list)
print(len_of_list)
| true
|
4bc82f2bdf496610241ad272ee9f76b69713c51d
|
codilty-in/math-series
|
/codewars/src/highest_bi_prime.py
| 1,100
| 4.1875
| 4
|
"""Module to solve https://www.codewars.com/kata/highest-number-with-two-prime-factors."""
def highest_biPrimefac(p1, p2, end):
"""Return a list with the highest number with prime factors p1 and p2, the
exponent for the smaller prime and the exponent for the larger prime."""
given_primes = set([p1, p2])
k1 = 0
k2 = 0
highest = 0
for n in range(end, 0, -1):
pf = prime_factors(n, given_primes)
if given_primes == set(pf):
if pf.count(p1) > k1 and pf.count(p2) > k2:
k1 = pf.count(p1)
k2 = pf.count(p2)
highest = n
if (p1 ** k1) * (p2 ** k2) > n:
return [highest, k1, k2]
return None
def prime_factors(n, given_primes):
"""Return a list with all prime factors of n."""
factors = []
if n < 2:
return factors
p = 2
while n >= (p * p):
if n % p:
p += 1
else:
if p not in given_primes:
return []
n = n // p
factors.append(p)
factors.append(n)
return factors
| true
|
d20b15088e93c670f2ddd84ec8d2b78ad0d63199
|
codilty-in/math-series
|
/codewars/src/surrounding_prime.py
| 1,328
| 4.25
| 4
|
def eratosthenes_step2(n):
"""Return all primes up to and including n if n is a prime
Since we know primes can't be even, we iterate in steps of 2."""
if n >= 2:
yield 2
multiples = set()
for i in range(3, n+1, 2):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
def prime(n, primes):
"""Return True if a given n is a prime number, else False."""
if n > 5 and n % 10 == 5:
return False
for p in primes:
if n % p == 0:
return False
return True
def get_next_prime(n, primes, direction=1):
"""Return the next prime of n in given direction."""
if direction > 0:
start = n + 1 if n % 2 == 0 else n + 2
step = 2
stop = n * n
else:
start = n -1 if n % 2 == 0 else n - 2
step = -2
stop = 0
prime_generator = (x for x in xrange(start, stop, step) if prime(x, primes))
return prime_generator.next()
def prime_bef_aft(n):
"""Return the first pair of primes between m and n with step g."""
#n needs to start out as an odd number so we can step over known composites
primes = [p for p in eratosthenes_step2(int(n // 2))]
before = get_next_prime(n, primes, -1)
after = get_next_prime(n, primes, 1)
return [before, after]
| true
|
7a291a64dea198b5050b83dc70f5e30bcf8876f5
|
codilty-in/math-series
|
/codewars/src/nthfib.py
| 524
| 4.1875
| 4
|
"""This module solves kata https://www.codewars.com/kata/n-th-fibonacci."""
def original_solution(n):
"""Return the nth fibonacci number."""
if n == 1:
return 0
a, b = 0, 1
for i in range(1, n - 1):
a, b = b, (a + b)
return b
#better solution
def nth_fib(n):
"""Return the nth fibonacci number. Per the kata, f(1) is supposed to be
0 so the fibonacci sequence for this kata was not indexed at 0."""
a, b = 0, 1
for __ in range(n-1):
a, b = b, a + b
return a
| true
|
9b4a1f7ef0879176a70ee0324c49914d24c76c80
|
achiengcindy/Lists
|
/append.py
| 347
| 4.375
| 4
|
# define a list of programming languages
languages = ['java', 'python', 'perl', 'ruby', 'c#']
# append c
languages.append('c')
print(languages)
# Output : ['java', 'python' ,'perl', 'ruby', 'c#', 'c']
# try something cool to find the last item,
# use **negative index** to find the value of the last item
print(languages[-1])
# should give you c
| true
|
3c35233bf3598594d8a13645d950d25ac4d05bca
|
psycoleptic/Python_class
|
/Funk Task 8.py
| 747
| 4.34375
| 4
|
#Определите функцию, которая принимает значение коэффициентов квадратного уравнения и выводит значение корней или
#предупреждение, что уравнение не имеет корней (в случае если детерминант оказался отрицательным)
def s_eq(a, b, c):
tmp = b**2 - 4*a*c
if tmp < 0:
print("Уравнение не имеет корней!")
else:
x1 = (tmp**0.5 - b)/(2*a)
x2 = (-b - tmp**0.5) / (2 * a)
print(x1, x2)
a = int(input("Print a "))
b = int(input("Print b "))
c = int(input("Print c "))
print(s_eq(a, b, c))
| false
|
08704a8d03cabc6a757eb3b85b46d39183095dfc
|
psycoleptic/Python_class
|
/Funk Task 10.py
| 486
| 4.40625
| 4
|
#Напишите функцию, которая для заданного в аргументах списка, возвращает как результат перевернутый список
def revers(a, b):
old_list = []
for i in range(a, b):
l = i+1
old_list.append(l)
i+= 3
new_list = list(reversed(old_list))
print(old_list)
print(new_list)
a = int(input("Print a "))
b = int(input("Print b "))
print(revers(a, b))
| false
|
d7a0d968a0b1155703ec27009f4c673bab32416f
|
johnmcneil/w3schools-python-tutorials
|
/2021-02-09.py
| 2,405
| 4.40625
| 4
|
# casting to specify the data type
x = str(3)
y = int(3)
z = float(3)
# use type() to get the data type of a variable
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
# you can use single or double quotes
# variables
# variable names are case-sensitive.
# must start with a letter or the underscore character
# cannot start with a number
# can containe alpha-numeric characters and underscores
# camel case
myVariableName = "camel case"
# Pascal Case
MyVariableName = "Pascal case"
# snake case
my_variable_name = "snake case"
# assigning multiple variables in a line
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
# assigning the same value to multiple variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
# unpacking
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
# output variables with print: variable plus text
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
# for numbers, + inside print works as addition
x = 5
y = 10
print(x + y)
# variable with global scope
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
# variable with local scope
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
# global keyword
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
# data types
# assignment of a value, constructor function
# text
str
x = str("Hello World")
x = "Hello World"
# numeric
int
x = int(20)
x = 20
float
x = float(20.5)
x = 20.5
complex
x = complex(1j)
x = 1j
# sequence
list
x = list(("apple", "banana", "cherry"))
x = ["apple", "banana", "cherry"]
tuple
x = tuple(("apple", "banana", "cherry"))
x = ("apple", "banana", "cherry")
range
x = range(6)
x = range(6)
# mapping
dict
x = dict(name="John", age=36)
x = {"name": "John", "age": 36}
# set
set
x = set(("apple", "banana", "cherry"))
x = {"apple", "banana", "cherry"}
frozenset
x = frozenset(("apple", "banana", "cherry"))
x = frozenset({"apple", "banana", "cherry"})
# boolean
bool
x = bool(5)
x = True
# binary
bytes
x = bytes(5)
x = b"Hello"
bytearray
x = bytearray(5)
x = bytearray(5)
memoryview
x = memoryview(bytes(5))
x = memoryview(bytes(5))
# Numbers
# Float can be scientifice with an e to indicate the power of 10
z = -87.7e100
| true
|
df2a11b4b05eb2a086825a7a996347f0f56a75ee
|
johnmcneil/w3schools-python-tutorials
|
/2021-03-05.py
| 1,466
| 4.65625
| 5
|
# regexp
# for regular expressions, python has the built-in package re
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
print(x)
# regex functions
# findall() - returns a list of all matches
x = re.findall("ai", txt)
print(x)
x = re.findall("sdkj", txt)
print(x)
# search() - returns a match object if there is a match anywhere in the string
x = re.search("ai", txt)
print(x)
x = re.search("Portugal", txt)
print(x)
# split() - returns a list where the string has been split at each match
x = re.split("i", txt)
print(x)
x = re.split("\s", txt)
print(x)
x = re.split("q", txt)
print(x)
# maxsplit parameter
# e.g. split string only at first occurence
x = re.split("\s", txt, 1)
print(x)
# sub() - replaces one or many matches with a string
x = re.sub("\s", "9", txt)
print(x)
# count parameter controls the number of replacements
x = re.sub("\s", "9", txt, 2)
print(x)
# Match Object
# contains information about the search and its result
# if there is no match, None will be returned
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x)
# Match object properties and methods
# span() - returns a tuple containing the start and end positions of the match
print(x.span())
# string - print the string passed into the function
print(x.string)
# print the part of the string where there was a match
print(x.group())
# pip
import camelcase
c = camelcase.CamelCase()
txt = "hello world!"
print(c.hump(txt))
| true
|
c31786c6ad2645c08348c68592c2e95c1b924be9
|
krishnakesari/Python-Fund
|
/Operators.py
| 1,296
| 4.15625
| 4
|
# Division (/), Integer Division (//), Remainder (%), Exponent (**), Unary Negative (-), Unary Positive (+)
y = 5
x = 3
z = x % y
z = -z
print(f'result is {z}')
# Bitwise operator (& | ^ << >>)
x = 0x0a
y = 0x02
z = x << y
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
# Comparision Operators
x = 42
y = 73
if x < y:
print('comparision is true')
else:
print('comparision is false')
if x > y:
print('comparision is true')
else:
print('comparision is false')
if x != y:
print('comparision is true')
else:
print('comparision is false')
if x == y:
print('comparision is true')
else:
print('comparision is false')
# Boolean Operators
a = True
b = False
x = ('bear', 'bunny', 'tree')
y = 'tree'
if a and b:
print('expression is true')
else:
print('expression is false')
if a or b:
print('expression is true')
else:
print('expression is false')
if not b:
print('expression is true')
else:
print('expression is false')
if y and x:
print('expression is true')
else:
print('expression is false')
if y is x[2]:
print('expression is true')
else:
print('expression is false')
print(id(y))
print(id(x[2]))
# Operator Precedence
print( 2 + 4 * 5)
| true
|
4e0088bb25588855455f58537abbabb1769b2459
|
ETDelaney/automate-the-boring-stuff
|
/05-01-guess-the-number.py
| 1,343
| 4.21875
| 4
|
# a game for guessing a number
import random
num_of_chances = 5
secret_number = random.randint(1,20)
#print(secret_number)
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 0 and 20.')
print('Can you guess the number? I will give you ' + str(num_of_chances) + ' chances.')
for guessesTaken in range(num_of_chances+1):
if guessesTaken == num_of_chances:
print('You have run out of chances... I was thinking of the number: ' + str(secret_number))
break
try:
if guessesTaken == num_of_chances-1:
print('You have 1 guess remaining, uh oh ;-) \n')
else:
print('You have ' + str(num_of_chances-guessesTaken) + ' guesses remaining.\n')
guess = int(input('Guess: '))
if int(guess) < secret_number:
print('Sorry, too low.')
elif int(guess) > secret_number:
print('Sorry, too high.')
else:
print('Congrats,' + name + '! That is the correct guess.')
if guessesTaken+1 == 1:
print('You got it in a single try!')
else:
print('You got it in ' + str(guessesTaken + 1) + ' tries.')
break
except:
print('You need to enter an integer ... try again.')
| true
|
8d37af2dc7cf5fba984f7c35f343c6741a30653e
|
rustybailey/Project-Euler
|
/pe20.py
| 425
| 4.15625
| 4
|
"""
n! means n * (n - 1) * ... * 3 * 2 * 1
For example, 10! = 10 * 9 * ... 3 * 2 * 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
import math
def sumFactorial(n):
num = math.factorial(n)
total = 0
while (num > 0):
total += num % 10
num = math.trunc(num / 10)
return total
print sumFactorial(100)
| true
|
d23909d63299735beebb3954cc835727b87fa38b
|
myworkshopca/LearnCoding-March2021
|
/basic/types.py
| 564
| 4.15625
| 4
|
age = input("How old are you?")
print("Age is: {0}".format(age))
print("35 / 2 = ", 35 / 2)
print("35 // 2 = ", 35 // 2)
a = 'Hello Somebody'
print("Repeating \"{0}\" {1} times: {2}".format(a, 4, a * 4))
print("Try the named index placeholder:")
print("Name: {name}, Age: {age}".format(age=100, name="Sean"))
b = "Hello\n\"World\"!"
#print(b + a)
c = """hello
Line one "world"
line two
line 4
"""
#print("original: " + c)
#print("Title:" + c.title())
#print("Capitalize:" + c.capitalize())
#print("Upper cases:" + c.upper())
#print("lower cases:" + c.lower())
| false
|
b495c945cfed8db9787f8d9fab4e3c02a5232dfb
|
shagunsingh92/PythonExercises
|
/FaultyCalculator.py
| 1,122
| 4.53125
| 5
|
import operator
'''Exercise: My_faulty_computer
this calculator will give correct computational result for all the numbers except [45*3 = 555, 56+9=77
56/6=4]
'''
def my_faulty():
allowed_operator = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
# ask the user for an input
a = int(input('give me a number:'))
b = int(input('give me another number:'))
opp = input('What operation do you want to perform: ')
if a == 45 and b == 3 and opp == '*':
print(555)
elif a == 56 and b == 9 and opp == '+':
print(77)
elif a == 56 and b == 6 and opp == '/':
print(4)
# https://docs.python.org/3/library/operator.html check the documentation on operators
# operator.add(a,b) is the basic representation
elif opp in ['+', '-', '*', '/']:
result = allowed_operator[opp](a, b)
print(result)
else:
print('I am not capable of performing that computation.')
while True:
my_faulty()
command = input('Do you want to calculate more? ')
if command == 'Yes':
continue
else:
break
| true
|
3302de8bad34c27c4ed7216b5d4b9fb786979c6c
|
allenc8046/CTI110
|
/P4HW4_Chris Allen.py
| 356
| 4.21875
| 4
|
import turtle
redCross = turtle.Screen()
x = turtle.Turtle()
x.color("red") # set x turtle color
x.pensize(3) # set x turtle width
print("It's a red cross!")
print ()
# use a for loop
for redCross in range (4):
x.forward(150)
x.left(90)
x.forward(150)
x.left(90)
x.forward(150)
x.right(90)
| true
|
00129adf4cbb2fda2215c499ba7392ca17e90b10
|
rafaelalmeida2909/Python-Data-Structures
|
/Linked Queue.py
| 2,268
| 4.28125
| 4
|
class Node:
"""Class to represent a node in Python3"""
def __init__(self, data):
self.data = data # Node value
self.next = None # Next node
class LinkedQueue:
"""Class to represent a Linked Queue(without priority) in Python3"""
def __init__(self):
self._front = None # The first element of queue
self._back = None # The last element of queue
self._size = 0 # The size of queue
def enqueue(self, elem):
"""Inserts an element at the end of the queue"""
if self._size == 0:
aux = Node(elem)
self._front = aux
self._back = aux
else:
pointer = self._back
aux = Node(elem)
pointer.next = aux
self._back = aux
self._size += 1
def dequeue(self):
"""Removes and returns the first element from the queue"""
if self._size == 0:
raise Exception("Empty queue")
elem = self._front.data
self._front = self._front.next
self._size -= 1
return elem
def length(self):
"""Returns the size of queue"""
return self._size
def first(self):
"""Returns the first element from queue"""
if self._size == 0:
raise Exception("Empty queue")
return self._front.data
def last(self):
"""Returns the last element from queue"""
if self._size == 0:
raise Exception("Empty queue")
return self._back.data
def empty(self):
"""Returns true if the queue is empty, otherwise, it returns false"""
if self._size == 0:
return True
return False
def __del__(self):
"""Destructor method"""
def __str__(self):
"""Method for representing the linked queue (user)"""
rep = "\033[1;31m" + "first" + "\033[0;0m" + " -> "
pointer = self._front
while pointer != None:
rep += f"{pointer.data} -> "
if pointer.next is None:
break
pointer = pointer.next
rep += "\033[1;34mNone\033[0;0m"
return rep
def __repr__(self):
"""Method for representing the linked queue (developer)"""
return str(self)
| true
|
b314cc818cdf04d37dbc36fae60f5f0ca354182e
|
divineunited/casear_cipher
|
/casear_cipher.py
| 2,649
| 4.125
| 4
|
def casear(message, n, encrypt=True):
'''This casear encryption allows for undercase and capital letters. Pass a message to encrypt or decrypt, n number of positions (must be less than 26) where n will add to the alphabet for encryption and subtract for decryption, and optional encrypt=False to allow for decryption of a message. The message must not include any non alphabetic characters besides a space'''
# creating our dictionary with number key and letter value
num_let = {i:let for i, let in enumerate('abcdefghijklmnopqrstuvwxyz')}
# creating our dictionary with corresponding letter key and number value
let_num = {let:i for i, let in enumerate('abcdefghijklmnopqrstuvwxyz')}
# creating versions for the capital letters
NUM_LET = {i:let for i, let in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ')}
LET_NUM = {let:i for i, let in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ')}
final = ''
# encryption
if encrypt:
# going through our message and replacing each letter with a coded number by adding n to each letter and using the dictionary.
for letter in message:
# if this letter is a space, leave it
if letter in ' ':
final += letter
# if letter is non capital
elif letter in let_num.keys():
# if this is one of the later numbers at the end of the dictionary, loop around to the beginning
if let_num[letter] + n > 25:
final += num_let[let_num[letter]+n-26]
else:
final += num_let[let_num[letter]+n]
# if letter is capitalized
else:
if LET_NUM[letter] + n > 25:
final += NUM_LET[LET_NUM[letter]+n-26]
else:
final += NUM_LET[LET_NUM[letter]+n]
return final
# decryption
else:
for letter in message:
if letter == ' ':
final += letter
elif letter in let_num.keys():
if let_num[letter] - n < 0:
final += num_let[let_num[letter]-n+26]
else:
final += num_let[let_num[letter]-n]
else:
if LET_NUM[letter] - n < 0:
final += NUM_LET[LET_NUM[letter]-n+26]
else:
final += NUM_LET[LET_NUM[letter]-n]
return final
# main testing:
message = 'This is a test of the excellent Casear Cipher'
print(casear(message, 3))
cipher = 'Wklv lv d whvw ri wkh hafhoohqw Fdvhdu Flskhu'
print(casear(cipher,3,encrypt=False))
| true
|
7c4f5a725fb49a86333809956941866f45d0effb
|
MeghaSajeev26/Luminar-Python
|
/Advance Python/Test/pgm5.py
| 448
| 4.4375
| 4
|
#5. What is method overriding give an example using Books class?
#Same method and same arguments --- child class's method overrides parent class's method
class Books:
def details(self):
print("Book name is Alchemist")
def read(self):
print("Book is with Megha")
class Read_by(Books):
def read(self):
print("Book is with Akhil")
b=Read_by()
b.read()
#method overloading---consider no of arguments while callling
| true
|
9f9a506baa32ca4d7f7c69ed5d66eac431d0c37f
|
MeghaSajeev26/Luminar-Python
|
/Looping/for loop/demo6.py
| 212
| 4.21875
| 4
|
#check whether a number is prime or not
num=int(input("enter a number"))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
if(flag>0):
print(num,"is not a prime")
else:
print(num,"is prime")
| true
|
cd4a8b02ac32153c308a9461a170c9086c91e948
|
MeghaSajeev26/Luminar-Python
|
/Advance Python/Regular Expression/Rulesof_Quantifiers/Rule7.py
| 212
| 4.375
| 4
|
#ending with 'a'----consider the whole string
import re
x="a$"
r="aaa abc aaaa cga" #check string ending with 'a'
matcher=re.finditer(x,r)
for match in matcher:
print(match.start())
print(match.group())
| false
|
6bd7154a5b9369d2a4cde07b1b60d62f8bee1a71
|
leonelparrales22/Curso-Python
|
/Clase_2-Operadorers_y_Expresiones/Clase_Parte_2_codigo.py
| 1,122
| 4.3125
| 4
|
# Expresiones Anidadas
print("EXPRESIONES ANIDADAS")
x = 10
# QUEREMOS SABER SI UN NUMERO ESTRA ENTRE 8 Y 10
# Si no cumple nos va a devolver un False
# Si se cumple nos va a devolver un True
# resultado = x>=8 and x<=10
resultado = 8 <= x <= 10
print(resultado)
# Operadores con Asignación
print("OPERADORES CON ASIGNACIÓN")
# En programación se usan muchos los contadores.
# 0
# 0 + 1
# 1
# 1 + 1
# 2
a = 2
print(a)
# a = a + 1
a += 1
print(a)
# a = a + 1
a += 1
print(a)
# Ejercicio
print("Ejericio 1")
# Realizar un programa que lea 2 números por teclado y determine los siguientes
# aspectos (es suficiente con mostrar True o False)
# -Si los dos numeros son iguales (True o False) LISTO
# -Si los dos numeros son diferentes LISTO
# -Si el primero es mayor que el segundo
# -Si el segundo es mayor o igual que primero
n1 = float(input("Introduce el primer número: "))
n2 = int(input("Introduce el primer número: "))
print("¿Son iguales?", n1 == n2)
print("¿Son diferentes?", n1 != n2)
print("¿El primero es mayor que el segundo?", n1 > n2)
print("¿El segundo es mayor o igual que primero?", n2 >= n1)
| false
|
05984d56459fb9738b27f9bc1fe070ede6d948ea
|
uttam-kr/PYTHON
|
/Basic_oops.py
| 1,042
| 4.1875
| 4
|
#!/usr/bin/python
#method - function inside classes
class Employee():
#How to initialize attribute
#init method
def __init__(self, employee_name, employee_age, employee_weight, employee_height):
print('constructor called')
#('init method or constructor called') ---->This __init__ method called constructor
self.name = employee_name
self.age = employee_age
self.weight = employee_weight
self.height = employee_height
def Developer(self):
print("Developer {}".format(self.name))
def is_eligible(self):
print(self.age)
#Variable define under __init__ method called instance variable
#An object employee1 is created using the constructor of the class Employee
employee1 = Employee("Uttam", "age 25", "65 kg", "175 cm")
#self = employee1
#Whenever we create object __init__ gets called, it create space in memory so that we can work with objects.
print(employee1.name)
print(employee1.age)
print(employee1.weight)
print(employee1.height)
print('method call')
employee1.Developer() #Method call
employee1.is_eligible()
| true
|
49f4d48bc9ccc29332f76af833fefa0383defea3
|
fadhilahm/edx
|
/NYUxFCSPRG1/codes/week7-functions/lectures/palindrome_checker.py
| 631
| 4.15625
| 4
|
def main():
# ask for user input
user_input = input("Please enter a sentence:\n")
# sterilize sentence
user_input = sterilize(user_input)
# check if normal equals reversed
verdict = "is a palindrome" if user_input == user_input[::-1] else "is not a palindrome"
# render result
print("Your sentence {}".format(verdict))
def sterilize(string):
# define value to be removed
forbidden = "!@#$%^&*()_-+={[}]|\\:;'<,>.?/ "
for char in string:
if char in forbidden:
string = string.replace(char, "")
# return lowercased string
return string.lower()
main()
| true
|
4872a55bfbdc17106db2640bbbf988bdab42ee65
|
fadhilahm/edx
|
/NYUxFCSPRG1/codes/week4-branching_statements/lectures/24_to_12.py
| 492
| 4.21875
| 4
|
print("Please enter a time in a 24-hour format:")
hours24 = int(input("Hour: "))
minutes24 = int(input("Minute: "))
condition1 = hours24 // 12 == 0
condition2 = hours24 == 0 or hours24 == 12
time_cycle = "AM" if condition1 else "PM"
hours12 = 12 if condition2 else (hours24 if condition1 else hours24 % 12)
print("{hours24}:{minutes24} is {hours12}:{minutes24} {time_cycle}".format(
hours24 = hours24,
minutes24 = minutes24,
hours12 = hours12,
time_cycle = time_cycle
))
| false
|
c90774a80721049b89b00f43f9bab31a1ed7285e
|
Jason-Cee/python-libraries
|
/age.py
| 879
| 4.1875
| 4
|
# Python Libraries
# Calculating Age
from datetime import datetime
year_born = int(input("Enter year born: "))
month_born = int(input("Enter your month born: "))
day_born = int(input("Enter your day born: "))
current_year = int(datetime.today().strftime("%Y"))
current_month = int(datetime.today().strftime("%m"))
current_day = int(datetime.today().strftime("%d"))
age = current_year - year_born - 1
if month_born < current_month:
age += 1
elif current_month == month_born:
if current_day >= day_born:
age += 1
print(age)
# current time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time = ", current_time)
# Task
import datetime
now = datetime.datetime.today()
print(now.year)
print(now.month)
print(now.day)
print(now.date())
myDate = now.date()
for i in range(14, 140, 14):
print(myDate)
| false
|
d77058bbe4637423834c5f59e905f21721e16674
|
DiksonSantos/Bozon_Treinamentos_Python
|
/Aula_31_Modulos_Criando e Importando.py
| 966
| 4.125
| 4
|
# Modulo com funções variadas
#Função que exibe mensagem de boas vindas:
def mensagem ():
print('Ralando pra sair dessa vida!\n')
# Função para calculo de fatorial de um numero:
def fatorial(numero):
if numero < 0:
return 'Digite um valor maior ou igual a Zero'
else:
if numero ==0 or numero ==1:
return
else:
return numero * fatorial(numero =1)
# Função para Retornar uma série Sequencia de Fibonacci até um valor X :
def fibo(n):
resultado = [0]
a, b= 0, 1
while b < n:
resultado.append(b)
a, b = b, a+b
return resultado
#Modulo Principal
#import modfunções # Este Bózon não explicou como declarar QUEM é o MODFUNÇÕES !!
modfunções.mensagem()
numero = int(input('Digite Um Numero Inteiro:'))
print('Calculando o Fatorial do Número: ')
fat = modfunções.fatorial(numero)
print('O Fatorial é: ',fat)
print('Calculando a Sequencia de Fibonacci: ')
fib = modfunções.fibo(numero)
print('O Fibonacci é: ', fib)
| false
|
264e9468222fb4e6674410eab08618580ed09cf4
|
jeonghaejun/01.python
|
/ch08/ex04_리스트 관리 삽입.py
| 743
| 4.1875
| 4
|
# .append(값)
# 리스트의 끝에 값을 추가
# .insert(위치, 값)
# 지정한 위치에 값을 삽입
nums = [1, 2, 3, 4]
nums.append(5)
print(nums) # [1, 2, 3, 4, 5]
nums.insert(2, 99)
print(nums) # [1, 2, 99, 3, 4, 5]
nums = [1, 2, 3, 4]
nums[2:2] = [90, 91, 92] # 새로운 값들을 삽입 슬라이싱
print(nums) # [1, 2, 90, 91, 92, 3, 4]
nums = [1, 2, 3, 4]
nums[2] = [90, 91, 92] # 지정한 위치의 엘리먼트에 리스트 대체 인덱싱
print(nums) # [1, 2, [90, 91, 92], 4]
list1 = [1, 2, 3, 4, 5]
list2 = [10, 11]
list3 = list1 + list2 # 새로운 리스트를 리턴
print(list3) # [1, 2, 3, 4, 5, 10, 11]
list1.extend(list2) # 기존 리스트를 확장
print(list1) # [1, 2, 3, 4, 5, 10, 11]
| false
|
cd1f058045cc9414ca8d8f2d5ed0e7f0d4ef231d
|
suiody/Algorithms-and-Data-Structures
|
/Data Structures/Circular Linked List.py
| 1,248
| 4.125
| 4
|
"""
* Author: Mohamed Marzouk
* --------------------------------------
* Circular Linked List [Singly Circular]
* --------------------------------------
* Time Complixty:
* Search: O(N)
* Insert at Head/Tail: O(1)
* Insert at Pos: O(N)
* Deletion Head/Tail: O(1)
* Deletion [middle / pos]: O(N)
* Space Complixty: O(N)
* Used Language: Python
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = self.tail = Node(None)
self.tail.next = self.head
self.head.next = self.tail
def add(self, data):
newNode = Node(data)
if self.head.data is not None:
self.tail.next = newNode
self.tail = newNode
newNode.next = self.head
else:
self.head = self.tail = newNode
newNode.next = self.head
def display(self):
current = self.head
if self.head is None:
print("List is empty")
return;
else:
print("Nodes of the circular linked list: ");
print(current.data)
while(current.next != self.head):
current = current.next;
print(current.data)
cllist = CircularLinkedList()
cllist.add(5)
cllist.add(2)
cllist.add(1)
cllist.add(3)
cllist.display()
| true
|
16c3c7b2302a7fd892b67a00b09d41e058a3cff5
|
sula678/python-note
|
/basic/if-elif-else.py
| 233
| 4.125
| 4
|
if 3 > 5:
print "Oh! 3 is bigger than 5!"
elif 4 > 5:
print "Oh! 4 is bigger than 5!"
elif 5 > 5:
print "Oh! 5 is bigger than 5!"
elif 6 > 5:
print "Of course, 6 is bigger than 5!"
else:
print "There is no case!"
| true
|
e707b084c1932e484b5023eae4052fc606332c3c
|
mreboland/pythonListsLooped
|
/firstNumbers.py
| 878
| 4.78125
| 5
|
# Python's range() function makes it easy to generate a series of numbers
for value in range(1, 5):
# The below prints 1 to 4 because python starts at the first value you give it, and stops at the second value and does not include it.
print(value)
# To count to 5
for value in range(1, 6):
print(value)
# You can also pass 1 argument
for value in range(6):
print(value) # prints values 0-5
# Using range to make a list of numbers
# If you want to make a list of numbers, you can covert the results of range() directly into a list using the list() function.
numbers = list(range(1, 6))
print(numbers) # outputs [1, 2, 3, 4, 5]
# You can also use the range() function to tell python to skip numbers in a given range
# The third argument tells python to skip by 2
even_numbers = list(range(2, 11, 2))
print(even_numbers) # outputs [2, 4, 6, 8, 10]
| true
|
8a9b9a790d09aa9e7710b48b67575553224a497b
|
EvheniiTkachuk/Lessons
|
/Lesson24/task1.py
| 949
| 4.15625
| 4
|
# Write a program that reads in a sequence of characters and prints
# them in reverse order, using your implementation of Stack.
class MyStack:
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
return self.array.pop()
def peek(self):
return self.__current()
def __current(self):
return self.array[self.count() - 1]
def count(self):
return len(self.array)
def __iter__(self):
self.index = self.count() - 1
return self
def __next__(self):
if self.index < 0:
raise StopIteration()
result = self.array[self.index]
self.index -= 1
return result
if __name__ == "__main__":
string = '123456789'
stack = MyStack()
for i in string:
stack.push(i)
for i in stack:
print(i, end=' ')
| true
|
f12695405b54a25339bbd9b7098502bee4bd0d42
|
EvheniiTkachuk/Lessons
|
/Lesson13/task3.py
| 965
| 4.46875
| 4
|
# Напишите функцию под названием `choose_func`, которая принимает список из числа и 2
# функции обратного вызова. Если все числа внутри списка положительны, выполнить
# первую функцию в этом списке и вернуть ее результат. В противном случае вернуть результат второго
def square_nums(nums):
return [num ** 2 for num in nums]
def remove_negatives(nums):
return [num for num in nums if num > 0]
def choose_func(f1, f2):
def result_choice(nums):
for i in nums:
if i < 0:
return f2(nums)
return f1(nums)
return result_choice
nums1 = [1, 2, 3, 4, 5]
nums2 = [1, -2, 3, -4, 5]
test = choose_func(square_nums, remove_negatives)
print(test(nums1))
print(test(nums2))
| false
|
d69a710becdd434773d15def23dbe71e3c426b75
|
EvheniiTkachuk/Lessons
|
/Lesson24/task3_2.py
| 1,856
| 4.125
| 4
|
# Extend the Queue to include a method called get_from_stack that
# searches and returns an element e from a queue. Any other element must
# remain in the queue respecting their order. Consider the case in which the element
# is not found - raise ValueError with proper info Message
class Queue:
def __init__(self):
self._items = []
def is_empty(self):
return bool(self._items)
def enqueue(self, item):
self._items.insert(0, item)
def dequeue(self):
return self._items.pop()
def size(self):
return len(self._items)
def get_from_queue(self, item):
try:
return self._items.pop(self._items.index(item))
except (ValueError, TypeError):
print(f'\nItem "{item}" don\'t found')
def __iter__(self):
self.index = len(self._items) - 1
return self
def __next__(self):
if self.index < 0:
raise StopIteration
self.index -= 1
return self._items[self.index + 1]
def __repr__(self):
representation = "<Queue>\n"
for ind, item in enumerate(reversed(self._items), 1):
representation += f"{ind}: {str(item)}\n"
return representation
def __str__(self):
return self.__repr__()
if __name__ == "__main__":
string = '123456789'
queue = Queue()
for i in string:
queue.enqueue(i)
for i in queue: # __iter__, __next__
print(i, end=' ')
print()
print(queue)
queue.get_from_queue('9')
queue.get_from_queue('8')
queue.get_from_queue('7')
print(queue)
queue.get_from_queue('5')
queue.get_from_queue('4')
queue.get_from_queue('3')
queue.get_from_queue('2')
print(queue)
queue.get_from_queue('test')
| true
|
02ffe7089ad2b5c05246949bf9731c73130e3ebd
|
EvheniiTkachuk/Lessons
|
/Lesson24/task2.py
| 1,596
| 4.15625
| 4
|
# Write a program that reads in a sequence of characters,
# and determines whether it's parentheses, braces, and curly brackets are "balanced."
class MyStack:
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
return self.array.pop(self.count() - 1)
def peek(self):
return self.__current()
def __current(self):
return self.array[self.count() - 1]
def count(self):
return len(self.array)
def __iter__(self):
self.index = self.count() - 1
return self
def __next__(self):
if self.index < 0:
raise StopIteration()
result = self.array[self.index]
self.index -= 1
return result
def check(string: str, stack: MyStack) -> bool:
for i in string:
if i == '(' or i == '{' or i == '[':
stack.push(i)
elif i == ')' and stack.peek() == '(':
stack.pop()
elif i == ']' and stack.peek() == '[':
stack.pop()
elif i == '}' and stack.peek() == '{':
stack.pop()
return True if stack.count() == 0 else False
if __name__ == "__main__":
my_string = '{[()]}'
my_string1 = '((((((('
my_string2 = '{{{[]}}}'
my_stack = MyStack()
my_stack1 = MyStack()
my_stack2 = MyStack()
print(f'{my_string} = {check(my_string, my_stack)}')
print(f'{my_string1} = {check(my_string1, my_stack1)}')
print(f'{my_string2} = {check(my_string2, my_stack2)}')
| true
|
7191a0743560cc83b9522c6fae2f5bdffb721bc0
|
EvheniiTkachuk/Lessons
|
/Lesson5/task1.py
| 460
| 4.125
| 4
|
# #The greatest number
# Write a Python program to get the largest number from a list of random numbers with the length of 10
# Constraints: use only while loop and random module to generate numbers
from random import randint as rand
s = []
i = 1
while i <= 10:
s.append(rand((10**9), (10**10) - 1))
print(f'{i}. {s[i-1]}')
i += 1
maxElem = max(s)
print(f'Max list item at position {s.index(maxElem) + 1} and has matters {max(s)}')
| true
|
55062a569b72f7a94548b73ed83539de1c57adb0
|
kookoowaa/Repository
|
/SNU/Python/BigData_Programming/170619/Programming_1.py
| 537
| 4.1875
| 4
|
print('\nWelcome to Python Programming') #Greetings
print('This is Your First Python Program\n')
print('What is your name?') #Ask for your input
name = input()
print('Hi! ' + name) #compare this with the following line
print('Hi!', name)
print('The length of your name is:')
print(len(name))
age = input ('\nWhat is your age?')
print('You will be ' + '(int(age) + 1)' + 'years old in the next year.') #Another way of asking user input
print('You will be\t', int(age) + 1, '\tyears old in the next year.')
print('Bye~~!')
| false
|
9a9f02d7d36150749820c11ad1815e1939c21fad
|
kookoowaa/Repository
|
/SNU/Python/코딩의 기술/zip 활용 (병렬).py
| 774
| 4.34375
| 4
|
### 병렬에서 루프문 보다는 zip 활용
names = ['Cecilia', 'Lise', 'Marie']
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
# 루프문 활용
for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count
print(longest_name)
print(max_letters)
# >> Cecilia
# >> 7
# 루프 enumerate 활용
for order, name in enumerate(names):
if len(name)>max_letters:
max_letters, longest_name = letters[order], name
print(longest_name)
print(max_letters)
# >> Cecilia
# >> 7
# zip 활용
for name, length in zip(names, letters):
if length > max_letters:
max_letters, longest_name = length, name
print(longest_name)
print(max_letters)
# >> Cecilia
# >> 7
| true
|
fb57296132ee3c28d5940f746bbc1496e566c946
|
nidhi988/THE-SPARK-FOUNDATION
|
/task3.py
| 2,329
| 4.34375
| 4
|
#!/usr/bin/env python
# coding: utf-8
# # Task 3: Predicting optimum number of clusters and representing it visually.
# ## Author: Nidhi Lohani
# We are using Kmeans clustering algorithm to get clusters. This is unsupervised algorithm. K defines the number of pre defined clusters that need to be created in the process. This is done by elbow method, which is based on concept of wcss (within cluster sum of squares).
# In[1]:
# Importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
#To display maximum columns of dataframe
pd.pandas.set_option('display.max_columns',None)
# ## Loading dataset
# In[3]:
data=pd.read_csv('C:\\Users\\LOHANI\\Desktop\\Iris2.csv')
print("Data imported")
# In[4]:
print(data.shape)
# In[5]:
data.head()
# ## Extracting Independent variables
# In[6]:
X=data.iloc[:,[0,1,2,3]].values
# ## finding optimum value of k
# In[10]:
from sklearn.cluster import KMeans
wcss=[]
for i in range(1,11):
Kmeans=KMeans(n_clusters=i,init='k-means++',max_iter=300,n_init=10,random_state=0)
Kmeans.fit(X)
wcss.append(Kmeans.inertia_)
#plotting the results into line graph
plt.plot(range(1,11),wcss)
plt.title("Elbow method")
plt.xlabel("No of clusters")
plt.ylabel("WCSS")
plt.show()
# ## Using dendogram to find optimal no of clusters.
# ## Hierarchical clustering
# In[12]:
import scipy.cluster.hierarchy as sch
dendrogram=sch.dendrogram(sch.linkage(X,method='ward'))
plt.title("Dendrogram")
plt.xlabel("Species")
plt.ylabel("Euclidean Distance")
plt.show()
# optimum clusters will be cluster after which wcss remains almost constant. From above two graphs, optimum no of clusters is 3.
# ## creating kmeans classifier
# In[13]:
kmeans=KMeans(n_clusters=3,init='k-means++',max_iter=300,n_init=10,random_state=0)
y_kmeans=kmeans.fit_predict(X)
# ## Visualizing the clusters
# In[15]:
plt.scatter(X[y_kmeans==0,0],X[y_kmeans==0,1],s=100,c='red',label='setosa')
plt.scatter(X[y_kmeans==1,0],X[y_kmeans==1,1],s=100,c='blue',label='versicolor')
plt.scatter(X[y_kmeans==2,0],X[y_kmeans==2,1],s=100,c='green',label='virginica')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=100,c='yellow',label='centroids')
plt.legend()
# In[ ]:
| true
|
65d2ba3d984567002d83f04bbf0fa42ded16a5bb
|
dineshneela/class-98
|
/file.py
| 678
| 4.125
| 4
|
# program to read and open a file.
#>>> f= open("test.txt")
#>>> f.read()
#'test filllles'
#>>> f= open("test.txt")
#>>> filelines=f.readlines()
#>>> for line in filelines:
#... print(line)
#...
#test filllles. somettttthing else
# program to split the words in a string.
#>>> introstring="my name is Dinesh,I am 13 years old"
#>>> words=introstring.split()
#>>> print(words)
#['my', 'name', 'is', 'Dinesh,I', 'am', '13', 'years', 'old']
#>>> words=introstring.split(",")
#>>> print(words)
#['my name is Dinesh', 'I am 13 years old']
# how to write a function in python
#def Greet(name):
# print("Hello "+ name+"How are you")
#Greet("Dinesh")
| true
|
1a7c48054418adef604c72fa24c62904e6a41525
|
Oli-4ction/pythonprojects
|
/dectobinconv.py
| 556
| 4.15625
| 4
|
"""*************************
Decimal to binary converter
*************************"""
#function
def function():
#intialize variables
number = 0
intermediateResult = 0
remainder = []
number = int(input("Enter your decimal number: "))
base = int(input("Choose the number format: "))
#loops
while number != 0:
remainder.append(number % base)
number = number // base
remainder.reverse()
for result in remainder:
print(result, end = "")
#output
function()
| true
|
cd0e31fec220f4c3e9a04262de709ed86c91e37f
|
posguy99/comp644-fall2020
|
/L3-12.py
| 270
| 4.125
| 4
|
# Create a while loop that will repetitively ask for a number.
# If the number entered is 9999 stop the loop.
while True:
answer = int(input('Enter a number, 9999 to end: '))
if answer == 9999:
break
else:
print('Your number was: ', answer)
| true
|
5da4e0552096abe360fcab61e2cf883924fa8baf
|
posguy99/comp644-fall2020
|
/L5-13.py
| 378
| 4.125
| 4
|
# python lab 5 10-6-20
# l5_13 shallow copy of a list, the id() are the same indicating
# that they are both pointers to the same list object
the_list = ['Apples', 'Pears', 'Oranges', 'Mangoes', 'Tomatoes']
print('the_list: ', the_list)
the_new_list = the_list
print('the_new_list: ', the_new_list)
print('the_list', id(the_list))
print('the__new_list', id(the_new_list))
| false
|
266855d66e3b769f19350e5fa22af81c7b367811
|
stfuanu/Python
|
/basic/facto.py
| 268
| 4.125
| 4
|
num = input("Enter a number: ")
num = int(num)
x = 1
if num < 0:
print("Factorial doesn't exist for -ve numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1,num + 1):
x = x*i
print("Factorial of",num,"is",x)
| true
|
3ab084579276659c14fca1a6421903dc47227b27
|
jrngpar/PracticePython
|
/15 reverse word order.py
| 1,273
| 4.28125
| 4
|
#reverse word order
#ask for a long string with multiple words
#print it back with the words in backwards order
#remove spaces? Maybe print back with words in reverse
#2 functions, one to reverse order of words, one to reverse letters in words?
#Can call both functions to reverse order and letters if wanted
def reverse_words(sentence_in):
swapped = sentence_in.split(" ")
swapped = " ".join(reversed(swapped))
return swapped
def get_sentence():
user_sentence = input("What would you like reversed:\n")
return user_sentence
#print(reverse_words(get_sentence()))
def reverse_sentence(s):
backwards = s[::-1]
return backwards
#print(reverse_sentence(get_sentence()))
def other_reverse(s):
backwards = "".join(reversed(s))
return backwards
def sentence_editor():
user_sentence = input("Would you like to edit a sentence or quit(type 'quit')?")
while user_sentence != "quit":
my_sentence = input("Enter your sentence:")
which_mod = input("Reverse words(1)\nReverse letters in words(2)\nReverse entire sentence(3)\n")
if which_mod == "1":
print(reverse_words(my_sentence))
break
elif which_mod =="2":
print(reverse_words(other_reverse(my_sentence)))
break
else:
print(reverse_sentence(my_sentence))
break
sentence_editor()
| true
|
1341c50fd7e58931c55c79478479d0b29deb0787
|
MrazTevin/100-days-of-Python-Challenges
|
/SolveQuiz1.py
| 695
| 4.15625
| 4
|
# function to determine leap year in the gregorian calendar
# if a year is leap year, return Boolean true, otherwise return false
# if the year can be evenly divided by 4, it's a leap year, unless: The year can be evenly divided by 100 it is# not a leap year,unless the year is also divisible by 400, then its a leap year
# In the Gregorian Calendar, years 2000 and 2400 are leap years, while 1800,1900,2100,2200,2300 and 2500 are not leap years
def leap_year(year):
if (year%4==0 and year%100!=0):
return True
elif (year%100==0 and year%400==0):
return True
else:
return False
yearInput = int(input("Enter any year i.e 2001 :"))
print(leap_year(yearInput))
| true
|
82573c7abbdd044e489e75c4b53f7840c10873ae
|
rdstroede-matc/pythonprogrammingscripts
|
/week5-files.py
| 978
| 4.28125
| 4
|
#!/usr/bin/env python3
"""
Name: Ryan Stroede
Email: rdstroede@madisoncollege.edu
Description: Week 5 Files Assignment
"""
#1
with open("/etc/passwd", "r") as hFile:
strFile = hFile.read()
print(strFile)
print("Type:",type(strFile))
print("Length:",len(strFile))
print("The len() function counts the number of characters in a file.")
print("You would use this technique if you want to print certain characters in a file.")
#2
with open("/etc/passwd", "r") as hFile:
fileList = hFile.readlines()
print(fileList)
print("Type:",type(fileList))
print("Length:",len(fileList))
print("The len() function counts each object in the list.")
print("You can use this to get a number of how many objects are in the list.")
#3
with open("/etc/passwd", "r") as hFile:
fileLine = hFile.readline()
print(fileLine)
print("Type:",type(fileLine))
print("Length:",len(fileLine))
print("You would use this technique when you want to count one line at a time.")
| true
|
1bdfad55963a5ca778fc06d402edc95abcf8fb16
|
stak21/DailyCoding
|
/codewarsCodeChallenge/5-anagram.py
| 1,300
| 4.28125
| 4
|
# Anagram
# Requirements:
# Write a function that returns a list of all the possible anagrams
# given a word and a list of words to create the anagram with
# Input:
# 'abba', ['baab', 'abcd', 'baba', 'asaa'] => ['baab, 'baba']
# Process:
# Thoughts - I would need to create every permutation of the given word and check the list for each one
# example: 'a' in ['a', 'ab', 'c'] -> true, but would 'a' in 'ab' be true too? The answer is no
# Naive approach: a possible naive approach is to sort each word and put each one in a dictionary with a list of the matching letters.
# Approach 1: change each character in different arrangements and check if that character is in the list
# Naive approach
def is_anagram(word, words):
matchings = {}
for w in words:
sorted_word = ''.join(sorted(w))
if sorted_word in matchings:
matchings[sorted_word].append(w)
else:
matchings[sorted_word] = [w]
sorted_word = ''.join(sorted(word))
return matchings.get(sorted_word, [])
tests = [('a', ['a', 'b', 'ab']), ('aba', ['aab', 'baa', 'abb']), ('ab', ['a'])]
answers = [['a'], ['aab', 'baa'], []]
for test, answer in zip(tests, answers):
res = is_anagram(test[0], test[1])
print(res, 'Success: ', res == answer)
| true
|
afc80165e3d0f02bbc8d49ce2ba2dae80092abc2
|
HarithaPS21/Luminar_Python
|
/Advanced_python/Functional_Programming/dictionary.py
| 632
| 4.125
| 4
|
employees={
1000:{"eid":1000,"ename":"ajay","salary":34000,"Designation":"developer"},
1001:{"eid":1001,"ename":"arun","salary":38000,"Designation":"developer"},
1002:{"eid":1002,"ename":"akhil","salary":21000,"Designation":"hr"},
1003:{"eid":1003,"ename":"anu","salary":45000,"Designation":"Analyst"}
}
id=int(input("enter an id ")) # input through output
if id not in employees:
print("invalid id")
else:
prop=input("enter the property you want to print: 1.ename 2.salary 3.Designation ")
if prop not in employees:
print("The property you entered doesn't exist")
else:
print(employees[id][prop])
| false
|
aaad26766dbaf3819cebe370c7f5117283fd1630
|
HarithaPS21/Luminar_Python
|
/python_fundamentals/flow_of_controls/iterating_statements/while_loop.py
| 339
| 4.15625
| 4
|
# loop - to run a block of statements repeatedly
# while loop -run a set of statements repeatedly until the condition becomes false
#Syntax
# while condition:
# code
# inc/dec operator
a=0
while a<=10:
print("hello") # prints "hello" 11 times
a+=1
print("\nwhile decrement example")
i=10
while i>0:
print(i)
i-=1
| true
|
85b7319bc24340a96ce0e3a97791d6eee2643c32
|
Syconia/Harrow-CS13
|
/Stacks.py
| 1,611
| 4.125
| 4
|
# Stack class
class Stack():
# Put in a list and set a limit. If limit is less than 0, it's basically infinitely large
def __init__(self, List, INTlimit):
self.Values = List
if INTlimit < 0:
INTlimit = 99999
self.Limit = INTlimit
# Set up pointer. It's set by list index so start from 0. If empty, it's false
if self.Values == []:
self.Pointer = False
else:
self.Pointer = len(List)-1
# If pointer exists, then check if it's over the limit
if self.Pointer != False:
if self.Limit < self.Pointer + 1:
raise IndexError
# Add item to top of stack
def push(self, item):
# Check to see if it's over the limit
if self.Pointer + 2 > self.Limit:
raise IndexError
# Check to see if it's at top of list
try:
# If not, then change next value to item
self.Values[self.Pointer + 1] = item
except IndexError:
# else, add new value
self.Values.append(item)
# Pointer update
if self.Pointer == False:
self.Pointer = 0
else:
self.Pointer += 1
# Return top item, do not delete
def pop(self):
returnValue = self.Values[self.Pointer]
# Update pointer
self.Pointer -= 1
return returnValue
# Empty the stack, reset the pointer
def emptyStack(self):
self.Values = []
self.Pointer = False
# For convenient printing
def __str__(self):
return str(self.Values)
| true
|
c353be9014cb341a5a04e1f55ef53661f88175ef
|
JoshTheBlack/Project-Euler-Solutions
|
/075.py
| 1,584
| 4.125
| 4
|
# coding=utf-8
'''It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed?'''
from comm import timed
DEBUG = False
@timed
def p075(max):
def driver():
from typing import DefaultDict
from math import gcd
limit = int((max/2)**0.5)
triangles = DefaultDict(int)
result = 0
for m in range(2,limit):
for n in range(1,m):
if ((n+m) % 2) == 1 and gcd(n, m) == 1:
a = m**2 + n**2
b = m**2 - n**2
c = 2*m*n
p = a + b + c
while p < max:
triangles[p] += 1
if triangles[p] == 1: result += 1
if triangles[p] == 2: result -= 1
p += a+b+c
return result
return driver()
if __name__ == "__main__":
print(p075(1_500_000))
| true
|
c8509d347b9d8dce353f1e40f9ba2a1c4d3df4f2
|
RaviC19/Dictionaries_Python
|
/more_methods.py
| 625
| 4.375
| 4
|
# pop - removes the key-value pair from the dictionary that matches the key you enter
d = dict(a=1, b=2, c=3)
d.pop("a")
print(d) # {'b': 2, 'c': 3}
# popitem - removes and returns the last element (key, value) pair in a dictionary
e = dict(a=1, b=2, c=3, d=4, e=5)
e.popitem()
print(e) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# update - updates keys and values in a dictionary with another set of key value pairs
user = {
"name": "Ravi",
"location": "UK",
"age": 30
}
person = {"language": "Python"}
person.update(user)
print(person)
# returns {'language': 'Python', 'name': 'Ravi', 'location': 'UK', 'age': 30}
| true
|
44291c2c7fe818202a9d424139eba73e90dfd5ce
|
Jwbeiisk/daily-coding-problem
|
/mar-2021/Mar15.py
| 1,643
| 4.4375
| 4
|
#!/usr/bin/env python3
"""
15th Mar 2021. #558: Medium
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x^2 + y^2 = r^2.
"""
"""
Solution: We sample random points that would appear in the first quadrant of the coordinate axes. The points lie
between 0 and 1 and may lie inside a circle of radius 1 with its origin at (0, 0) if it satisfies the condition x^2 +
y^2 <= 1^2 (or r^2). If we have sampled enough of the quarter of the circle uniformly, the ratio of points inside the
circle and total samples is pi/4. We multiply this by 4 to get an approximate pi.
https://en.wikipedia.org/wiki/Monte_Carlo_method
"""
from random import random, seed
SAMPLES = 999
def monte_carlo_pi():
prev = 0
pi = 3
total_valid_points = 0
total_points = 0
# The approximation of pi stays the same for over a couple estimations
while abs(prev - pi) > 1e-6:
# Get SAMPLES number of random points with x, y in range(0, 1)
for _ in range(SAMPLES):
# Check if random point lies inside a circle of radius 1 with its centre at origin
if random() ** 2 + random() ** 2 <= 1:
total_valid_points += 1
total_points += 1
prev = pi
# New estimation is 4 * (pi/4)
pi = float(4 * total_valid_points) / float(total_points)
# Return result to 3 decimal places
return '{0:.3f}'.format(pi)
def main():
print(monte_carlo_pi()) # Prints 3.142
return
if __name__ == "__main__":
main()
| true
|
f2c376ba14e0c328cc64f9985d080d4968a57431
|
Jwbeiisk/daily-coding-problem
|
/mar-2021/Mar10.py
| 1,667
| 4.5
| 4
|
#!/usr/bin/env python3
"""
10th Mar 2021. #553: Medium
This problem was asked by Google.
You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to
ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is
lexicographically later as you go down each row. It does not matter whether each row itself is ordered
lexicographically.
For example, given the following table:
cba
daf
ghi
This is not ordered because of the a in the center. We can remove the second column to make it ordered:
ca
df
gi
So your function should return 1, since we only needed to remove 1 column.
As another example, given the following table:
abcdef
Your function should return 0, since the rows are already ordered (there's only one row).
As another example, given the following table:
zyx
wvu
tsr
Your function should return 3, since we would need to remove all the columns to order it.
"""
"""
Solution: Self-explanatory.
"""
def col_del(arr):
count = 0
for i in range(len(arr[0])):
char = 'a'
for row in arr:
if ord(row[i]) < ord(char):
count += 1
break
char = row[i]
return count
def main():
arr1 = [
'cba',
'daf',
'ghi'
]
arr2 = ['abcdef']
arr3 = [
'zyx',
'wvu',
'tsr'
]
print(col_del(arr1)) # Prints 1
print(col_del(arr2)) # Prints 0
print(col_del(arr3)) # Prints 3
return
if __name__ == "__main__":
main()
| true
|
14b70002c95cdd503190e523f840b543a272f481
|
Jwbeiisk/daily-coding-problem
|
/feb-2021/Feb17.py
| 1,784
| 4.40625
| 4
|
#!/usr/bin/env python3
"""
17th Feb 2021. #532: Medium
This problem was asked by Google.
On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that
have another bishop located between them, i.e. bishops can attack through pieces.
You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the
number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered the
same as (2, 1).
For example, given M = 5 and the list of bishops:
(0, 0)
(1, 2)
(2, 2)
(4, 0)
The board would look like this:
[b 0 0 0 0]
[0 0 b 0 0]
[0 0 b 0 0]
[0 0 0 0 0]
[b 0 0 0 0]
You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4.
"""
"""
Solution: The diagonals on a chessboard would have coordinates along a line that has the characteristic of always
being the same number of steps down as it is across. For example, from (2, 2) to (4, 0) we have to go 2 steps left and
2 steps down. Thus we simply calculate the number of coordinate pairs where the difference in x or y coordinate values
is the same (regardless of sign).
"""
def bishop_kills(bishops):
kills = 0
for i in range(len(bishops)):
# Look for every bishop after the selected one
for j in range(min(i + 1, len(bishops)), len(bishops)):
if abs(bishops[i][0] - bishops[j][0]) == abs(bishops[i][1] - bishops[j][1]):
kills += 1
return kills
def main():
bishops = [(0, 0),
(1, 2),
(2, 2),
(4, 0)]
print(bishop_kills(bishops)) # Prints 2
return
if __name__ == "__main__":
main()
| true
|
f98b5090fbc532098ebbcd8026efae383bfcc507
|
Jwbeiisk/daily-coding-problem
|
/jan-2021/Jan30.py
| 1,092
| 4.34375
| 4
|
#!/usr/bin/env python3
"""
30th Jan 2021. #514: Medium
This problem was asked by Microsoft.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its
length: 4.
Your algorithm should run in O(n) complexity.
"""
"""
Solution: Nothing too fancy. We use hashing to convert a solution that would usually run in O(nlogn) time and O(1)
space to O(n) time and space. We use a set here, and search for consecutive elements, which is faster than first
ordering a list and then looping through for sequences.
"""
def longest_sequence(arr):
count = 0
s = set(arr)
for i in range(len(arr)):
if arr[i] - 1 not in s:
j = arr[i]
while j in s:
j += 1
count = max(count, j - arr[i])
return count
def main():
arr = [100, 4, 200, 1, 3, 2]
print(longest_sequence(arr)) # Returns 4 (for [1, 2, 3, 4])
return
if __name__ == "__main__":
main()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.