blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f2b06363eb7bf486e5d397ffbf4c68f88ba6c5bc | Xiangyaojun/Algorithms | /栈和队列/用栈实现队列.py | 1,886 | 4.125 | 4 | # coding:utf-8
'''
leetcode 224
题目:使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
'''
class MyQueue:
def __init__(self):
self.stack_1 = []
self.stack_2 = []
def push(self, x):
while len(self.stack_2)>0:
temp = self.stack_2.pop(-1)
self.stack_1.append(temp)
self.stack_1.append(x)
def pop(self):
while len(self.stack_1) > 0:
temp = self.stack_1.pop(-1)
self.stack_2.append(temp)
return self.stack_2.pop()
def peek(self):
while len(self.stack_1) > 0:
temp = self.stack_1.pop(-1)
self.stack_2.append(temp)
result = self.stack_2[-1]
while len(self.stack_2) >0:
temp = self.stack_2.pop(-1)
self.stack_1.append(temp)
return result
def empty(self):
if len(self.stack_1)==0 and len(self.stack_2)==0:
return True
else:
return False
# Your MyQueue object will be instantiated and called as such:
obj = MyQueue()
obj.push(1)
obj.push(2)
obj.push(3)
print(obj.pop())
print(obj.pop())
print(obj.pop())
| false |
8678b04cd9e28847b30d4b8ec7fe3f9aaddc1708 | rohan8594/DS-Algos | /leetcode/medium/Arrays and Strings/ReverseWordsInAString.py | 1,076 | 4.3125 | 4 | # Given an input string, reverse the string word by word.
# Example 1:
# Input: "the sky is blue"
# Output: "blue is sky the"
# Example 2:
# Input: " hello world! "
# Output: "world! hello"
# Example 3:
# Input: "a good example"
# Output: "example good a"
# Note:
# A word is defined as a sequence of non-space characters.
# Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
# You need to reduce multiple spaces between two words to a single space in the reversed string.
class Solution:
def reverseWords(self, s: str) -> str:
strArr = []
curWord, res = "", ""
# strArr = s.split(" ")
for char in s:
if char == " ":
strArr.append(curWord)
curWord = ""
continue
curWord += char
strArr.append(curWord)
for i in range(len(strArr) - 1, -1, -1):
if strArr[i] == "":
continue
res += strArr[i] + " "
return res[:-1]
| true |
634119cf7cb1a5d461e0a320ac79151f217e00fd | rohan8594/DS-Algos | /leetcode/easy/Arrays and Strings/UniqueCharachters.py | 476 | 4.25 | 4 | # Given a string,determine if it is comprised of all unique characters. For example,
# the string 'abcde' has all unique characters and should return True. The string 'aabcde'
# contains duplicate characters and should return false.
def uniqueChars(s):
seen = set()
for i in range(len(s)):
if s[i] not in seen:
seen.add(s[i])
else:
return False
return True
print(uniqueChars("abcdefg"))
print(uniqueChars("abcdefgg"))
| true |
bce31c7854e9835b1a697eb2a0604d78664c0bda | mrDurandall/Python-Basics-Course | /Lesson_3/Lesson-3_HW_Task-1.py | 1,184 | 4.125 | 4 | # Задание 1 - Функция деления.
print('Задание 4 - Функция деления.')
def divide():
"""Функция деления двух чисел
для вводимых чисел используется формат float,
т.к. пользователь может ввести не только целые числа.
также при вводе каждого числа проверям,
точно ли пользователь ввел числа, а не другой текст.
Если введено не число, то сообщаем об этом и прекращаем выполнение."""
try:
num1 = float(input('Введите делимое: '))
except ValueError:
print('Вы ввели не число')
return
try:
num2 = float(input('Введите делитель: '))
except ValueError:
print('Вы ввели не число')
return
try:
print(f'{num1} / {num2} = {num1 / num2}')
return num1 / num2
except ZeroDivisionError:
print('Делить на ноль нельзя!')
print(divide()) | false |
a2510d4c072bbae473cee9ea22e27c081bd97a4c | MVGasior/Udemy_training | /We_Wy/reading_input.py | 1,536 | 4.3125 | 4 | # This program is a 1# lesson of In_Ou Udemy
# Author: Mateusz Gąsior
# filename = input("Enter filename: ")
# print("The file name is: %s" % filename)
file_size = int(input("Enter the max file size (MB): "))
print("The max size is %d" % file_size)
print("Size in KB is %d" % (file_size * 1024))
print("-------------------------------------------------------")
def check_int(s):
"""
This function checking if number is int
:param s:number to check
:return:True or False
"""
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
input_a = input("Please insert parameter a of quadratic equation: ")
input_b = input("Please insert parameter b of quadratic equation: ")
input_c = input("Please insert parameter c of quadratic equation: ")
if not check_int(input_a) or not check_int(input_b) or not check_int(input_c):
print("The inserted values are not correct")
else:
a = int(input_a)
b = int(input_b)
c = int(input_c)
if a == 0:
print("This is not a quadratic equation !!!")
else:
delta = b ** 2 - 4 * a * c
if delta < 0:
print("The is no solution of that quadratic equation.")
elif delta == 0:
x1 = (- b - delta ** 0.5) / (2 * a)
print("The only one zero point is: ", x1)
else:
x1 = (- b - delta ** 0.5) / (2 * a)
x2 = (- b + delta ** 0.5) / (2 * a)
print("The zero points are: ", x1, x2)
| true |
e8967361e05174dcd4cd64751213ecf91ce88814 | pynic-dot/Python-code-practice | /Objects and Data Structures Assessment Test.py | 955 | 4.28125 | 4 | # Print out 'e' using indexing
s = 'Hello'
print(s[1])
# Reverse the string
print(s[::-1])
# Two method to produce letter 'o'
print(s[4])
print(s[-1])
# Lists Build list [0,0,0] in two different way
s = []
for i in range(3):
s.append(0)
print(s)
print([0, 0, 0])
print([0]*3)
# Reassign 'hello' in this nested list to say 'goodbye' instead:
list_1 = [1, 2, [3, 4, 'Hello']]
list_1[2][2] = 'Hello Goodbye'
print(list_1)
# Sort the list
list_4 = [5, 3, 4, 6, 1]
print(sorted(list_4))
# Dictionary
dit = {'simple_key': 'Hello0'}
print(dit['simple_key'])
dit = {'k1': {'k2': 'hello1'}}
print(dit['k1']['k2'])
dit = {'k1': [{'nest_key': ['this is deep', ['Hello2']]}]}
print(dit['k1'][0]['nest_key'][1][0])
dit = {'k1': [1, 2, {'k2': ['this is tricky', {'tough': [1, 2, ['hello3']]}]}]}
print(dit['k1'][2]['k2'][1]['tough'][2][0])
# There are two nested loop
list1 = [1, 2, [3, 4]]
list2 = [1, 2, {'k1': 4}]
print(list1[2][0] <= list2[2]['k1'])
| false |
c6fd9774176663a75853ab33bd9ac42c5573f65f | ursu1964/Libro2-python | /Cap2/Programa 2_9.py | 1,576 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Problema 2.9
"""
def aparece_dos_veces(palabra):
""" Determina si todas las letras de la palabra están exactamente 2 veces.
Parámetro:
palabra: de tipo str.
Regresa:
True si la palabra cumple la condición y False en caso contrario.
"""
n = len(palabra)
# Debe tener, por lo menos, dos caracteres y un número par de
# caracteres para poder cumplir con la propiedad que se pide.
if n > 1 and n % 2 == 0:
primera = set()
segunda = set()
indice = 0
resp = True
while indice < n and resp:
letra = palabra[indice]
if letra not in primera:
primera.add(letra)
else:
if letra not in segunda:
segunda.add(letra)
else:
resp = False # Está más de 2 veces.
indice += 1
resp = resp and len(primera) == len(segunda)
else:
resp = False
return resp
# Algunas pruebas de la función.
print('\nCP1: la palabra "papa" -->', aparece_dos_veces('papa'))
print('CP2: la palabra "nenes" -->', aparece_dos_veces('nenes'))
print('CP3: la palabra "detergente" -->', aparece_dos_veces('detergente'))
print('CP4: la palabra "tratar" -->', aparece_dos_veces('tratar'))
# Se quitó el acento a termómetro.
print('CP5: la palabra "termometro" -->', aparece_dos_veces('termometro'))
print('CP6: una cadena vacía -->', aparece_dos_veces(''))
| false |
7af831e19af6f8fd26a5e83ae00c391ff9bfcd15 | ursu1964/Libro2-python | /Cap1/Ejemplo 1_2.py | 1,392 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Ejemplo 1_2
Operaciones con listas.
"""
dias_laborables = ["lunes", "martes", "miércoles", "jueves", "viernes"]
colores_primarios = ['rojo', 'verde', 'azul']
precios = [205.30, 107.18, 25, 450, 310.89, 170.23, 340]
# =============================================================================
# Acceso a los elementos de las listas.
# =============================================================================
print('\nPrimer elemento:', dias_laborables[0]) # Imprime 'lunes'.
print('Último elemento:', dias_laborables[-1]) # Imprime 'viernes'.
print('Último desde la derecha:', dias_laborables[-5]) # Imprime 'lunes'.
# print(dias_laborables[-100]) # IndexError: list index out of range
# =============================================================================
# Ejemplos de uso de los operadores + y *.
# =============================================================================
fin_semana = ['sábado', 'domingo']
# Concatena las listas en el orden dado.
semana = fin_semana + dias_laborables
# Repite los elementos. El número debe ser un entero.
colores_repetidos = colores_primarios * 2
# TypeError: can't multiply sequence by non-int of type 'float'
# precios_repetidos = precios * 3.5
print('\nListas concatenadas:', semana)
print('Elementos repetidos:', colores_repetidos)
| false |
d1af7d34089b172801b7bef550955595791f2422 | yujie-hao/python_basics | /datatypes/type_conversion_and_casting.py | 1,689 | 4.75 | 5 | # ==================================================
"""
https://www.programiz.com/python-programming/type-conversion-and-casting
Key Points to Remember
1. Type Conversion is the conversion of object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.
"""
# ==================================================
# implicit Type Conversion: Implicit Type Conversion is automatically performed by the Python interpreter.
# 1. Converting integer to float: implicit conversion
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int: ", type(num_int))
print("datatype of num_flo: ", type(num_flo))
print("datatype of num_new: ", type(num_new))
print("datatype of num_new: ", type(num_new))
# 2. Addition of string data type and integer datatype --> TypeError
num_int = 123
num_str = "456"
# num_new = num_int + num_str # TypeError: unsupported operand type(s) for +: 'int' and 'str'
# print("Data type of num_new: ", type(num_new))
# print("num_new = ", num_new)
# ==================================================
# Explicit type conversion: <type>(), a.k.a: Type Casting
num_int = 123
num_str = "456"
num_str = int(num_str)
print("Data type of num_str after type casting: ", type(num_str))
num_sum = num_int + num_str
print("Data type of num_sum: ", type(num_sum), ", value: ", num_sum)
| true |
1eb815e71e54a98630a1c89715a1a59edabaf461 | yujie-hao/python_basics | /objects/class_and_object.py | 2,060 | 4.53125 | 5 | # A class is a blueprint for the object
class Parrot:
# docstring: a brief description about the class.
"""This is a Parrot class"""
# class attribute
species = "bird"
# constructor
def __init__(self, name, age):
# instance attribute
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
print("Parrot.__doc__: {}".format(Parrot.__doc__))
print("species: " + Parrot.species)
print(Parrot.sing)
# An object (instance) is an instantiation of a class
blueParrot = Parrot("Blue", 10)
greenParrot = Parrot("Green", 5)
# access the class attributes
print("Blue parrot is a {}".format(blueParrot.__class__.species))
print("Green parrot is a {}".format(greenParrot.__class__.species))
# access the instance attributes
print("{} is {} years old".format(blueParrot.name, blueParrot.age))
print("{} is {} years old".format(greenParrot.name, greenParrot.age))
# call instance methods
print(blueParrot.sing("'Happy'"))
print(blueParrot.dance())
print(blueParrot.dance)
# Constructors
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
# Create a new ComplexNumber object
num1 = ComplexNumber(2, 3)
# Call get_data() method
num1.get_data()
# Create another ComplexNumber object
# and create a new attribute 'attr'
num2 = ComplexNumber(5)
num2.attr = 10
print(num2.real, num2.imag, num2.attr)
# print(num1.attr) # AttributeError: 'ComplexNumber' object has no attribute 'attr'
# delete attributes and objects
num1.get_data()
del num1.imag
# num1.get_data() # AttributeError: 'ComplexNumber' object has no attribute 'imag'
num2.get_data()
del ComplexNumber.get_data
# num2.get_data() # AttributeError: 'ComplexNumber' object has no attribute 'get_data'
c1 = ComplexNumber(1, 3)
del c1
# c1.get_data() # NameError: name 'c1' is not defined
| true |
48fd47973debe27fdf06e7d9335a92e5a5e7eb4e | DagmarMpheio/ExercicioComListasPython | /ExerciciosListas10.py | 387 | 4.125 | 4 | #Faa um programa que crie uma matriz aleatoriamente. O tamanho da matriz deve ser informado pelo usurio.
import random
print("\t\t Matriz")
mat=[]
lin=int(input("Digite o numero de linhas: "))
col=int(input("Digite o numero de colunas: "))
for i in range(lin):
val=[]
for j in range(col):
val.append(random.randint(-100,100))
mat.append(val)
print(mat) | false |
867fcce1d6992bf8108ff0f7232acce9dcbefd3d | rozmeloz/PY | /dz2/task4-1.py | 591 | 4.34375 | 4 | """
1. Запросить у пользователя его возраст и определить, кем он является:
ребенком (0–2), подростком (12–18), взрослым (18_60) или пенсионером (60– ...).
"""
W = int(input('Введите Ваш возвраст:'))
if W < 12:
print ('Ребенок')
elif 12 <= W <=18:
print ('Подросток')
elif 18 < W < 60:
print ("Взрослый")
elif W >= 60:
print ('Пенсионер')
else:
print('ошибка')
input ('Нажмите Enter для выхода')
| false |
efbc69732c249969b406b3a7071010c998d59297 | SandyHoffmann/ListasPythonAlgoritmos | /Lista 3/SH-PCRG-AER-Alg-03-Ex-05.py | 1,054 | 4.15625 | 4 | #Pedindo mês e fazendo com q ele sempre fique no formato minusculo.
mes = input("Qual o mês? ").lower()
#Checando os meses para printar o tanto de dias.
if mes == "janeiro":
print(f'O mês de {mes} tem 31 dias.')
elif mes == "fevereiro":
print(f'O mês de {mes} tem 28 ou 29 dias.')
elif mes == "março":
print(f'O mês de {mes} tem 31 dias.')
elif mes == "abril":
print(f'O mês de {mes} tem 30 dias.')
elif mes == "maio":
print(f'O mês de {mes} tem 31 dias.')
elif mes == "junho":
print(f'O mês de {mes} tem 30 dias.')
elif mes == "julho":
print(f'O mês de {mes} tem 31 dias.')
elif mes == "agosto":
print(f'O mês de {mes} tem 31 dias.')
elif mes == "setembro":
print(f'O mês de {mes} tem 30 dias.')
elif mes == "outubro":
print(f'O mês de {mes} tem 31 dias.')
elif mes == "novembro":
print(f'O mês de {mes} tem 30 dias.')
elif mes == "dezembro":
print(f'O mês de {mes} tem 31 dias.')
#Se n for encontrado retorna uma mensagem de erro.
else:
print("Não foi encontrado mês com esse nome.") | false |
6a9980954beb1a423130f6eb65c83a2a4ec8a1b7 | lekakeny/Python-for-Dummies | /file_operations.py | 1,762 | 4.46875 | 4 | """
File operation involves
1. opening the file
2. read or write the file
3. close file
Here we are learning how to read and write files. I learnt how to read and write long time ago! How could I be
learning now? Anyway, kwani ni kesho?
"""
f = open('text.txt', 'w',
encoding='utf8') # open the file called text.txt if it does exist. If not the python will create one
"Read from standard input and write to the file"
"""
inputs = input('input: ') # Define the input
f.write(inputs) # write the input to the file using the write method
f.close() # close the file so that the file object may not remain in memory. Data is only written when the file closes
"""
"Read from the file we have just created"
f = open('text.txt', 'r') # r means read only
print(f.read(6)) # read 6 characters from the current position (default is 0)
print(f.read()) # read from current position to the end
f.close()
"Add more data to the file by using mode 'a'"
f = open('text.txt', 'a')
f.write(' I have just added this content to the file!')
f.close()
"Use 'with' statement to open file. File object will automatically close"
with open('text1.txt', 'w') as f:
f.write('I have learnt a new technique\n I am not very masai anymore\n call me stupid at your own risk')
# use with statement to read the file
with open('text1.txt', 'r') as f:
print("This is the file I have created: \n", f.read())
'Read the file line by line using the \'readline()\' method'
with open('text1.txt', 'r') as f:
line = f.readline()
print("read one line: %s" % line)
# use readlines to get a list of lines
lines = f.readlines() # starts from the current position
print(lines)
"Can I call this file management? I now know how to read and write in python!"
| true |
ed5cb135e00272635753e85b0a7d8d859dea1e0d | lekakeny/Python-for-Dummies | /generator_and_decorators.py | 2,132 | 4.59375 | 5 | """
Generators are functions that return a lazy iterator
lazy iterators do not store their contents in memory, unlike lists
generators generate elements/values when you iterate over it
It is lazy because it will not calculate the element until when we want to use the element
"""
"Use isinstance function to check if an object is iterable"
import collections as c
print(isinstance([], c.Iterable))
print(isinstance('a,b,c', c.Iterable))
print(isinstance(100, c.Iterable))
print(isinstance((1, 2, 3, 4, 5, 6,), c.Iterable))
"Create an iterator using iter function"
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
l_iteration = iter(l)
print("The type of iterator is: ", type(l_iteration))
"The next function provides the next element in the iterator"
print("First Value is: ", next(l_iteration))
print("Second Value is: ", next(l_iteration))
print("Third Value is: ", next(l_iteration))
print("Fourth Value is: ", next(l_iteration))
# Generators: We define how each element in the iterator is generated
"Use the example of n fibonacci numbers to learn the generators"
print("fibonacci begins here")
def fib(n):
current = 0
num1, num2 = 0, 1
while current < n:
num = num2
num1, num2 = num2, num1 + num2
current += 1
yield num # We use key word yield instead of return when building a generator
yield "Done"
g = fib(5)
for number in g:
print(number)
"A shorter way to create generators is using list comprehensions"
g = (x ** 2 for x in range(5))
print("This has been done using list comprehension")
for x in g:
print(x)
"""
Decorators
Add functionality to an existing code without modifying its structure
It is a function that returns another function. Callable object that returns another callable object
Takes in a function, add some functionality and returns it
Provides a flexible way of adding/extending the functionality of a function
"""
def decorate(decorated_function):
def decorated():
print("This is the decorated function")
decorated_function()
return decorated()
@decorate
def plain():
print("I am not decorated at all!")
plain()
| true |
8488ee8f09498521c1cc3054147370b793a35fe1 | xs2tariqrasheed/python_exercises | /integer_float.py | 722 | 4.1875 | 4 | _ = print
# NOTE: don't compare floating number with ==
# A better way to compare floating point numbers is to assume that two
# numbers are equal if the difference between them is less than ε , where ε is a
# small number.
# In practice, the numbers can be compared as follows ( ε = 10 − 9 )
# if abs(a - b) < 1e-9: # a and b are equal
# _(0.3*3+0.1)
# x = 4.66668
# _(round(x, 2))
# c = 4 + 2j # complex
# print(type(c))
# i = 9999999999999999999999999999999999
# f = 0.00000000000000000001
# print(f)
# print(45.1e-2)
# _(0.1 + 0.2) # TODO: reading https://docs.python.org/3.6/tutorial/floatingpoint.html
# _(16 ** -2 == 1 / 16 ** 2) # True
# _(17 / 3) # 5.666666666666667
# _(17 // 3) # 5
# _(17 % 3) # 2
| true |
6af88b90a7d58c79ee0e192212d0893c168bf45e | BinYuOnCa/DS-Algo | /CH2/stevenli/HW1/pycode/NumpyDemo.py | 1,454 | 4.25 | 4 | import numpy as np
# Generate some random data
data = np.random.randn(2, 3)
print("first random data: ", data)
# data * 10
data = data * 10
print("Data times 10: ", data)
# try np shape
print("Data shape: ", data.shape)
# Print data value's type
print("Data types:", data.dtype)
# Create a new ndarray
data_forarray = [6, 7.5, 8, 0, 1]
np_array = np.array(data_forarray)
print("Np array is: ", np_array)
# create a second ndarry
data_forarray2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
np_array2 = np.array(data_forarray2)
# create a 1D array
data_forarray3 = [10]
np_array3 = np.array(data_forarray3)
# Demo broadcasting, array 1 + array3
print("Broadcasting, array1 + array3: ", np_array+np_array3)
# numpy array indexing and slicing
np_array4 = np.arange(10)
print("Initialize an array in range 10: ", np_array4)
# print out the range 5:8. The 5th, 6th and 7th values will be printed out. The 8th value won't
print("The range 5:8 is: ", np_array4[5:8])
# assign a slicing
array_slice = np_array4[5:8]
array_slice[1] = 12345
print("After slicing: ", np_array4)
array_slice[:] = 64
print("Second slicing: ", np_array4)
# Create a 2 dimensional array
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("The second element of array: ", array2d[1])
print("The 3rd value of 2nd sub array: ", array2d[1][2])
# Create a 3 Dimensional array
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("The 3D array is: ", array3d)
| true |
ea4dd28662cd52fb13147661624fa28381cd0433 | dery96/challenges | /zero_name_generator.py | 909 | 4.21875 | 4 | from random import randint as RANDOM
'''
Generates Words it meant to be character name generator
'''
letters = 'abcdefghijklmnoprstuvwyz'
len_letters = len(letters) - 1
syllabes = ['mon', 'fay', 'shi', 'fag', 'blarg', 'rash', 'izen']
def Generate_Word(word_len=15, word=''):
'''This function generate Words (Random Letters) with syllabes that it
could make sense'''
word_length = RANDOM(5, word_len)
syllabe_rand = syllabes[RANDOM(0, len(syllabes) - 1)]
for i in range(0, word_length):
letter_random = letters[RANDOM(0, len_letters)]
if i == 0:
'First letter must be UPPER'
word += letter_random.upper()
if i + len(syllabe_rand) >= word_length:
word += syllabe_rand
break
if i > 0:
word = word + letter_random
return word
print 'Hello: %s %s' % (Generate_Word(6), Generate_Word(7))
| false |
416500cec0887721d8eb35ace2b89bc8d208a247 | qasimriaz002/LeranOOPFall2020 | /qasim.py | 555 | 4.34375 | 4 | from typing import List
def count_evens(values: List[List[int]]) -> List[int]:
"""Return a list of counts of even numbers in each of the inner lists
of values.
# >>> count_evens([[10, 20, 30]])
[3]
# >>> count_evens([[1, 2], [3], [4, 5, 6]])
[1, 0, 2]
"""
evenList = []
for sublist in values:
count = 0
for eachValue in sublist:
if eachValue % 2 == 0:
count = count + 1
evenList.append(count)
return evenList
x = [[1, 2], [3], [4, 5, 6]]
print(count_evens(x)) | true |
ad3a6c22485fece625f45f894962d548960b00b0 | qasimriaz002/LeranOOPFall2020 | /Labs/Lab_1/Lab_1_part_3.py | 1,323 | 4.53125 | 5 | # Here we will use the dictionaries with the list
# We will create the record of 5 students in the different 5 dictionaries
# Then we will add all of the these three dictionaries in the list containing the record of all student
# Creating the dictionaries
stdDict_1 = {"name": "Bilal", "age": 21, "rollno": "BSDS-001-2020"}
stdDict_2 = {"name": "Ahsan", "age": 19, "rollno": "BSDS-002-2020"}
stdDict_3 = {"name": "Hassan", "age": 22, "rollno": "BSDS-003-2020"}
stdDict_4 = {"name": "Kashif", "age": 24, "rollno": "BSDS-004-2020"}
stdDict_5 = {"name": "Talha", "age": 18, "rollno": "BSDS-005-2020"}
# Creating the list
listStudent_Record = [stdDict_1, stdDict_2, stdDict_3, stdDict_4, stdDict_5]
# Getting the data from the list
print(listStudent_Record)
print("-----------------------------")
# Getting the record of first dictionary from list
print(listStudent_Record[0])
print("-----------------------------")
# Getting the name of student from 1 dictionary from list
print(listStudent_Record[0]["name"])
print("-----------------------------")
# Getting the names of all the students present in all the dictionaries in the list
print(listStudent_Record[0]["name"])
print(listStudent_Record[1]["name"])
print(listStudent_Record[2]["name"])
print(listStudent_Record[3]["name"])
print(listStudent_Record[4]["name"])
| true |
c2bf6604b053c51f040365c80ccdb95d3dae9fba | domsqas-git/Python | /vscode/myGame.py | 1,044 | 4.21875 | 4 | print("Bim Bum Bam!!")
name = input("What's your name? ").upper()
age = int(input("What's your age? "))
print("Hello", name, "you are", age, "years hold.")
points = 10
if age >= 18:
print("Hooray!! You can play!!")
wants_to_play = input("Do you want to play? ").lower()
if wants_to_play == "yes":
print("Let's Rock&Roll!!")
print("You're starting off with", points, "points")
up_or_down = input("Choose.. Up or Down.. ").lower()
if up_or_down == "up":
ans = input("Great! There is an Helicopter.. Do you want to jump in? ").lower()
if ans == "yes":
print("The helicopter crashed, you're injured and lost 5 points")
points -= 5
elif ans == "no":
print("Good choice! You're safe!")
elif ans == "down":
print("Have a sit and someone will come and get you!")
else:
print("That's fine", name, "but you're missing big my Friend!")
else:
print("Sorry", name, "You can't play!") | true |
04c9bfd9367c43b47f01ba345ba94a7a9ac61129 | Nilutpal-Gogoi/LeetCode-Python-Solutions | /Array/Easy/674_LongestContinuousIncreasingSubsequence.py | 856 | 4.21875 | 4 | # Given an unsorted array of integers, find the length of longest continuous
# increasing subsequence(Subarray).
# Example 1:
# Input: [1,3,5,4,7]
# Output: 3
# Explanation: The longest continuous increasing subsequence is [1,3,5], its length
# is 3. Even though [1,3,5,7] is also an increasing subsequence, it's
# not a continuous one where 5 and 7 are separated by 4.
# Example 2:
# Input: [2,2,2,2,2]
# Output: 1
# Explanation: The longest continuous increasing subsequence is [2], its length is 1.
# Note: Length of the array will not exceed 10,000.
def findLengthofLCIS(nums):
result = 0
anchor = 0
for i in range(len(nums)):
if i > 0 and nums[i-1] >= nums[i]:
anchor = i
result = max(result, i-anchor + 1)
return result
print(findLengthofLCIS([1,3,5,4,7])) | true |
05365bc5a7afac8cb90b1078393aec87ec1867b4 | Nilutpal-Gogoi/LeetCode-Python-Solutions | /Array/Easy/349_IntersectionOfTwoArrays.py | 986 | 4.21875 | 4 | # Given two arrays, write a function to compute their intersection.
# Example 1:
# Input: nums1 = [1,2,2,1], nums2 = [2,2]
# Output: [2]
# Example 2:
# Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# Output: [9,4]
# Note:
# Each element in the result must be unique.
# The result can be in any order.
# ------------------ Brute Force -----------------------------------------
def intersection(nums1, nums2):
lis = []
for i in nums1:
for j in nums2:
if i == j:
if i not in lis:
lis.append(i)
return lis
# ---------------- Using inbuilt sets ---------------------------------------
def intersection1(nums1, nums2):
set1 = set(nums1)
set2 = set(nums2)
return set1.intersection(set2)
# Time Complexity = O(n+m), O(n) time is used to convert nums1 into set, O(m) time
# is used to convert nums2
# Space Complexity = O(n+m) in the worst case when all the elements in the arrays
# are different.
| true |
8b9c0aac40b97452fc35f19f49f191bc161e90b9 | Nilutpal-Gogoi/LeetCode-Python-Solutions | /LinkedList/Easy/21_MergeTwoSortedLists.py | 1,184 | 4.21875 | 4 | # Merge two sorted linked lists and return it as a new sorted list. The new list should
# be made by splicing together the nodes of the first two lists.
# Example:
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
first = l1
second = l2
if not first:
return second
if not second:
return first
if first.val < second.val:
third = last = first
first = first.next
else:
third = last = second
second = second.next
while first and second:
if first.val < second.val:
last.next = first
last = first
first = first.next
else:
last.next = second
last = second
second = second.next
if first != None:
last.next = first
else:
last.next = second
return third | true |
14e28eb677d53cd4e5b6931b2036c0de647f68a3 | pol9111/algorithms | /二叉树/二叉树_建树.py | 2,117 | 4.15625 | 4 | from collections import deque
import unittest
class Node:
"""二叉树的节点类"""
def __init__(self, elem=-1, lchild=None, rchild=None): # 一个节点实例具有三个属性: 值, 左子节点, 右子节点
self.elem = elem # 准备存入的数据
self.lchild = lchild
self.rchild = rchild
class Tree:
"""二叉树类"""
def __init__(self):
self.root = None
def add(self, elem):
"""为树添加节点"""
node = Node(elem)
if self.root is None: # 如果树是空的,则对根节点赋值
self.root = node # 变成一个节点实例, elem值为传入elem, 同时具有lchild, rchild两个属性, 值为None
else:
queue = deque() # deque作为双向队列比list好
queue.append(self.root) # 对已有的节点进行层次遍历
while queue:
cur = queue.popleft() # 弹出队列的一个节点
if cur.lchild is None:
cur.lchild = node # 该节点lchild变成一个节点实例, 新的节点值为传入elem, 同时具有lchild, rchild两个属性, 值为None
return
elif cur.rchild is None:
cur.rchild = node
return
else: # 如果左右子树都不为空,加入队列继续判断
queue.append(cur.lchild)
queue.append(cur.rchild)
def breadth_travel(self):
"""利用队列实现树的层次遍历"""
if self.root is None:
return
queue = deque()
queue.append(self.root)
while queue:
node = queue.popleft()
print(node.elem, end='\t')
if node.lchild is not None:
queue.append(node.lchild)
if node.rchild is not None:
queue.append(node.rchild)
class Test(unittest.TestCase):
def testTree(self):
tree = Tree()
for i in range(1000):
tree.add(i)
tree.breadth_travel()
if __name__ == "__main__":
unittest.main() | false |
2ff343c91342b32581d3726eb92c6570eb4c049e | forgoroe/python-misc | /5 listOverLap.py | 1,102 | 4.3125 | 4 | """
ake two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.
Extras:
Randomly generate two lists to test this
Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
"""
import random
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
my_random = [random.sample(range(100),10), random.sample(range(100),10)]
for sample in my_random:
sample.sort()
def commonElementsBetween(firstList, secondList):
commonList = []
for element in firstList:
if element in secondList:
if element not in commonList:
commonList.append(element)
return commonList
print('first list: ' + str(my_random[0]), '\nsecond list: ' + str(my_random[1]))
print('elements in common: ' + str(commonElementsBetween(my_random[0],my_random[1]))) | true |
1e138a3770218338f66b78f14945e0508c1041a4 | forgoroe/python-misc | /3 listLessThan.py | 912 | 4.375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
Write this in one line of Python.
Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
missing = None
def listLessThan(myList, paramArg = missing):
b = []
if paramArg is None:
paramArg = 5
for element in myList:
if element < paramArg:
b.append(element)
return b
try:
param = int(input('Create list of all the numbers less than (default is < 5): '))
print(listLessThan(a, param))
except:
print(listLessThan(a))
| true |
7c57689eac501ab4bc6da1e8c17a5c7abe1dd58b | forgoroe/python-misc | /14 removeListDuplicates.py | 771 | 4.21875 | 4 | """
Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.
Extras:
Write two different functions to do this - one using a loop and constructing a list, and another using sets.
Go back and do Exercise 5 using sets, and write the solution for that in a different function.
"""
listOfDuplicates = [1,1,1,2,2,2,5,5,5,9,10]
def removeDuplicates(listParam):
myList = list(set(listParam))
myList.sort()
return myList
def secondaryRemoveDuplicate(listParam):
newList = []
for element in listParam:
if element not in newList:
newList.append(element)
newList.sort()
return newList
print(removeDuplicates(listOfDuplicates))
print(secondaryRemoveDuplicate(listOfDuplicates)) | true |
c45559cbf2cd3491aa031ec9116ba6d2478dace9 | notontilt09/Intro-Python-I | /src/prime.py | 294 | 4.125 | 4 | import math
x = input("Enter a number, I'll let you know if it's prime:")
def isPrime(num):
if num < 2:
return False
for i in range(2, math.ceil(math.sqrt(num))):
if num % i == 0:
return False
return True
if isPrime(int(x)):
print('Prime')
else:
print('Not prime')
| true |
4d343fedf8584b93d3835f74851898c2bbff0e8c | Tanner-Jones/Crypto_Examples | /Encryption.py | 696 | 4.15625 | 4 | from cryptography.fernet import Fernet
# Let's begin by showing an example of what encryption looks like
# This is an example random key. If you run the file again
# you will notice the key is different each time
key = Fernet.generate_key()
print(key)
# Fernet is just a symmetric encryption implementation
f = Fernet(key)
print(f)
# Notice the Encrypted output of this example string
# You don't need to worry about how the message is being encrypted
# Just notice that the output is gibberish compared to the input
token = f.encrypt(b"This is some example of a secret")
print(token)
# an accompanying decryption is established
token = f.decrypt(token)
print(token)
| true |
d337dff4b4895be03919604f2b501f5cda598fb0 | jonaskas/Programa-o | /7_colecoes-master/G_set2.py | 637 | 4.15625 | 4 | """
Sets
- Allow operations based on set theory.
"""
set1 = {'a', 'b', 'c', 'a', 'd', 'e', 'f'}
set2 = set("aaaabcd")
print()
print("intersection:", set1 & set2) # same as print(set1.intersection(set2))
print("union:", set1 | set2) # same as print(set1.union(set2))
print("diference: ", set1 - set2) # same as print(set1.difference(set2))
print("symmetric_difference:", set1.symmetric_difference( set("xzabc") )) # not in both
print()
print("issuperset:", set1.issuperset(set2))
print("issubset:", set1.issubset(set2))
print("isdisjoint:", set2.isdisjoint(set("xz")))
print()
for item in set1 - set2:
set2.add(item)
print(set2)
| false |
4b772bd2b3e80c5efb292bfedf7e74908aae1d7a | jonaskas/Programa-o | /7_colecoes-master/C_mutability2.py | 489 | 4.15625 | 4 | """
Mutability
- Python is strongly object-oriented in the sense that everything
is an object including numbers, strings and functions
- Immutable objects: int, float, decimal, complex, bool, string,
tuple, range, frozenset, bytes
- Mutable objects: list, dict, set, bytearray,user-defined classes
"""
def print_memory(obj):
print(hex(id(obj)), ":", obj)
# integers are immutable
print()
a = 5
print_memory(a)
a += 1
print_memory(a)
b = a
print(a is b) # identity equality
| true |
3939d09d42684a7b934c5d81820cb8153b8c4b29 | jonaskas/Programa-o | /7_colecoes-master/C_mutability4.py | 684 | 4.3125 | 4 | """
Mutability
- Python is strongly object-oriented in the sense that everything
is an object including numbers, strings and functions
- Immutable objects: int, float, decimal, complex, bool, string,
tuple, range, frozenset, bytes
- Mutable objects: list, dict, set, bytearray,user-defined classes
"""
def print_memory(obj):
print(hex(id(obj)), ":", obj)
# list are mutable
print()
my_list = []
print_memory(my_list)
my_list += [11, 22]
print_memory(my_list)
my_list.append(33)
print_memory(my_list)
my_list.remove(11)
print_memory(my_list)
print()
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2)
print(list1 is list2)
print(list1 is list3)
| true |
62fb02699f26a16e7c18ba5d70b234068c05b0ee | jonaskas/Programa-o | /7_colecoes-master/C_mutability3.py | 474 | 4.125 | 4 | """
Mutability
- Python is strongly object-oriented in the sense that everything
is an object including numbers, strings and functions
- Immutable objects: int, float, decimal, complex, bool, string,
tuple, range, frozenset, bytes
- Mutable objects: list, dict, set, bytearray,user-defined classes
"""
def print_memory(obj):
print(hex(id(obj)), ":", obj)
# tuples are immutable
tuple_ = (1, 2, 3)
print_memory(tuple_)
tuple_ += (4, 5, 6)
print_memory(tuple_)
| true |
74494d848957c254dea03530e1cabe13b1b399b1 | Jithin2002/pythonprojects | /List/element found.py | 384 | 4.125 | 4 | lst=[2,3,4,5,6,7,8]
num=int(input("enter a number"))
flag=0
for i in lst:
if(i==num):
flag=1
break
else:
flag=0
if(flag>0):
print("element found")
else:
print("not found")
#this program is caled linear search
# we have to search everytime wheather element is thereor not
# drawback increases complexity
# to overcome this we use binary search
| true |
321f1e726d75e4f7013074163ce7cfeab25dbeb8 | sunglassman/U3_L11 | /Lesson11/problem3/problem3.py | 253 | 4.1875 | 4 | print('-' * 60)
print('I am EvenOrOdd Bot')
print()
number = input('Type a number: ')
number = int(number)
if number == even:
print('Your number is even. ')
else:
print('Your number is odd. ')
print('Thank you for using the app! ')
print('-' * 60) | true |
ee0e317f118463d348f2a765fd161bb689ddc11e | swikot/Python3 | /ListComprehension.py | 2,162 | 4.15625 | 4 | __author__ = 'snow'
# List comprehension is an elegant
# way to define and create
# list in Python
Celsius = [39.2, 36.5, 37.3, 37.8]
Far=[((float(9)/5)*x + 32) for x in Celsius]
print("far values",Far)
odd_number=[x for x in range(1,11) if x%2]
print("odd number is: ",odd_number)
even_number=[x for x in range(1,11) if x%2==0]
print("even number is: ",even_number)
list_tuples=[(x,y) for x in odd_number for y in even_number]
print("list tuples: ",list_tuples)
# Generator Comprehension
# use () instead of []
suare_x=(x**2 for x in range(21))
print("Generator List Comprehension: ",list(suare_x))
# sieve of Eratosthenes
noprime=[j for i in range(2,8) for j in range(i*2,100,i)]
prime=[i for i in range(2,100) if i not in noprime]
print("prime numbers are: ",prime)
from math import sqrt
n=100
non_prime=[j for i in range(2,int(sqrt(n))) for j in range(i*2,100,i)]
primes=[i for i in range(2,100) if i not in non_prime]
print("prime numbers are: ",primes)
# Set Comprehension
n1=1000
key=int(sqrt(n1))
not_prime={j for i in range(2,key) for j in range(i*2,1000,i)}
primes={i for i in range(2,n1) if i not in not_prime}
print("set comprehension primes: ",primes)
# Recursive Function to Calculate the Primes
def primes(n):
if n == 0:
return []
elif n == 1:
return []
else:
p = primes(int(sqrt(n)))
no_p = {j for i in p for j in range(i*2, n+1, i)}
p = {x for x in range(2, n + 1) if x not in no_p}
return p
for i in range(1,50):
print(i, primes(i))
# n Python 2, the loop control variable is not local,
# t can change another variable of that name outside of the list comprehension,
# x = "This value will be changed in the list comprehension"
# res = [x for x in range(3)]
# res
# [0, 1, 2]
# x
# 2
# res = [i for i in range(5)]
# i
# 4
#
#in python 3
# $ python3
# Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
# [GCC 4.5.2] on linux2
# Type "help", "copyright", "credits" or "license" for more information.
# >>> x = "Python 3 fixed the dirty little secret"
# >>> res = [x for x in range(3)]
# >>> print(res)
# [0, 1, 2]
# >>> x
# 'Python 3 fixed the dirty little secret'
# >>> | false |
1056aa97f9bd6fe7024e8b17dcbfb4e48a40e82e | swikot/Python3 | /MaxFunction.py | 518 | 4.1875 | 4 | __author__ = 'snow'
# x = eval(input("1st Number: "))
# y = eval(input("2nd Number: "))
# z = eval(input("3rd Number: "))
#
#
# maximum=max((x,y,z))
# mximum2=maximum
# print("maximum=" +str(maximum))
# print("maxumum2=",mximum2)
#
print()
number_of_values = int(input("How many values? "))
maximum = float(input("Value: "))
print(maximum)
for i in range(number_of_values - 1):
value = float(input("Value: "))
if value > maximum:
maximum = value
print("The maximal value is: " + str(maximum))
| false |
639de603bbf4502f07acfdfe29d6e048c4a89076 | rjtshrm/altan-task | /task2.py | 926 | 4.125 | 4 | # Algorithm (Merge Intervals)
# - Sort the interval by first element
# - Append the first interval to stack
# - For next interval check if it overlaps with the top interval in stack, if yes merge them
def merge_intervals(intervals):
# Sort interval by first element
sort_intervals_first_elem = sorted(intervals, key=lambda k: k[0])
stack = []
# stack iteration and interval operation
for interval in sort_intervals_first_elem:
if len(stack) == 0:
stack.append(interval)
else:
f, e = interval
tf, te = stack[-1] # top element in stack
if tf <= f <= te:
# interval overlap each other
stack[-1][1] = max(e, te)
else:
stack.append(interval)
return stack
if __name__ == '__main__':
intervals = [[25, 30], [2, 19], [14, 23], [4, 8]]
print(merge_intervals(intervals))
| true |
132b54c3b4587e500e050d6be5cfadc4488f5da5 | briantsnyder/Lutron-Coding-Competiton-2018 | /move_maker.py | 1,946 | 4.4375 | 4 | """This class is the main class that should be modified to make moves in order to play the game.
"""
class MoveMaker:
def __init__(self):
"""This class is initialized when the program first runs.
All variables stored in this class will persist across moves.
Do any initialization of data you need to do before the game begins here.
"""
print("Matthew J Gunton and Brian Snyder")
def make_move(self, mancala_board):
# {
# "MyCups": [4, 3, 2, 1, 5, 3],
# "MyMancala": 0,
# "OpponentCups": [3, 6, 2, 0, 1, 2],
# "OpponentMancala": 3
# }
#strategy:
# 1) take all free moves as they happen
# 2) can it land on an empty space & steal
# 3) if all else fails, whichever is closest, you move
NUMOFCUPS = 6
#1
for i in range(NUMOFCUPS-1,-1,-1):
#we don't account for if you can go around and get this
if mancala_board["MyCups"][i] == NUMOFCUPS - i:
return i
#2
if mancala_board["MyCups"][i] == 0 and mancala_board["OpponentCups"][5-i] != 0:
for curIndex, stone_count in enumerate(mancala_board["MyCups"]):
if i > curIndex:
if i == stone_count - 13 + curIndex and stone_count != 0:
print("we found a way to steal")
return curIndex
else:
if stone_count == i - curIndex and stone_count != 0:
print("we found a way to steal\n our index:"+str(i)+"\n current index: "+str(curIndex)+"\n stone count"+str(stone_count))
return curIndex
print("nothing better")
#3
for i in range(NUMOFCUPS - 1, -1, -1):
if (mancala_board["MyCups"][i] != 0):
return i
return 0
| true |
c7363294a807a273dce1204c1c6b0a2b167590ee | nathancmoore/code-katas | /growing_plant/plant.py | 528 | 4.34375 | 4 | """Return the number of days for a plant to grow to a certain height.
#1 Best Practices Solution by Giacomo Sorbi
from math import ceil; growing_plant=lambda u,d,h: max([ceil((h-u)/(u-d)),0])+1
"""
def growing_plant(up_speed, down_speed, desired_height):
"""Return the number of days for a plant to grow to a certain height."""
height = 0
days = 0
while height < desired_height:
days += 1
height += up_speed
if height >= desired_height:
return days
height -= down_speed
| true |
d0f59bf4520f993c32505a7b3406d786a76befa9 | PaviLee/yapa-python | /in-class-code/CW22.py | 482 | 4.25 | 4 | # Key = Name
# Value = Age
# First way to make a dictionary object
database = {}
database["Frank"] = 21
database["Mary"] = 7
database["John"] = 10
print(database)
# Second way to make a dictionary object
database2 = {
"Frank": 21,
"Mary": 7,
"Jill": 10
}
print(database2)
for name, age in database2.items():
print(name + " is " + str(age) + " years old")
# Make a phonebook dictionary
# 3 key-value pairs
# Key = name of person
# Value = distinct phone number
| true |
832439c69ddbcbeb4b2ad961e7427b760306fb92 | Th0rt/LeetCode | /how-many-numbers-are-smaller-than-the-current-number.py | 999 | 4.125 | 4 | # https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
import unittest
from typing import List
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
length = len(nums)
temp = sorted(nums)
mapping = {}
for i in range(length):
if temp[i] not in mapping:
mapping[temp[i]] = i
return [mapping[nums[i]] for i in range(length)]
class TestSolution(unittest.TestCase):
def test_1(self):
nums = [8, 1, 2, 2, 3]
expect = [4, 0, 1, 1, 3]
assert Solution().smallerNumbersThanCurrent(nums) == expect
def test_2(self):
nums = [6, 5, 4, 8]
expect = [2, 1, 0, 3]
assert Solution().smallerNumbersThanCurrent(nums) == expect
def test_3(self):
nums = [7, 7, 7, 7]
expect = [0, 0, 0, 0]
assert Solution().smallerNumbersThanCurrent(nums) == expect
if __name__ == "__main__":
unittest.main()
| true |
9f0d9d5ee1f94937f54a70330e70f5c3b5dc0358 | JoeD1991/Quantum | /Joe_Problem_1.py | 361 | 4.3125 | 4 | """
If we list all the natural numbers below 10 that are multiples of
3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
myList = set()
N5 = 1000//5
N3 = 1000//3+1
for i in range(1,N3):
myList.add(3*i)
if i<N5:
myList.add(5*i)
print(sum(myList))
| true |
53684088e0af3d314c602a4c58439b76faf161cb | NGPHAN310707/C4TB13 | /season6/validpasswordstourheart.py | 212 | 4.125 | 4 | while True:
txt = input("Enter your password?")
print(txt)
if txt.isalpha() or len(txt)<=8 or txt.isdigit:
print(txt,"is a name")
break
else:
print("please don't")
| true |
144a61b43eab0992d60e4b0e8146734ed53347d0 | JitinKansal/My-DS-code | /tree_imlementation.py | 1,048 | 4.1875 | 4 | # Creating a new node for the binary tree.
class BinaryTree():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Inorder traversal of the tree (using recurssion.)
def inorder(root):
if root:
inorder(root.left)
print(root.data,end=" ")
inorder(root.right)
# postorder traversal of the tree (using recurssion.)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.data,end=" ")
# preorder traversal of the tree (using recurssion.)
def preorder(root):
if root:
print(root.data,end=" ")
preorder(root.left)
preorder(root.right)
root = BinaryTree(1)
root.left = BinaryTree(2)
root.right = BinaryTree(3)
root.left.left = BinaryTree(4)
root.left.right = BinaryTree(5)
root.right.left = BinaryTree(6)
root.right.right = BinaryTree(7)
inorder(root)
print()
print()
postorder(root)
print()
print()
preorder(root)
| true |
be4af81f42222bb4cb60937d036fc6f91b6fea67 | a421101046/-python | /ex45.py | 1,024 | 4.5 | 4 | # -- coding: utf-8 --
# 习题 45: 对象、类、以及从属关系
# 针对类和对象 "is_a" 讨论两个类的共同点 “has_a”指 两个类无共同点,仅仅供互相参照
# is_a
class Animal(object):
pass
class Dog(Animal):
def __init_(self, name):
# has_a
self.name = name
# is_a
class Cat(Animal):
def __init__(self, name):
# has_a
self.name = name
# is_a
class Person(object):
def __init__(self, name):
# has_a
self.name = name
# Person has_a pet的属性
self.pet = None
# is_a
class Employee(Person):
def __init__(self, name, salary):
# ????
super(Employee, self).__init(name)
# has_a
self.salary = salary
# is_a
class Fish(object):
pass # ??
# is_a
class GoldFish(Fish):
pass
# is_a
dog = Dog("哈士奇")
Tom = Cat("汤姆")
linqi = Person("林奇")
# has_a
linqi.pet = Tom
"""
1.python添加object类的目的是,要求所有子类都从object这个类中继承
2.??
6.存在多重继承 has_many,尽量避免使用
"""
| false |
4b6e6e0c460c8a3bd09e60009cac823ab52fed4b | yangrencong/pythonstudy | /3.0/copy.py | 389 | 4.125 | 4 | My_foods =['pizza','falafel','carrot','cake']
Friend_foods =My_foods[:]
My_foods.append('cannoli')
Friend_foods.append('ice cream')
print('my favorate foods are:')
print(My_foods)
print("\nmy friend's favorate food are: ")
print(Friend_foods)
print('the first three items in list are:')
food1=My_foods[0:3]
print(food1)
food2=My_foods[1:4]
print(food2)
food3=My_foods[-3:]
print(food3)
| false |
86a9f9654568017337b9f306ebd4a8eea326b535 | YaohuiZeng/Leetcode | /152_maximum_product_subarray.py | 1,446 | 4.28125 | 4 | """
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
"""
Q:
(1) could have 0, and negative
(2) input contains at least one number
(3) all integers?
Algorithm: Time: O(n); Space: O(1). https://www.quora.com/How-do-I-solve-maximum-product-subarray-problems
You have three choices to make at any position in array.
1. You can get maximum product by multiplying the current element with
maximum product calculated so far. (might work when current
element is positive).
2. You can get maximum product by multiplying the current element with
minimum product calculated so far. (might work when current
element is negative).
3. Current element might be a starting position for maximum product sub
array
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
prev_max, prev_min, cur_max, res = nums[0], nums[0], nums[0], nums[0]
for i in range(1, len(nums)):
cur_max = max(prev_max * nums[i], prev_min * nums[i], nums[i])
cur_min = min(prev_max * nums[i], prev_min * nums[i], nums[i])
res = max(cur_max, res)
prev_max, prev_min = cur_max, cur_min
return res
| true |
d5ac5a0d89985b6525988e21ed9fe17a44fb4caa | YaohuiZeng/Leetcode | /280_wiggly_sort.py | 1,227 | 4.21875 | 4 | """
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
"""
"""
1. use python in-place sort()
2. one pass: compare current and next, if not the right order, swap.
This works because: suppose we already have nums[0] <= nums[1] in the right order. Then when comparing nums[1]
and nums[2], if nums[1] < nums[2], meaning the required ">=", we swap nums[1] and nums[2], the first "<=" still
holding because nums[2] > nums[1] >= nums[0].
"""
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
nums.sort()
for i in range(1, n-1, 2):
nums[i], nums[i+1] = nums[i+1], nums[i]
def wiggleSort2(self, nums):
for i in range(0, len(nums)-1):
if i % 2 == 0:
if nums[i] > nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
else:
if nums[i] < nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i] | true |
6aea488ab45998317d8a8d5e180d539e5721873e | ariModlin/IdTech-Summer | /MAC.py | 518 | 4.125 | 4 | # finds the MAC of a message using two different keys and a prime number
message = "blah blahs"
key1 = 15
key2 = 20
prime_num = 19
def find_mac():
message_num = 0
for i in range(len(message)):
# takes each letter of the message and finds its ASCII counterpart
num = ord(message[i])
# adds each ASCII number to an integer message_num
message_num += num
# the mac of the message is equal to this equation
m = ((key1 * message_num) + key2) % prime_num
return m
mac = find_mac()
print(mac) | true |
6fe51f731f777d02022852d1428ce069f0594cf4 | ariModlin/IdTech-Summer | /one time pad.py | 1,867 | 4.21875 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
message = input("input message you want to encrypt: ")
key = input("input key you want to encrypt the message with: ")
message_array = []
key_array = []
encrypted_numbers = []
decrypted_message = ""
def convert_message():
for i in range(len(message)):
# takes the message and converts the letters into numbers
message_index = (alphabet.find(message[i]))
message_array.append(message_index)
return message_array
def convert_key():
for j in range(len(key)):
# takes the key and converts the letters into numbers
key_index = (alphabet.find(key[j]))
key_array.append(key_index)
return key_array
def encrypt_message():
encrypted_message = ""
for x in range(len(message)):
# adds each number letter from both the message array and the key array and mods 26 to get the new number
new_num = (message_array[x] + key_array[x]) % 26
# adds each new number to an encrypted numbers array
encrypted_numbers.append(new_num)
# converts each of the new numbers into its corresponding letter
new_letters = alphabet[encrypted_numbers[x]]
encrypted_message += new_letters
print("encrypted message: " + encrypted_message)
return encrypted_message
convert_message()
convert_key()
encrypt_message()
question = input("do you wish to see the message decrypted again? y/n ")
if question == "y":
for a in range(len(encrypted_message)):
decrypted_nums = encrypted_numbers[a] - key_array[a]
if decrypted_nums < 0:
decrypted_nums = 26 + decrypted_nums
decrypted_letters = alphabet[decrypted_nums]
decrypted_message += decrypted_letters
print("decrypted message: " + decrypted_message)
else:
print("goodbye")
| true |
ada99ffe37296e78bbaa7d804092a495be47c1ba | dineshj20/pythonBasicCode | /palindrome.py | 890 | 4.25 | 4 | #this program is about Palindrome
#Palindrom is something who have the same result if reversed for e.g. " MOM "
#how do we know whether the given string or number is palindrome
number = 0
reverse = 0
temp = 0
number = int(input("Please Enter the number to Check whether it is a palidrome : "))
print(number)
temp = number #given number is copied in temp variable
while(temp != 0): # until the number is reversed
reverse = reverse * 10 # reverse will store the reversed number by one digit and shift the place of digit
reverse = reverse + temp % 10 # remainder of the given number gives last digit every time and is stored in reverse
temp = int(temp/10) # every last digit of given number is eliminated here
if(reverse == number):
print("Number is a Palindrome")
else:
print("Number is not a Palindrome")
| true |
6c5ee3e9cb85a24940a9238981b7f6fbf9ec1696 | MichealPro/sudoku | /create_sudoku.py | 2,158 | 4.375 | 4 | import random
import itertools
from copy import deepcopy
# This function is used to make a board
def make_board(m=3):
numbers = list(range(1, m ** 2 + 1))
board = None
while board is None:
board = attempt_board(m, numbers)
return board
# This function is used to generate a full board
def attempt_board(m, numbers):
n = m ** 2
board = [[None for _ in range(n)] for _ in range(n)]
for i, j in itertools.product(range(n), repeat=2):
i0, j0 = i - i % m, j - j % m # origin of m * m block
random.shuffle(numbers)
for x in numbers:
if (x not in board[i] # row
and all(row[j] != x for row in board) # column
and all(x not in row[j0:j0 + m]
for row in board[i0:i])):
board[i][j] = x
break
else:
return None
return board
# This function is used to print the whole Soduku out
def print_board(board, m=3):
numbers = list(range(1, m ** 2 + 1))
omit = 5
challange = deepcopy(board)
for i, j in itertools.product(range(omit), range(m ** 2)):
x = random.choice(numbers) - 1
challange[x][j] = 0
spacer = "++-----+-----+-----++-----+-----+-----++-----+-----+-----++"
print(spacer.replace('-', '='))
for i, line in enumerate(challange):
print("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||"
.format(*(cell or ' ' for cell in line)))
if (i + 1) % 3 == 0:
print(spacer.replace('-', '='))
else:
print(spacer)
return challange
def print_answers(board):
spacer = "++-----+-----+-----++-----+-----+-----++-----+-----+-----++"
print(spacer.replace('-', '='))
for i, line in enumerate(board):
print("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||"
.format(*(cell or ' ' for cell in line)))
if (i + 1) % 3 == 0:
print(spacer.replace('-', '='))
else:
print(spacer)
def generate():
Board = make_board()
bo=print_board(Board)
return bo | true |
f605c356950e7e609d3e57c92169775cf4ed497a | sssvip/LeetCode | /python/num003.py | 1,303 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-09-28 22:25:36
# @Author : David:admin@dxscx.com)
# @Link : http://blog.dxscx.com
# @Version : 1.0
"""
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
>>> print Solution().lengthOfLongestSubstring("bdbf")
3
>>> print Solution().lengthOfLongestSubstring("abcdd")
4
"""
max_length = 0
pre_substr = ""
for x in s:
indexof = pre_substr.find(x) # optimizable point (make O(n^2))
if indexof >= 0:
pre_substr = pre_substr[indexof + 1:]
pre_substr = pre_substr + x
max_length = max(max_length, len(pre_substr))
return max_length
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
# print Solution().lengthOfLongestSubstring("abcdd")
| true |
89db6d170e6eb265a1db962fead41646aaed6f9f | sssvip/LeetCode | /python/num581.py | 1,606 | 4.21875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: David
@contact: tangwei@newrank.cn
@file: num581.py
@time: 2017/11/7 20:29
@description:
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
"""
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
>>> print Solution().findUnsortedSubarray([1,2,3,4])
0
>>> print Solution().findUnsortedSubarray([1,3,2,1,5,6])
3
>>> print Solution().findUnsortedSubarray([2,6,4,8,10,9,15])
5
"""
n = len(nums)
if n < 1:
return 0
snums = sorted(nums)
start = 0
end = 0
for x in range(n):
if snums[x] != nums[x]:
start = x
break
for x in range(n):
if snums[n - x - 1] != nums[n - x - 1]:
end = n - x - 1
break
return end - start + 1 if (end - start) > 0 else 0
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
| true |
bee25d157f354404981db25e5912e87f21e1bb10 | GeginV/Iterations-Python | /practice (17).py | 769 | 4.1875 | 4 | list_ = [-5, 2, 4, 8, 12, -7, 5]
# Объявим переменную, в которой будем хранить индекс отрицательного элемента
index_negative = None
for i, value in enumerate(list_):
if value < 0:
print("Отрицательное число: ", value)
index_negative = i # перезаписываем значение индекса
print("Новый индекс отрицательного числа: ", index_negative)
else:
print("Положительное число: ", value)
print("---")
print("Конец цикла")
print()
print("Ответ: индекс последнего отрицательного элемента = ", index_negative)
| false |
b2df25d12178483143cbb6fcceaba3e2220b2b4b | eludom/snippits | /python/exercises/python/QuickSort.py | 2,607 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
This class implements qucksort on arrays.
See https://en.wikipedia.org/wiki/Quicksort
# algorithm quicksort(A, lo, hi) is#
# if lo < hi then
# p := partition(A, lo, hi)
# quicksort(A, lo, p – 1)
# quicksort(A, p + 1, hi)
#
# algorithm partition(A, lo, hi) is
# pivot := A[hi]
# i := lo - 1
# for j := lo to hi - 1 do
# if A[j] ≤ pivot then
# i := i + 1
# swap A[i] with A[j]
# swap A[i+1] with A[hi]
# return i + 1
#
"""
class QuickSort(object):
"""Quicksort implementaton"""
def __init__(self, unsorted_array):
"""Initialize an array for quicksort"""
self.array_to_sort = unsorted_array
self.is_sorted = False
print "starting array is", self.print_array()
return None
def print_array(self):
"""Print the [un]sorted array"""
print self.array_to_sort
def swap(self, swap_x, swap_y):
"""swap two elements of an array"""
tmp = self.array_to_sort[swap_x]
self.array_to_sort[swap_x] = self.array_to_sort[swap_y]
self.array_to_sort[swap_y] = tmp
def partition(self, lo_index, hi_index):
"""Parttiton the array"""
print "partition(%d,%d)" % (lo_index, hi_index)
print " array: ", self.array_to_sort
# pivot on this value
pivot = self.array_to_sort[hi_index]
print " pivot on hi_index ", hi_index, " pivot is ", pivot
print
# next place to put values less than pivot
insert_here = lo_index - 1
for from_here in range(lo_index, hi_index):
if self.array_to_sort[from_here] <= pivot:
# move where to insert right one
insert_here = insert_here + 1
# put value less than pivot left of pivot value
self.swap(insert_here, from_here)
# finally, swap the pivot value itself to the end of the lis
self.swap(insert_here+1, hi_index)
# and report where we partitioned
return insert_here + 1
def quicksort(self, lo_index, hi_index):
"""Quicksort a slice of the array"""
print "quicksort(%d,%d)" % (lo_index, hi_index)
print " array: ", self.array_to_sort
print
if lo_index < hi_index:
partition_index = self.partition(lo_index, hi_index)
self.quicksort(lo_index, partition_index - 1)
self.quicksort(partition_index + 1, hi_index)
self.is_sorted = True
| false |
009cdcd897a882a10ba8424fa34b1f4906e2a3ae | stenen19/hw1.py | /hw1.py | 2,251 | 4.25 | 4 | from math import sqrt
def greeting():
capture = input("What's your name? ")
print("Hello %s " % capture)
def number():
number = input("enter any real number ")
numberint = int(number)
print("Your number is", numberint )
def average():
first = input("enter your first number ")
firstint = float(first)
second = input("enter your second number ")
secondint = float(second)
third = input("enter your third number ")
thirdint = float(third)
average = ((firstint+secondint+thirdint)/3)
print("the average is", average)
def graduate():
gradyear = input("What's your class year? ")
gradyearint = int(gradyear)
yearstogo = gradyearint - 2019
print("You will graduate from USNA in", yearstogo, "years" )
def sphere( radius ):
A = (4*3.14)*(radius**2)
V = (4/3)*(3.14)*(radius**3)
print( "Surface area is", A," and volume is", V)
#Professor Casey, why is the remainder not calculating correctly?
def division(divisor, dividend):
divisor = float(divisor)
dividend = float(dividend)
quotient = 0
count = 0
while dividend >= divisor:
dividend -= divisor
quotient += 1
count += 1
remainder = dividend - (divisor * count)
print("Quotient is" ,quotient, "and remainder is" ,remainder)
# Professor Casey, same problem as with previous example
#def division_alt ():
def triangle():
length = input("length of one leg of an isocleles right triangle: ")
length = float(length)
hypotenuse = sqrt(2 * (length ** 2))
print("The length of the hypotenuse is",hypotenuse)
"""
def feet( inches ):
feet = inches // 12
rem = inches % 12
print( feet, "feet", rem, "inches" )
def packets ( bits_in_file, bits_in_packet ):
num_full_packets = bits_in_file // bits_in_packet
rem_bits = bits_in_file % bits_in_packet
print( num_full_packets, " packets and ", rem_bits, " bits" )
def rect_base( length, width ):
area = length * width
return area
def pyramid ( length, width, height ):
volume = rect_base ( length, width ) * ( height )
return volume
"""
#greeting()j
#number()
#average()
#graduate()
#sphere( 32 )
#feet(72)
#division (4,11)
#division_alt (4,3)
#triangle()
| false |
89fa015cb0842c4e402b99284b3f2f6ebf46e0a4 | cmcg513/app-sec-assgn01-p2 | /mramdass/fib.py | 1,531 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Munieshwar (Kevin) Ramdass
Professor Justin Cappos
CS-UY 4753
14 September 2015
Compute up to the ith Fibonacci number
"""
def fib(ith): # BAD IMPLEMENTATION
if ith == 0:
return 0
elif ith == 1:
return 1
else:
return fib(ith - 1) + fib(ith - 2)
def fast_fib(ith, _cache={}): # FASTER IMPLEMENTATION
if ith in _cache:
return _cache[ith]
elif ith > 1:
return _cache.setdefault(ith, fast_fib(ith - 1) + fast_fib(ith - 2))
return ith
def print_fib(the_range):
"""
This function will print the Fibonacci numbers up to a certain point.
This function uses the bad implementation above.
"""
def fib(ith): # BAD IMPLEMENTATION
if ith == 0:
return 0
elif ith == 1:
return 1
else:
return fib(ith - 1) + fib(ith - 2)
for i in range(0, the_range + 1):
print (str(fib(i)))
def print_fast_fib(the_range):
"""
This function will print the Fibonacci numbers up to a certain point.
This function uses the faster implementation above.
"""
def fast_fib(ith, _cache={}): # FASTER IMPLEMENTATION
if ith in _cache:
return _cache[ith]
elif ith > 1:
return _cache.setdefault(ith, fast_fib(ith - 1) + fast_fib(ith - 2))
return ith
for i in range(0, the_range + 1):
print (str(fast_fib(i)))
print_fib(16)
print_fast_fib(128)
| false |
7e608dbf5c0d15627d9272e73afc33f69b37dfc5 | prabuinet/mit-intro-cs-py | /python_basics.py | 926 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#Scalar objects in python:
5 #int
2.5 #float
True #bool
None #NoneType
type(5)
type(3.2)
type(False)
type(None)
#Type Cast
float(5)
int(2.5)
# operators on ints and floats
i = 5
j = 2
i + j # sum
i - j # difference
i * j # product
i / j # division
i // j # => 2 integer division
i % j # => 1 reminder
i ** j # => 25 i to the power of j
# operator precedence
# 1. parantheses
# 2. **, *, /, + and -
# binding variabls and values
pi = 3.14159
pi_approx = 22/7
# abstracting expressions
radius = 2.2
area = pi * (radius ** 2)
#comparison operators on int and float
i > j
i >= j
i < j
i <= j
i == j
i != j
# a simple program
x = int(input('enter an integer:'))
if x % 2 == 0:
print ('')
print ('Even')
else:
print('')
print('Odd')
print('Done with conditional')
| false |
047983b82b4d26b73b2afe14859b5253cce17263 | erisaran/cosc150 | /Lab 05/Divisibleby3.py | 285 | 4.4375 | 4 | def is_divisible_by_3(x):
if x % 3 == 0:
print x,"is divisible by 3."
else:
print "This number is not divisible by 3."
def is_divisible_by_5(y):
if y%5==0:
print y,"is divisible by 5."
else:
print y,"is not divisble by 5."
| false |
d576f4074bb56baf51b82b9bf525db46c494f312 | CarlaCCP/EstudosPython | /Python/aula4_elif.py | 302 | 4.40625 | 4 | numero = int(input("Digite um número: "))
if numero%3 ==0:
print("Numero divisivel por 3")
else:
if numero%5 ==0:
print("Numero divisivel por 5")
if numero%3 ==0:
print("Numero divisivel por 3")
elif numero%5 ==0:
print("Numero divisivel por 5")
| false |
09eb0f8acf255d4471a41a56a50bccf24ed4c91c | MissBolin/CSE-Period3 | /tax calc.py | 230 | 4.15625 | 4 | # Tax Calculator
cost = float(input("What is the cost of this item? "))
state = input("What state? ")
tax = 0
if state == "CA":
tax = cost * .08
print("Your item costs ${:.2f}, with ${:.2f} in tax.".format(cost+tax, tax))
| true |
b9884eae05e9518e3ec889dd5280a8cea7c3c1d7 | gandastik/365Challenge | /365Challenge/insertElementes.py | 382 | 4.125 | 4 | #Jan 24, 2021 - insert a elements according to the list of indices
from typing import List
def createTargetArray(nums: List[int], index: List[int]) -> List[int]:
ret = []
for i in range(len(nums)):
ret.insert(index[i], nums[i])
return ret
lst = [int(x) for x in input().split()]
index = [int(x) for x in input().split()]
print(createTargetArray(lst, index)) | true |
20644bc6631d5eb8e555b1e2e61d1e0e6273bd00 | gandastik/365Challenge | /365Challenge/matrixDiagonalSum.py | 762 | 4.21875 | 4 | #37. Feb 6, 2021 - Given a square matrix mat, return the sum of the matrix diagonals.
# Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
from typing import List
def diagonalSum(mat: List[List[int]]) -> int:
res = 0
for i in range(len(mat)):
for j in range(len(mat)):
if(i+j == len(mat)-1):
res += mat[i][j]
if(i == j):
res += mat[i][j]
if(len(mat) % 2 != 0):
return res-mat[len(mat)//2][len(mat)//2]
return res
n = int(input())
arr = []
for i in range(n):
arr.append(list(map(int, input().split())))
print(diagonalSum(arr)) | true |
fb5ac6e49d0c5724362a41e2b004286e6a11478d | gandastik/365Challenge | /365Challenge/if-else.py | 409 | 4.34375 | 4 | # Jan 6, 2021 -if n is odd print Weird, n is even and inbetween 2 and 5 print Not Weird,
# n is even and inbetween 5 and 20 print Weird, n is even and greater than 20 print Not Weird
n = int(input())
if(n % 2 != 0):
print("Weird")
elif(n % 2 == 0 and n > 2 and n <= 5):
print("Not Weird")
elif(n % 2 == 0 and n > 5 and n <= 20):
print("Weird")
elif(n % 2 == 0 and n > 20):
print("Not Weird")
| false |
9fdedda65ec74a7ac9d9ab1510dcc1b63adf502d | ovidubya/Coursework | /Python/Programs/assign5part1.py | 560 | 4.46875 | 4 | def find_longest_word(wordList):
print("The list of words entered is:")
print(wordList)
result = ""
i = 0
while(i < len(wordList)): # iterates over the list to find the first biggest word
if(len(result) < len(wordList[i])):
result = wordList[i]
i = i + 1
print("")
print("The longest word in the list is:")
print(result)
# User enters words to be seperated in a list
x = input("Enter a few words and I will find the longest:")
# splits words into a list
xyz = x.split()
find_longest_word(xyz) | true |
6d3693dc72b467e593b511e79bea1a1b6f6d1392 | mcmxl22/Python-doodles | /fun/weird.py | 355 | 4.125 | 4 | #!/usr/bin/env python3
"""
weird version 1.1
Python 3.7
"""
def is_weird():
"""Is a number odd or even?"""
while True:
pick_number = int(input("Pick a number: "))
if pick_number % 2 == 0:
print("Not Weird!")
else:
print("Weird!")
if __name__ == "__main__":
is_weird()
| false |
a5201821c6cd15088a4b1a4d604531bbcca68c69 | mlrice/DSC510_Intro_to_Programming_Python | /fiber_optic_discount.py | 1,297 | 4.34375 | 4 | # DSC510
# 4.1 Programming Assignment
# Author Michelle Rice
# 09/27/20
# The purpose of this program is to estimate the cost of fiber optic
# installation including a bulk discount
from decimal import Decimal
print('Hello. Thank you for visiting our site, we look forward to serving you.'
'\nPlease provide some information to get started.\n')
# Retrieve company name and feet of cable from customer
company = input("What is your company name?")
feetRequired = float(input("How many feet of fiber optic cable do you need? (please enter numbers only)"))
# Set price tier
price1 = .87
price2 = .80
price3 = .70
price4 = .50
# Determine price based on requested feet of cable
if feetRequired > 500:
discPrice = price4
elif 250 < feetRequired <= 500:
discPrice = price3
elif 100 < feetRequired <= 250:
discPrice = price2
else:
discPrice = price1
# Calculate total cost
def calculate(feet, price):
cost = feet * price
return cost
totalCost = calculate(feetRequired, discPrice)
# Print receipt with company name and total cost
print("\n***RECEIPT***")
print("\nCustomer: " + company)
print("Required cable =", feetRequired, "feet at $", "{:.2f}".format(discPrice), "per foot")
print("Total Cost = $", "{:.2f}".format(totalCost))
print("\nThank you for your business!")
| true |
65293fcbfb356d2f045eff563083e2b751e61326 | martinkalanda/code-avengers-stuff | /wage calculaor.py | 297 | 4.40625 | 4 | #Create variables
hourly_rate = int(input("what is your hourly rate"))
hours_worked = int(input("how many hours have you worked per week"))
#Calculate wages based on hourly_rate and hours_worked
wages = hourly_rate * hours_worked
print("your wages are ${} per week" .format(wages))
| true |
d1c8e6df0c2a44e543b879dcfcee89a2f77557ba | NishadKumar/interview-prep | /dailybyte/strings/longest_substring_between_characters.py | 1,874 | 4.21875 | 4 | # Given a string, s, return the length of the longest substring between two characters that are equal.
# Note: s will only contain lowercase alphabetical characters.
# Ex: Given the following string s
# s = "bbccb", return 3 ("bcc" is length 3).
# Ex: Given the following string s
# s = "abb", return 0.
# Approach:
# To solve this problem we can leverage a hash map. Our hash map can keep track of the last index a specific character has occurred.
# We can iterate through all the characters in our string s, continuously updating a variable max_length that will hold the length of the longest
# substring we've found that occurs b/w 2 equal characters. At every iteration of our loop, we can start by first storing the current character
# that we are on within s. With the current character stored, we can now check if our hash map already contains this character. If it is, that means
# it has already occurred and therefore we can update our max_length variable to be the maximum between the current value of max_length and our current index i minus the
# index that the first occurrence of our current character occurred. If our current character is not in our map, we can place it in our map with the current
# index i that we are on. Once our loop ends, we'll have stored the longest length subarray b/w 2 equal characters in max_length and can simply return it.
def longest_substring_between_characters(s):
dictionary = {}
max_length = -1
for i in range(len(s)):
if s[i] in dictionary:
max_length = max(max_length, i - dictionary[s[i]] - 1)
else:
dictionary[s[i]] = i
return max_length
# Time Complexity:
# O(N) where N is the total number of characters in s.
# Space complexity:
# O(1) or constant since our hash map will at most grow to a size of twenty-six regardless of the size of s. | true |
649fb09854bb5c385e3eaff27302436741f09e4f | NishadKumar/interview-prep | /leetcode/1197_minimum_knight_moves/minimum_knight_moves.py | 2,147 | 4.125 | 4 | # In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].
# A knight has 8 possible moves it can make. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
# Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.
# Example 1:
# Input: x = 2, y = 1
# Output: 1
# Explanation: [0, 0] -> [2, 1]
# Example 2:
# Input: x = 5, y = 5
# Output: 4
# Explanation: [0, 0] -> [2, 1] -> [4, 2] -> [3, 4] -> [5, 5]
# Constraints:
# |x| + |y| <= 300
# Approach:
# BFS -> This problem boils down to finding shortest path from knight's origin to its destination. Dijkstra's algorithm is the most intuitive
# approach one can think of. We start by queueing the origin and explore all the initial knight's possible directions. If we reach the vertex we
# are looking for, we are done. Else, we repeat the process until we find it. Mind to have a data structure to not visit the already explored vertex.
# A set can be used for that. Also, a queue to process vertex in order helps us achieve the task.
def min_moves(x, y):
offsets = [(2,1), (2,-1), (-2,1), (-2,-1), (1,2), (-1,2), (1,-2), (-1,-2)]
def bfs(x, y):
queue = [(0, 0)]
visited = set()
steps = 0
while queue:
current_level_length = len(queue)
for i in range(current_level_length):
current_x, current_y = queue.pop(0)
if (current_x, current_y) == (x, y):
return steps
for offset_x, offset_y in offsets:
next_x, next_y = current_x + offset_x, current_y + offset_y
if (next_x, next_y) not in visited:
visited.add((next_x, next_y))
queue.append((next_x, next_y))
steps += 1
return bfs(x, y)
# Time & Space Complexity:
# If you have premium subscription on leetcode, then I would recommend reading the article by the author.
# Tests:
# python test_minimum_knight_moves.py
| true |
8cf3e9b82cd34fcd4c65339fdafb439476c7c64d | Masrt200/WoC2k19 | /enc/substitution_enc.py | 996 | 4.125 | 4 | #substitution cipher encryptor...
def substitute(plaintext):
plaintext=plaintext.upper()
_alphabet_='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
_alphabet_new_=''
keyword=input('Enter Keyword:')
keyword=(keyword.strip()).upper()
key_list=[]
for x in keyword:
ct=1
for y in key_list:
if x==y:
ct=0
break
if ct==1:
key_list.append(x)
_alphabet_new_=''.join(key_list)
for x in _alphabet_:
ct=1
for y in key_list:
if x==y:
ct=0
break
if ct==1:
_alphabet_new_+=x
print(_alphabet_+'\n'+_alphabet_new_)
ciphertext=''
for x in plaintext:
ct=0
for y in _alphabet_:
if x==y:
pos=_alphabet_.index(y)
ciphertext+=_alphabet_new_[pos]
ct=1
if ct==0:
ciphertext+=x
return ciphertext
| false |
8488da7cb5989c2785a81faf81d9ac7a849c5b0d | Marcus-Mosley/ICS3U-Unit4-02-Python | /product.py | 1,153 | 4.65625 | 5 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on October 2020
# This program finds the product of all natural numbers preceding the
# number inputted by the user (a.k.a. Factorial)
def main():
# This function finds the product of all natural numbers preceding the
# number inputted by the user (a.k.a. Factorial)
# Input
counter = 1
product = 1
natural_string = input("Enter a natural number (To Find Product 1 to N): ")
print("")
# Process & Output
try:
natural_integer = int(natural_string)
except Exception:
print("You have not inputted an integer, please input an integer"
" (natural number)!")
else:
if natural_integer <= 0:
print("You have not inputted a positive number, please input a"
" positive number!")
else:
while counter <= natural_integer:
product = product * counter
counter = counter + 1
print("The product of all natural numbers 1 to {0} is {1}"
.format(natural_integer, product))
if __name__ == "__main__":
main()
| true |
845d6abc11a2f6eae857c0bae2e466c0fdc757b5 | Ajaymagar/notes | /python/app.py | 2,055 | 4.28125 | 4 | #optional parameter tutorial
'''
def func(word, freq=3):
op = word*freq
ajay = func('ajay')
#print(ajay)
'''
#static methods
'''
class person(object):
population = 50 #class variable
def __init__(self,name ,age): # Constructor methods
self.name = name
self.age = age
@classmethod
def getpopulation(cls):
return cls.population
@staticmethod
def isadult():
return 5 > 18
def person_data(self):
print(self.name + ' ' + self.age )
ajay = person('ajay' , '55')
print(ajay.person_data())
print(person.getpopulation())
'''
#map function
'''
list_1 = [1,2,3,4,5,6,7,8]
def func(x):
return x*x
print(list(map(func,list_1)))
'''
# lambda function
'''
a = [1,2,3,4,5,6,7,8,9]
ajay = list(map(lambda x:x+5 ,a))
print(ajay)
'''
# collection module
'''
import collections
from collections import Counter
from collections import namedtuple
point = namedtuple('point','x y z')
newP = point(3,4,5)
print(newP)
'''
# deque module
'''
import collections
from collections import deque
d = deque('hello')
d.append('4')
d.append(5)
print(d)
'''
# Unpacking a sequence of tuple into variables
'''
ajay = (4,5)
x , y = ajay
#print(x)
#print(y)
s = "hello"
a , b , c ,d,e = s
'''
# unpacking elements from iterables of Arbitrary Length
# star expression in python
'''
record = ('ajay' , 'juinager' , '9594157161', '797724706')
name , adderss , *phone_numbers = record
print(phone_numbers)
'''
'''
*trailing_qtrs ,current_qtr = [10,20,30,40,50,60,70,80]
trailing_avg = sum(trailing_qtrs)/len(trailing_qtrs)
print(trailing_avg , current_qtr)
'''
#line spilliting
line2 = """ ajay magar:magarajay538,
pari shendkar : parishendkar@gmail.com
"""
line = 'noboby:*:-2:-2:unpriviledge User:/var/emapty:/usr/bin'
uname , *fields , homedir ,sh = line.split(':')
#print(uname)
#print(fields)
first_name , *last_name = line2.split(':')
#print(first_name)
#print(last_name)
record = ('ACME' , 50 , 123.45,(12,18,2012))
name , *_ , (*_ , year) = record
print(name)
print(year)
| false |
e979a01341447f6f2e566b82c92515d3b1eaadc0 | goriver/skinfosec | /DAY04/03_lambda.py | 2,461 | 4.1875 | 4 | # 람다
# • 기능을매개변수로전달하는코드를더효율적으로작성
def increase(value,original):
return original+value
original_list = [10,20,30,40,50]
print("before",original_list)
for index, value in enumerate(original_list):
original_list[index] = increase(5, value)
print("after ",original_list)
"""
# map : function을 매개변수로 받음
# filter : 두 함수는 function 매개변수에 집어넣어서 쉽게 사용 가능하다
"""
print("================매개변수에 함수 호출===============")
def increase(value):
return value+10
def decrease(value):
return value-10
original_list = [10,20,30,40,50]
print("original list",original_list)
# new_list =map(increase(), original_list) # <map object at 0x0314B058>
# print("map 실습 ",list(new_list))
def call_changedata(func,original_list): # 데이터 변수처럼 func 활용
new_list=[]
for index, value in enumerate(original_list):
new_list.append(func(value))
return new_list
print("new_list : ",call_changedata(increase,original_list))
print("new_list : ",call_changedata(decrease,original_list))
# call_changedata(increase,10)
# call_changedata(decrease,5)
print("================= map활용 ====================")
print("new_list", list(map(increase,original_list)))
print("new_list", list(map(decrease,original_list)))
print("================= lambda활용 ====================")
print("new_list", list(map(lambda value: value+10,original_list)))
print("new_list", list(map(lambda value: value-10,original_list)))
print("================= filter활용 ====================")
print("new_list", list(filter(lambda value: value<30,original_list))) # 30 미만의 값만 돌려준다
print("new_list", list(filter(lambda value: value>30,original_list))) # 30 초과의 값만 돌려준다
"""
# map 함수
내장함수
입력받은 자료형의 각 요소가 합수에 의해 수행된 결과를 묶어서 map iterator 객체로 리턴
# 문법
map(f, iterable)
# 함수(f)와 반복 가능한 (iterable) 자료형을 입력으로 받는다.
# lambda 인수1, 인수2, ... : 인수를 이용한 표현식
~> sum = lambda a, b: a+b
~> sum(3,4)
7
# filter 함수
filter(함수, literable)
두번째 인수인 반복 가능한 자료형 요소들을 첫번째 인자 함수에 하나씩 입력하여 리턴값이 참인 것만 묶어서 돌려준다.
함수의 리턴 값은 참이나 거짓이어야 한다.
"""
| false |
e7958f906c313378efd5815b81b70b4f5c45c65e | robbyhecht/Python-Data-Structures-edX | /CH9/exercise1.py | 776 | 4.15625 | 4 | # Write a program that reads the words inwords.txtand stores them askeys in a dictionary. It doesn’t matter what the values are. Then youcan use theinoperator as a fast way to check whether a string is in thedictionary.
from collections import defaultdict
f = input("Enter file name: ")
try:
content = open(f)
except:
print("File no good", f)
quit()
counts = defaultdict(lambda: 0)
# counts = dict()
for line in content:
words = line.split()
for word in words:
counts[word] += 1
# counts[word] = counts.get(word,0) + 1
def check_existance(word):
if word in counts:
print(f'Found it {counts[word]} times!')
else:
print("Didn't see it")
word_to_find = input("Look for your word: ")
check_existance(word_to_find) | true |
ac07705a2cea96a51f696c5f942adc2ee6e9796f | cosmos-sajal/ds_algo | /sliding_pattern/smallest_subarray.py | 1,478 | 4.125 | 4 | # https://www.educative.io/courses/grokking-the-coding-interview/7XMlMEQPnnQ
def get_sum_between_ptr(sum_array, i, j):
if i == 0:
return sum_array[j]
else:
return sum_array[j] - sum_array[i - 1]
def get_smallest_subarray_size(size, ptr1, ptr2):
if size > (ptr2 - ptr1 + 1):
return (ptr2 - ptr1 + 1)
else:
return size
def smallest_subarray_with_given_sum(s, arr):
_sum_array = []
_total = 0
for i in range(len(arr)):
_total += arr[i]
_sum_array.append(_total)
ptr1, ptr2, _sum = 0, 0, 0
smallest_subarray_size = len(arr) + 10
while ptr1 < len(arr) and ptr2 < len(arr):
# sum is the variable that will hold the sum between
# ptr1 and ptr2
_sum = get_sum_between_ptr(_sum_array, ptr1, ptr2)
if _sum >= s:
smallest_subarray_size = get_smallest_subarray_size(
smallest_subarray_size, ptr1, ptr2)
ptr1 += 1
else:
ptr2 += 1
if smallest_subarray_size == len(arr) + 10:
return -1
else:
return smallest_subarray_size
def main():
print("Smallest subarray length: " +
str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 3, 2])))
print("Smallest subarray length: " +
str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 8])))
print("Smallest subarray length: " +
str(smallest_subarray_with_given_sum(8, [3, 4, 1, 1, 6])))
main()
| false |
566a23e9b7633a9ce17062fad16cb1088e33e155 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec14_Numpy/numpy_practice.py | 886 | 4.1875 | 4 | """ Numpy
- Numpy is a fundamental package for scientific computing with Python.
- Official page: https://numpy.org/
- Numpy comes installed with Pandas library.
"""
import numpy
# .arange(int) created a new array with the specified int number.
n = numpy.arange(27)
print(n)
print(type(n))
print(len(n))
print("")
# creating multi-dimintion array
# .reshape() method creates a multi dimintion array
# numpy.arrange(int).reshape(numb_of_arrs, num_of_rows, num_of_columns)
new_array = numpy.arange(12)
print(new_array)
print("")
print("two dimensional array")
# two-dimintion array
two_dim_arr = new_array.reshape(3, 4)
# .reshape(rows, columns)
print(two_dim_arr)
print("")
print("three dimensional array")
# three-dimensional array
# three-dimensional array are less frequently used than two-dimensional array
three_dim = numpy.arange(24).reshape(3, 2, 4)
print(three_dim)
| true |
fdb85dd88220653054dc4127e2273885515a9c53 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec6_Basics_Proc_User_Input/string_formatting.py | 653 | 4.125 | 4 | """
String formatting in Python
- More on:
https://pyformat.info/
"""
def greet_user():
name = input('What is your name? ')
# this is the a string formatting method introduced in Python 2
return "Hello, %s!" %name.title()
# using format()
return "Hello, {}!".format(name.title)
# using f string
return f"Hello, {name.title()}!"
def user_details():
name = input('Name? ')
age = int(input('Age? '))
return 'You name is %s, and you age is %d' % (name.title(), age)
if __name__ == "__main__":
print(greet_user())
print(user_details())
print('{:_<10}'.format('test')) | true |
ebdfab2cb3cc75734d4d514005ffbb2bef50fa67 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec8_build_prog/input_problem.py | 1,092 | 4.25 | 4 | import re
# Write a program, that asks the user for input(s), until
# the user types \end
# user inputs should not include any symbols.
# return all user outputs
def inputs_problem():
inputs = list()
inputs_str = str()
interrogatives = ('how', 'what', 'why', 'where')
input_validator = re.compile(r"[\w a-z0-9']*$")
while True:
user_input = input('Type your input: ')
if input_validator.fullmatch(user_input):
if user_input.startswith(interrogatives):
inputs.append(user_input.capitalize() + '?')
else:
inputs.append(user_input.capitalize() + '.')
else:
print('Bad input format.')
print('')
continue
print
more_input = input('More input? (yes/no) ')
if more_input == 'no'.lower():
inputs_str = ' '.join(inputs)
return inputs_str
else:
continue
if __name__ == '__main__':
print(inputs_problem())
| true |
a8a7b3d0a42ddd22c88073c4df721292e0dfca76 | crampon231/ALDS | /ALDS1_1/ALDS1_1_C.py | 420 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import math
def isPrime(x):
if x == 2:
return True
if x < 2 or x % 2 == 0:
return False
for i in range(3, int(math.sqrt(x)) + 1):
if x % i == 0:
return False
return True
if __name__ == '__main__':
n = int(input())
cnt = 0
for _ in range(n):
x = int(input())
if isPrime(x):
cnt += 1
print(cnt)
| false |
a855b847eb732f4e7af1ee18c11d1c6d24e24aa3 | satfail/Python | /03_PrimerProyecto/app.py | 1,619 | 4.375 | 4 | """
--Peliculas 'a' añadir, 'l' list, 'f' buscar y 'q' salir
Tareas:
-Menu
-Añadir
-Listar
-Buscar
-Salir
"""
peliculas = []
def add_movie():
name = input("Nombre de pelicula : ")
director = input("Nombre de director : ")
año = input("Año de pelicula : ")
pelicula = {
'nombre' : name,
'director' : director,
'año' : año
}
peliculas.append(pelicula)
def listar(peliculas):
for pelicula in peliculas:
print(pelicula)
def buscar():
#año,nombre,director
buscando_por = input("Por que caracteristica estas buscando? : ")
valor_a_buscar = input(f"Valor de {buscando_por} a buscar : ")
movie = buscar_por_atributo(peliculas,valor_a_buscar, lambda x: x[buscando_por])
listar(movie)
#Generica(object, valor que quieres obtener, funcion lambda en este caso x vale el valor del campo buscado)
def buscar_por_atributo(items,expected,finder):
buscado = []
for i in items:
if finder(i) == expected:
buscado.append(i)
return buscado
def menu():
print("a(Añadir)-l(listar)-f(buscar)-q(salir)")
entrada = input("Introduzca el valor del menu : ")
while(entrada != 'q'):
if entrada == 'a':
add_movie()
elif entrada == 'l':
listar(peliculas)
elif entrada == 'f':
buscar()
elif entrada == 'q':
print("Adios!")
else:
print("Comando erroneo")
print("a(Añadir)-l(listar)-f(buscar)-q(salir)")
entrada = input("Introduzca el valor del menu : ")
menu()
| false |
567699b665fd5b526c33e31e090ac3ab1ef8c77e | fan-tian0/happy-journey | /day02.py | 1,529 | 4.21875 | 4 | #print()的用法
#1、用法
print('hello world')
name = '小小'
print(name)
#2、用法:print(name,age,gender)
age = 18
gender = 'boy'
#3、用法print(value,value,value,...sep = ' ' ,end = '\n')
print(name,age,gender) #sep(separation:分割)默认的分割是空格
print(name,age,gender,sep='_')#sep='&' sep = '%'
#print()后面默认跟两个sep(分割)空格,end(换行)\n
#转义字符:\n 换行
print('hello \n world')#每个print后面跟一个end='\n'
print('AAA',end = ' ')
print('BBB',end = ' ')
print('CCC',end = ' ')
#练习: 亲爱的xxx:
# 请点击练级激活用户:激活用户
print()
print('亲爱的xxx \n\t请点击链接激活用户:\n\t\t激活用户')
#pyton中 "''" '""' 允许双引号嵌套单引号,也允许单引号嵌套双引号
print("乔治说:'他想看小金鱼'")
print('乔治说: "他想睡觉"')
#\r:覆盖\r前内容输出\r后面的内容
print('\r hello\rworld')
# r 后面跟字符串,r后面的字符串中即使有转移字符也不会输出,但sep,end除外
print(r'hello\py\tworld',r'123\r345')#r'':rew 原样输出字符的内容,即使由转移字符也不会发生转义
print(age)
#help查看print的用法
help(print)
'''
单词:
help 帮助
Function 函数
Built-in(builtins) 内置
Module 模块
Value 置
Stream 流
denault 默认的
format 格式化
digit 数字 %d
Required 需要,必须
Raise 抛出,
''' | false |
f13e841d3a8ef2d2e46bd958811aa53409350686 | niyatigulati/Calculator.py | /calc.py | 524 | 4.125 | 4 | def calc(choice, x, y):
if (choice == 1):
add(x, y)
elif (choice == 2):
sub(x, y)
elif (choice == 3):
mul(x,y)
elif (choice == 2):
div(x,y)
# the below functions must display the output for the given arithmetic
# TODO
def add(a, b):
pass
def sub(a, b):
pass
def mul(a, b):
pass
def div(a, b):
pass
# TODO
# main function here
# Display options on what a calculator can do to perform (1 for add, 2 for sub and so on... )
# This must be in a while loop
| true |
7482d942e97a74847cbcdccf6e4809450238e845 | greenfox-velox/bizkanta | /week-04/day-03/08.py | 523 | 4.1875 | 4 | # create a 300x300 canvas.
# create a square drawing function that takes 2 parameters:
# the x and y coordinates of the square's top left corner
# and draws a 50x50 square from that point.
# draw 3 squares with that function.
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
def draw_square(x, y):
return canvas.create_rectangle(x, y, x + 50, y + 50, fill='green')
print(draw_square(20, 20))
print(draw_square(140, 40))
print(draw_square(120, 130))
root.mainloop()
| true |
a35413038dc25063fa1bda9bf93a868010510ce9 | greenfox-velox/bizkanta | /week-03/day-02/functions/39.py | 250 | 4.1875 | 4 | names = ['Zakarias', 'Hans', 'Otto', 'Ole']
# create a function that returns the shortest string
# from a list
def shortest_str(list):
short = list[0]
for i in list:
if len(i) < len(short):
short = i
return short
print(shortest_str(names))
| true |
0c1cedbaa3a31450caae59fd00de54f21f2da412 | greenfox-velox/bizkanta | /week-04/day-04/09.py | 329 | 4.125 | 4 | # 9. Given a string, compute recursively a new string where all the
# adjacent chars are now separated by a "*".
def separated_chars_with_stars(string):
if len(string) < 2:
return string[0]
else:
return string[0] + '*' + separated_chars_with_stars(string[1:])
print(separated_chars_with_stars('table'))
| true |
055b1173cbe0bc9a383f8863016bdf26b1285a00 | choogiesaur/codebits | /data-structures/py-trie.py | 1,350 | 4.21875 | 4 | # Implement a version of a Trie where words are terminated with '*'
# Efficient space complexity vs hashtable
# Acceptable time complexity. O(Key_Length) for insert/find
# Handle edge cases:
# - Empty String
# - Contains non alphabet characters (numbers or symbols)
# - Case sensitivity
class StarTrie:
# Each node has a dictionary of its children
head = {}
def add(self, word):
curr = self.head
for ch in word:
if ch not in curr:
# Make a new children dict
curr[ch] = {}
# Traverse downward
curr = curr[ch]
# Terminate word by storing '*' as a child
curr['*'] = {}
def search(self, word):
curr = self.head
for ch in word:
if ch not in curr:
return False
curr = curr[ch]
if '*' not in curr:
return False
else:
return True
my_trie = StarTrie()
test_str = "hello welcome to hell have some jello"
for word in test_str.split():
my_trie.add(word)
print(my_trie.head)
print(my_trie.search('hello'))
print(my_trie.search('hell'))
print(my_trie.search('hel'))
print(my_trie.search('welcome'))
print(my_trie.search('jello'))
print(my_trie.search(''))
my_trie.add('')
print(my_trie.search(''))
| true |
406bbf1479e8c0bf119b566e4aab895ecdbc01e8 | choogiesaur/codebits | /data-structures/py-stack.py | 1,319 | 4.28125 | 4 | ### A Python implementation of a Stack data structure
class PyStack:
# Internal class for items in stack
class StackNode:
def __init__(self, val = 0, child = None):
self.val = val
self.child = child
# Check if stack has items
def is_empty(self):
return self.size() == 0
# Get number of items in stack
def get_size(self):
return self.size
# View topmost item without modifying stack
def peek(self):
if self.is_empty():
print("Nothing left in stack.")
else:
return self.head.val
# Remove topmost item and return its value (modifies stack)
def pop(self):
if self.is_empty():
print("Nothing left in stack.")
else:
popped_val = self.head.val
self.head = self.head.child
self.size -= 1
return popped_val
# Add item x to top of stack
def push(self, x):
# Temp node for what we are inserting
new_node = self.StackNode(x, self.head)
self.head = new_node
self.size += 1
# Constructor
def __init__(self):
self.head = None
self.size = 0
### Testing code
my_stack = PyStack()
print(my_stack.get_size())
# Push 1
my_stack.push(1)
print(my_stack.get_size())
print(my_stack.peek())
# Push 4
my_stack.push(4)
print(my_stack.get_size())
print(my_stack.peek())
# Pop 4
my_stack.pop()
print(my_stack.peek())
# Pop 1
my_stack.pop()
print(my_stack.peek())
| true |
7513472d24d6090efd5a3c9def621a59b41405ab | jchavez2/COEN-144-Computer-Graphics | /Jason_C_Assigment1/assignment1P2.py | 1,936 | 4.21875 | 4 | #Author: Jason Chavez
#File: assignment1P2.py
#Description: This file rasters a circle using Bresenham's algorithm.
#This is taken a step further by not only rastering the circle but also filling the circle
#The file is saved as an image and displayed using the computers perfered photo drawing software.
from PIL import Image
import webbrowser #Necessary for Windows to open in Paint
filename = "CircleFill.png"
img= Image.new('RGB', (320, 240))
pixels= img.load()
#Intialize Varibles:
R = 50
d = (5/4) - R
x = 0
y = R
xc = 160
yc = 120
#Function to fill circle
def circleFill(xc,yc,x,y):
#Run loop to fill in pixels on y-axis
i = yc - y
while i < (yc + y):
i += 1
pixels[(xc + x), i] = (255,0,0)
pixels[(xc - x), i] = (255,0,0)
#Run loop to fill in pixels x-axis
i = xc - y
while i < (xc + y):
i+=1
pixels[i, (yc + x)] = (255,0,0)
pixels[i, (yc - x)] = (255,0,0)
#Function to call to draw circle:
def drawEdgeCircle(xc,yc,x,y):
#Intialize 8-Coordinates and alternate signs (with line fill)
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
x = -x
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
y = -y
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
x = -x
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
#Algorithum
circleFill(xc,yc,x,y)
drawEdgeCircle(xc,yc,x,y)
while y >= x:
if d < 0:
d += 2 * x + 3
x+=1
else:
d += 2 * (x - y) + 5
x+=1
y-=1
circleFill(xc,yc,x,y)
drawEdgeCircle(xc,yc,x,y)
#Commented out the show function since it does no work for windows systems
#img.show()
#Using the save() function as a subsustuite to display image along with the webbrowser.open() function.
img.save(filename)
webbrowser.open(filename)
| true |
dc9d95ec63607bec79a790a0e0e898bebe9998bc | nisarggurjar/ITE_JUNE | /ListIndex.py | 559 | 4.1875 | 4 | # Accessing List Of Items
li = ["a", 'b', 'c', 'd', 'e', 'f', 'g']
# index
print(li[2])
# Slicing
print(li[2:5]) # <LIST_NAME>[starting_index : ending_index] ==> ending_index = index(last_value) + 1
# stepping (Index Difference)
print(li[::2]) # <LIST_NAME>[starting_index : ending_index : index_difference]
# Negative Indexing
li1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(li1[-1])
print(li1[-4])
# from given list print all odd numbers
print(li1[::2])
# print list of even elements from the given list in reverse
print(li1[-2::-2]) | true |
330ffa3c0f75a1fae5d7af3d0597ccb7d1286de1 | nisarggurjar/ITE_JUNE | /ConditionalStatements.py | 2,228 | 4.21875 | 4 | # if
# if else
# elif
'''
rain = False
# if --> single condition
if rain == True:
print("I will take a leave")
# if else
if rain == True:
print("I will take a leave")
else:
print("I will go to office")
# if else
sunny = False
if rain:
print("I will take a leave")
elif sunny:
print("I will go to office")
else:
print("I will go for a movie show")
'''
# nested if
# WAP in python to satisfy given conditions
# take input from user for gender and age
# condition 1 : age >= 16 if gender is female
# condition 2 : age >= 18 if gender is male
age = int(input("Enter your age: "))
gender = input("Enter your gender: ") # f for females and m for males
if age >= 16:
if gender == 'f':
print("Eligible for vote")
elif gender == 'm':
print("Not eligible for vote")
else:
print("Enter a valid gender")
elif age >= 18 and (gender == 'm' or gender == 'f'):
print("Eligible for vote")
else:
print("Not eligible for vote")
'''
if age>=16 and gender == 'f':
print("Eligible for vote")
elif age>=18 and (gender == 'm' or gender == 'f'):
print("Eligible for vote")
else:
print("Not eligible for vote")
'''
'''
if age>=16 and gender is 'f':
print("Eligible for vote")
elif age>=18 and (gender is 'm' or gender is 'f'):
print("Eligible for vote")
else:
print("Not eligible for vote")'''
# != -----> is not
'''
if age >= 16:
if gender == 'f':
print("Eligible for vote")
elif gender == 'm':
print("Not eligible for vote")
else:
print("Enter a valid gender")
elif age >= 18 and (gender is 'm' or gender is 'f'):
print("Eligible for vote")
elif (gender is not 'f') or (gender is not 'm'):
print("Enter a valid gender")
else:
print("Not eligible for vote")
# Ambiguity ---> delima (confusion) ---> Absurd
# in C or Cpp --> print initialized variable ----> garbage ---> Absurd
'''
#
#num = 10
#
#if num is not 10:
# print("hello")
#else:
# print("Bye")
# Comparision Operators
# conditional Statements
# nested conditional statements
# logical operators
# use of is and not
# Short Hand Conditional Statement
num = -8
print("Positive") if num>0 else print("Negative") # ? : | false |
a714402ef8921b97870d62f24222575ba39fc5cb | Wakarende/chat | /app/main/helpers.py | 1,230 | 4.1875 | 4 | def first(iterable, default = None, condition = lambda x: True):
"""
Returns the first item in the `iterable` that
satisfies the `condition`.
If the condition is not given, returns the first item of
the iterable.
If the `default` argument is given and the iterable is empty,
or if it has no items matching the condition, the `default` argument
is returned if it matches the condition.
The `default` argument being None is the same as it not being given.
Raises `StopIteration` if no item satisfying the condition is found
and default is not given or doesn't satisfy the condition.
>>> first( (1,2,3), condition=lambda x: x % 2 == 0)
2
>>> first(range(3, 100))
3
>>> first( () )
Traceback (most recent call last):
...
StopIteration
>>> first([], default=1)
1
>>> first([], default=1, condition=lambda x: x % 2 == 0)
Traceback (most recent call last):
...
StopIteration
>>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
Traceback (most recent call last):
...
StopIteration
"""
try:
return next(x for x in iterable if condition(x))
except StopIteration:
if default is not None and condition(default):
return default
else:
raise
| true |
cb8a0d965ca2b62c8b50e54621e50f524366727d | tcaserza/coding-practice | /daily_coding_problem_20.py | 1,003 | 4.125 | 4 | # Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
#
# For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
#
# In this example, assume nodes with the same value are the exact same node objects.
#
# Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
class LinkedList:
def __init__(self, value, nextnode=None):
self.value = value
self.nextnode = nextnode
def find_intersection(node1,node2):
list1 = set()
while node1.nextnode is not None:
list1.add(node1.value)
node1 = node1.nextnode
while node2.nextnode is not None:
if node2.value in list1:
return node2.value
node2 = node2.nextnode
return None
list1 = LinkedList(3,LinkedList(7,LinkedList(8,LinkedList(10))))
list2 = LinkedList(99,LinkedList(1,LinkedList(8,LinkedList(10))))
print find_intersection(list1,list2) | true |
3b5e97f33277ee345b584501f9495e4f38c0b0e6 | tcaserza/coding-practice | /daily_coding_problem_12.py | 882 | 4.375 | 4 | # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
# Given N, write a function that returns the number of unique ways you can climb the staircase.
# The order of the steps matters.
#
# For example, if N is 4, then there are 5 unique ways:
#
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# 2, 2
# What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of
# positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
def num_ways(steps,allowed_steps):
ways = 0
if steps in known_ways:
return known_ways[steps]
for i in allowed_steps:
if steps > i:
ways += num_ways(steps-i,allowed_steps)
if steps == i:
ways += 1
known_ways[steps] = ways
return ways
known_ways = {}
print num_ways(4,[1,2,3]) | true |
4fbb7f1164e0e80689ac64a1f3a34d7e5c6f2f5b | tcaserza/coding-practice | /daily_coding_problem_18.py | 702 | 4.1875 | 4 | # Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of
# each subarray of length k.
#
# For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:
#
# 10 = max(10, 5, 2)
# 7 = max(5, 2, 7)
# 8 = max(2, 7, 8)
# 8 = max(7, 8, 7)
# Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results.
# You can simply print them out as you compute them.
def find_max(array,k):
max_vals = []
for i in range(len(array) - k + 1):
sub_array = array[i:i+k]
max_vals.append(max(sub_array))
print max_vals
find_max([10, 5, 2, 7, 8, 7],3)
| true |
1f76f9b05ec4a73c36583154bc431bd3746f659e | cseharshit/Registration_Form_Tkinter | /registration_form.py | 2,786 | 4.28125 | 4 | '''
This program demonstrates the use of Tkinter library.
This is a simple registration form that stores the entries in an sqlite3 database
Author: Harshit Jain
'''
from tkinter import *
import sqlite3
#root is the root of the Tkinter widget
root = Tk()
#geometry is used to set the dimensions of the window
root.geometry('550x580')
#title shows the title of the Tkinter window
root.title("Employee Form")
Name=StringVar() #Tkinter module to store strings
Email=StringVar()
Designation=StringVar()
Gender = IntVar()
Languages=IntVar()
def database():
name=Name.get()
email=Email.get()
designation=Designation.get()
gender=Gender.get()
languages=Languages.get()
# lang=Favorite_Language.get()
connection = sqlite3.connect('Form.db') #Connection instance
with connection:
cursor=connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS Employee (Name TEXT, Email TEXT, Designation TEXT, Gender TEXT,Languages TEXT)')
cursor.execute('INSERT INTO Employee (Name,Email,Designation,Gender,Languages) VALUES(?,?,?,?,?)',(name,email,designation,gender,languages))
connection.commit()
exit()
label_title = Label(root, text="Employee form",width=20,font=("bold", 30))
label_title.place(x=35,y=53)
label_name = Label(root, text="Name",width=20,font=("bold", 13))
label_name.place(x=40,y=130)
entry_box_name = Entry(root,textvar=Name)
entry_box_name.place(x=240,y=130)
label_email = Label(root, text="Email",width=20,font=("bold", 13))
label_email.place(x=40,y=180)
entry_box_email = Entry(root,textvar=Email)
entry_box_email.place(x=240,y=180)
label_gender = Label(root, text="Gender",width=20,font=("bold", 13))
label_gender.place(x=40,y=230)
var=IntVar()
Radiobutton(root, text="Male",padx = 5, variable=var, value=1).place(x=235,y=230)
Radiobutton(root, text="Female",padx = 5, variable=var, value=2).place(x=235,y=250)
label_designation = Label(root, text="Designation",width=20,font=("bold", 13))
label_designation.place(x=40,y=280)
designation_list = ['Software Developer','Software Intern','Software Tester','HR Manager','Business Development Manager']
droplist=OptionMenu(root,Designation, *designation_list)
droplist.config(width=15)
Designation.set('Choose Designation')
droplist.place(x=240,y=280)
label_languages = Label(root, text="Languages Known",width=20,font=("bold", 13))
label_languages.place(x=40,y=330)
english_var= IntVar()
hindi_var=IntVar()
french_var=IntVar()
Checkbutton(root, text="English", variable=english_var).place(x=235,y=330)
Checkbutton(root, text="Hindi", variable=hindi_var).place(x=235,y=350)
Checkbutton(root, text="French", variable=french_var).place(x=235,y=370)
Button(root, text='Submit',width=20,bg='green',fg='white',command=database).place(x=180,y=410)
root.mainloop()
| true |
0a121ab2cf53f4696a7ec57311ff0017549023ea | khushboo2243/Object-Oriented-Python | /Python_OOP_1.py | 1,850 | 4.46875 | 4 | #classes aallows logially grouping of data and functions in a way that's easy to resue
#and also to build upon if need be.
#data and functions asscoaited with a specific class are called attributes and methods
#mathods-> a function associated with class
class Employee: #each employee will have specific attributes (names, email, role)
#pass #when you don't want to keep a class empty, write pass
def __init__(self,first, last, pay): #this method can be seen as initialize or a constructor. When a method is created
self.first=first #inside a class they ereceive the instance as first argument. By convention, the instance
self.last=last #is called self.
self.pay=pay
self.email=first + '.'+ last +'@company.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
emp_1 = Employee('Corey','Schafer','5000') #each of these employees are instances of class employee. emp_1 is passed as the self argument.
emp_2 = Employee('Test','User','6000') #both of these employee objects have different locations in memory.
'''print(emp_1)
print(emp_2)
emp_1.first='Corey' #the long method of allocating values for each attribute of an instance. defininf these attributes
emp_1.last='Schafer' inside the class simplifies the process and lessens the amount of code.
emp_1.email='Corey.Schafer@company.com'
emp_1.pay= 5000
emp_2.first='Test'
emp_2.last='User'
emp_2.email='Test.User@company.com'
emp_2.pay= 6000'''
print(emp_1.email)
print(emp_2.email)
print (emp_1.fullname()) #when a method fir full name is defined inside the class.
#print('{} {}'.format(emp_1.first,emp_1.last)) #when a method is not present for full name.
print(Employee.fullname(emp_1))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.