blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
347940de62058edc0a229ebd819349c6fed1dbe4 | satwik3011/my_python | /test.py | 5,091 | 4.09375 | 4 | '''
#Removing spaces from string
getString = input('Enter string for action: ')
#Removing spaces from left
print(getString.lstrip(), 'has length: ', len(getString.lstrip()))
#Removing spaces from right
print(getString.rstrip(), 'has length: ', len(getString.rstrip()))
#Removing all spaces
print(getString.strip(), '... |
77530c893fa0782d3849a2e9137e19ca2aa914b6 | github-felipe/ExerciciosEmPython-cursoemvideo | /PythonExercicios/ex095.py | 1,402 | 3.671875 | 4 | jogador = dict()
listaGols = list()
cadastros = list()
while True:
totgols = 0
print('-' * 20)
nome = str(input('Nome: '))
quant = int(input(f'Quantos jogos {nome} jogou? '))
jogador['nome'] = nome
for jogo in range(1, quant+1):
gols = int(input(f'Gols feitos no {jogo}º jogo: '))
... |
34f0cc3361aa98ab434313e1905e4db42340024a | alanazip/market | /Mercado/projetoFinal.py | 708 | 3.6875 | 4 | produto = []
numero = []
preco = []
print('''<<< Cadastro de produtos - digite exit para sair >>>''')
produto.append(str (input("Nome do Produto: \n")))
numero.append((int(input("Número de série: \n"))))
preco.append((float(input("Valor R$: \n"))))
if produto or numero or preco == "exit":
print("Nome do produto",pr... |
e7fb96b620814487a1078ab7be99115ed91ccf03 | nicob825/Bruno_Nico | /Lesson_09/lesson_09.py | 62 | 3.546875 | 4 | myList = [1, 2, 3, 4, 5]
print(myList[2])
print(myList[:2])
|
36aa32ee37554a7858e1abb629fa66fef56e8a31 | TSLNIHAOGIT/gene | /geatpy_example/frame/shortest_path/bfs.py | 734 | 3.75 | 4 | import queue
import random
def bfs(adj, start):
visited = set()
q = queue.Queue()
q.put(start) # 把起始点放入队列
while not q.empty():
u = q.get()
print('u',u)
# print('adj.get(u, [])',adj.get(u, []))
a=adj.get(u, [])
random.shuffle(a)
print('a', a)
f... |
f59d8a2c6248a983cc08de4302e520e1f2ad52e9 | H-huihui/Python_work | /programming project2/project2.py | 1,322 | 4.125 | 4 | def checkTile(tile, number):
#YOUR CODE HERE
#always return false when tile is invalid
if tile<1 or tile>12:
return False
if number == "one":
if tile%3 == 0:
return True
else:
return False
if number == "two":
if tile <=3 or tile==5 or tile==7 or... |
2832553e8a27962fde03710e13d72331730a152c | thenowrrock/parcial_electiva_02 | /punto2.py | 1,735 | 4.1875 | 4 | #Autores Juan David Jimenez
'''
•Escriba un programa en python que utilizando
expresiones lambda devuelva los números de la
siguiente serie:
(2n)!
(n + 1)!n!
•Para generar los n números a calcular en la serie,
utilice una función generadora de números
enteros mayores a 0.
•Punt... |
17fefe9501c33240dbcaa7a926a31a1aa46258eb | mshahpazova/Python-course-solutions | /week2_solutions/reduce_file_path.py | 502 | 3.6875 | 4 | import os
import sys
def reduce_file_path(file_path):
splitted_path = file_path.split('/')
cleared_path = list(filter(lambda x: x != '' and x != '.', splitted_path))
reduced_path = []
for element in cleared_path:
if element == '..':
reduced_path.pop()
else:
reduce... |
36ddb9ca7d5a8260300f66b6f406e1af8e476e80 | Dutch-Man/Company | /MyTest/python/bbb.py | 729 | 3.859375 | 4 | #!/usr/bin/python
#coding:utf-8
class Test():
val1 = 1
def __init__(self):
val2 = 2
self.val3 = 3
def fun(self):
Test.val1 += 1
'''
def show(self):
print "m = %d"%m
print "n = %d"%n
'''
def main():
print "Test.val1 = %d"%Test.val1
test1 = Test()
... |
86a7f7011e2279110340d19cecc38a1f6dd1d3af | a-recknagel/auxtest | /src/auxtest/checks/check_funcs.py | 4,657 | 3.53125 | 4 | """Collection of check functions that can be called in the check-route.
Right now their names are equal to the names of their return keys, so we might
chose to streamline some of the logic to make this very configurable. It would
nail this app to only support keyword arguments that conform to python's
function naming ... |
ba9cf37cf27421edd4ca63e107ec217d7dc4707e | AymanMagdy/hands-on-python | /tuples/add_to_tuple.py | 348 | 4.25 | 4 | # Write a func to add an element to a tuple.
def add_to_tuple(tupleElements, newElement):
resultTuple = (*tupleElements, newElement)
return resultTuple
if __name__ == "__main__":
testTuple = ('ayman', 45 )
newValue = input("Enter a new value to add to tuple: ")
newTuple = add_to_tuple(testTuple, n... |
3af2281f7abc520c7b1794093dc7b7e0e793239a | AnshulRoonwal/2.Artificial-Intelligence | /3) Sudoku Solver/ReadGameState.py | 2,136 | 3.6875 | 4 | __author__ = 'Anshul/Aditi'
class ReadGameState:
def __init__(self):
self.board = []
self.AllEmptyPositions = []
def readGameState(self, filePath): #New Function for reading game state
#Reading file
fileHandle = open(filePath, 'r')
rawState = fileHandle.readline().s... |
1b1065a24baf626d25eba8c75d63dd3c77aa261a | deniscarr/pands-problem-set | /primes.py | 436 | 4.28125 | 4 | # Program Name: primes.py
# Programmer: Denis Carr
# Date: March 2019
# request user for positive number - convert it to int and store in variable number
number = int(input("Please enter a positive integer: "))
# loop from 2 to number -1
for i in range(2,number):
# if number is divisible, it is not prime
if ... |
387b400fc2bae91b0fc545770b5f4eae7fa54a2b | k-jinwoo/python | /Ch02/2_4_String.py | 1,437 | 4 | 4 | """
날짜 : 2021/04/26
이름 : 김진우
내용 : 파이썬 String 예제 교재 p48
"""
# 문자열 더하기
str1 = 'Hello'
str2 = "Python"
str3 = str1 + str2
print('str3 :', str3)
# 문자열 곱하기
name = '홍길동'
print('name * 3 :', name *3)
# 문자열 길이
msg = 'Hello World'
print('msg 길이 :', len(msg))
# 문자열 인덱스
print('msg 1번째 문자 :', msg[0])
print('msg 7번째 문자 :', msg[... |
675e446eb31505faf8d2597366b968a300463ce4 | josivantarcio/Desafios-em-Python | /Desafios/desafio067.py | 226 | 3.734375 | 4 | n = int(input('Digite um numero: '))
i = 0
while n >= 0:
while True:
print(f'{i} x {n} = {i * n}')
i += 1
if i > 10:
break
i = 0
n = int(input('Digite um numero: '))
print('FIM') |
63d00e8e67d33eb7df8b48c8ccd662993e30ec60 | sidv/Assignments | /Bijith/Aug23/filter_3first.py | 126 | 3.984375 | 4 | print("Filter first 3 letter from the given list .")
lst = ["Siddhant", "Pavan", "Ramya", "Raja"]
print([x[:3] for x in lst])
|
b79c8b3bb5146844ce57f73725a590c1948bd265 | SGTAn0nY/hashing_utilities | /dict_attack.py | 3,262 | 3.890625 | 4 | import random, hashlib
from string import ascii_letters
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
length = 4
def menu():
print("Dictionary attacks!")
print("ATTENTION:")
print(">> Change 'length' for different data length <<")
operation = str(input("what do you want to do ?\n1 --- Initial... |
6840627bd389da023df6c83755672ae5eb43db18 | Qondor/Python-Daily-Challenge | /Daily Challenges/Daily Challenge #95 - CamelCase Method/camel.py | 355 | 4.5 | 4 | def camelcase(input_text):
"""Camel Case text generator.
All words must have their first letter capitalized without spaces.
"""
words = input_text.split()
result = ""
for word in words:
result += f'{word[0].upper()}{word[1:]}'
return result
if __name__ == "__main__":
print(cam... |
3cf129e610ef2574f9e601b144eac1478555211b | atfelix/exercism-python | /collatz-conjecture/collatz_conjecture.py | 298 | 3.90625 | 4 | from functools import reduce
def collatz_steps(number):
if number <= 0:
raise ValueError('Invalid argument: number > 0 is required')
count = 0
while number != 1:
count += 1
number = number // 2 if number % 2 == 0 else 3 * number + 1
return count
|
64892f26ca721b09de7af70cd2d6a7f681b489d7 | evac/MachineProgrammer | /main/algorithms.py | 861 | 3.515625 | 4 | import random
def mutate(program):
if len(program[:]) > 1:
temp = program[:]
random.shuffle(temp)
program[:] = temp
return program
def merge(prog1, prog2):
prog1[:] = prog1 + prog2
return prog1
def multiply(prog1, prog2):
prog1[:], prog2[:] = prog1 + prog2, prog2 + prog1
... |
39bbbb555d9aac26f42302766de3ea6d71c0df50 | pangguoping/python-study | /day7/xml-test.py | 1,187 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
'''
from xml.etree import ElementTree as ET
tree = ET.parse('xo.xml')
root = tree.getroot()
print(root)
for child in root:
print(child)
print(child.tag,child.attrib)
for gradechild in child:
#print(gradechild)
print(gradec... |
0e3b0f05aaff1524f927a326d3673c07e0b33646 | arvakagdi/UdacityNanodegree | /Stacks/Postfix.py | 2,395 | 4.0625 | 4 | '''
Goal : Given a postfix expression as input, evaluate and return the correct final answer.
Input: List containing the postfix expression
Output: int: Postfix expression solution
Example: 3 1 + 4 *
Solution: (3 + 1) * 4 = 16
'''
class LinkedListNode:
def __init__(self, data):
self.data = da... |
9febea3cef5239ca48a272f740b6438c0988bac3 | m-hegyi/stocker | /classes/MovingAverage.py | 2,491 | 3.671875 | 4 | from classes.Stock import Stock
class MovingAverage():
prev = 0
prevLow = 0
prevHigh = 0
def __init__(self, lower, higher, Stock: Stock):
self.lower = lower
self.higher = higher
self.Stock = Stock
def getLowerValueByDate(self, date):
# az első átlag kiszámítása... |
1ad21e5d085c7b00e36496a8c0bc2ec799ccf301 | AlexHahnPublic/EulerProblems | /problem7_10001stPrime.py | 1,363 | 3.71875 | 4 | # Euler Problem 7:
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
# that the 6th prime number is 13.
# What is the 10001st prime number?
#Solution, Off the top of my head we could either greedily use trial division
# or more efficiently use a sieve (Sieve of Eratosthenes)
# Using the co... |
20cb42f4569ae2d1475dfefc332a2635e0f3579b | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sieve/d70734ec439f425e9c842157ef2262b5.py | 254 | 3.65625 | 4 | def sieve(limit):
numbers = range(2, limit + 1)
not_primes = []
for number in numbers:
for multiple in xrange(number + number, limit +1, number):
not_primes.append(multiple)
return list(set(numbers) ^ set(not_primes))
|
b7de7500178457bd40eff94e63cc23e673f31b3e | navaneeth-rajagopalan/Algorithms-and-Data-Structures | /Tree/Test.py | 1,215 | 3.859375 | 4 | import BinarySearchTree
my_bst = BinarySearchTree.Tree()
my_bst.add(11)
my_bst.add(6)
my_bst.add(8)
my_bst.add(3)
my_bst.add(15)
my_bst.add(13)
my_bst.add(17)
my_bst.add(19)
my_bst.add(14)
my_bst.add(12)
my_bst.add(3)
my_bst.add(1)
my_bst.add(5)
ordered_tree = my_bst.traverse(BinarySearchTree.TreeTraversalOrder.IN_OR... |
b01f947373fef89cea302a1fe27707786798950e | iswetha522/Plural_Sight | /corepy/shallow_and_deep_copy.py | 294 | 4.125 | 4 | a = [[1, 2], [3, 4]]
b = a[:]
print(a is b)
print( a == b)
print("------------")
print(a[0])
print(b[0])
print(a[0] is b[0])
print("----------")
a[0] = [8, 9]
print(a[0])
print(b[0])
print("----------")
a[1].append(5)
print(a[1])
print(b[1])
print("------")
print(a)
print(b)
print('-------')
|
b17a9c1c7d19acdf93befb1f536690336fc96186 | cbymar/pyspark-databricks | /mllib00.py | 1,311 | 3.5625 | 4 | import math
import numpy as np
# http://spark.apache.org/docs/latest/ml-guide.html
### Quick aside on entropy/information gain
def entropy(lst):
entropysum = 0
for _ in lst:
entropysum += _ * np.log2(_)
return -1 * entropysum
lst = [0.25, 0.75]
entropy(lst) # this is our baseline entropy, which is... |
67b5f8aec76efd743e50dbe324ac3564bac99ef7 | nuxion/python_2021_thu | /exercises/301.py | 943 | 3.828125 | 4 | """
Siguiendo el ejemplo del ejercicio 301, guardar estos valores en una tabla de sqlite3:
2020-04-08;95.5;140.0,44.5
2020-04-09;95.5;140.0,43.5
Cada columna significa lo siguiente:
fecha;dolar_blue;dolar_oficial;diferencia
Como ayuda uno de los lugares donde se puede tomar informacion es de:
https://... |
cc9df3a4b3bd61d3afda75cac49e14555e72b12b | rohitx/DS_and_Algo_in_Python | /Chapter3/R_3_4.py | 409 | 3.84375 | 4 | '''
R-3.4: Give an example of a function that is plotted the same on a log-log scale
as it is on the standard scale.
Answer: the linear function: f(n) = n is an example of a function that is the
same on a log-log scale and on the standard scale.
'''
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0... |
acf7461cbc23e1fc7ea0cd86f331a2c2822ab7d3 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/djgway001/mymath.py | 334 | 3.65625 | 4 | #calculate number of k-permutations of n items
#wayne de jager
#15 april 2014
def get_integer(n):
s=input("Enter "+n+":\n")
while not s.isdigit():
s=input("Enter "+n+":\n")
n=eval(s)
return n
def calc_factorial(n):
factorial=1
for i in range(1,n+1):
factorial*=i... |
9f4739372dbf2806999b5b898b3bed07ff66dfea | nonatalies/second_one | /1.py | 272 | 4.0625 | 4 | name = input('Введите имя: ')
surname = input('Введите фамилию: ')
birth = int(input('Введите год рождения: '))
print(name, surname, birth, sep = '_')
name, surname = surname, name
print(name, surname, birth + 60, sep = '_')
|
d30c731283a81dfa66c95971f44909e0b919c212 | omatveyuk/interview | /HackerRank/bigger_is_greater.py | 1,984 | 4.15625 | 4 | """Given a word W, rearrange the letters of W to construct another word S in such
a way that S is lexicographically greater than W. In case of multiple possible
answers, find the lexicographically smallest one among them.
>>> bigger_is_greater('ab')
'ba'
>>> bigger_is_greater('bb')
'no answer'
>... |
1d0a441ebf6eb3ee04f8c5fbfcf7921510864cb3 | maxwell-martin/txst-cis3389-spring2020 | /class_practice/on_campus/10_dictionaries_03042020.py | 1,983 | 4.34375 | 4 | # Dictionaries
# Create a dictionary
Dic1 = { 1:34, 2:45, 3:89 }
print(Dic1)
# Get value from dictionary
print(Dic1[2])
print(Dic1.get(2))
# Error thrown when key does not exist
#print(Dic1[4])
# No error thrown when key does not exist; returns None instead
print(Dic1.get(4))
print(Dic1.get(4, "Default message"))
... |
79f6b69a7a32844df700de3a2ae02bb5c72fd357 | Vakonda-River/Stanislav | /lesson3_4_0.py | 291 | 4.125 | 4 | #x^(-y)=1/x^y
x_1 = float(input('Введите действительное положительное число: '))
y_1 = int(input('Введите целое отрицательное число: '))
def step(x,y):
res = x ** y
return (res)
print(step(x_1,y_1))
|
8e05628afd61456dc02449fcb543cbe6162eaf26 | crisgrim/python-oop | /Kata3-Student.py | 1,974 | 3.90625 | 4 | class Student():
# Properties
name = ''
last_name = ''
dni = ''
age = 0
subjects = []
# Constructor
def __init__(self, name, last_name, dni, age):
self.name = name
self.last_name = last_name
self.dni = dni
self.age = age
# Methods
def greet(self)... |
a36714242e5be77a93e8734b0c5e29df5b662dad | soumyaevan/PythonProgramming | /CodeSignal/FixMessage.py | 209 | 3.6875 | 4 | """
Implement a function that will change the very first symbol of the given message to uppercase,
and make all the other letters lowercase.
"""
def fixMessage(message):
return message.lower().capitalize() |
4ecc50191ded5b9cfdfd8bf3b415e0604ea17739 | swalgocoder/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py~ | 158 | 3.78125 | 4 | #!/usr/bin/python3
"""
Read a text file (UTF8) and prints it to stdout.
"""
def read_file(filename=""):
print((open(filename, 'r').read()), end="")
|
b715e6c5e2de0d5daf4eeface1b8aa9b1b9a3263 | AnandD007/Amazing-Python-Scripts | /Restoring-Divider/script.py | 3,750 | 3.78125 | 4 | def main():
A = ""
Q = int(input("Enter the Dividend => "))
M = int(input("Enter the Divisor => "))
Q = bin(Q).replace("0b", "")
M = bin(M).replace("0b", "")
size = 0
"""
This part makes the initialisation of required for the Restoring Division to occur.
Which includes:
1) Settin... |
afcaaff5b072d1b3ec4829aa9034f5d32019b839 | MrBean1512/bioinformatics_collection | /32_code.py | 855 | 3.578125 | 4 | # open a file to get the input
file = open("32_input.txt", 'r')
lines = []
for line in file:
lines.append("{}".format(line.strip()))
file.close()
k = int(lines[0])
dna = lines[1]
def deBruijnGraph(k, dna):
#this is the main function
kDict = {}
for i in range(0, len(dna) - k + 1):
print(dna[i:i... |
768729b88ecdd415555fdc5d45a8d48db10d4a51 | OlgaLevshina/BL_Python | /homework_1/task_2.py | 529 | 4.375 | 4 | # 2. Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк. '''
second = str()
while second.isdigit() == False:
second = input("Введите время в секундах ")
second = int(second)
h = second//3600
m = (second % 3600)//60
s =... |
1a887c9e1c06f2e3c1c4a8833d7de31f56b79d0f | MarthaSamuel/foundation | /palindromic.py | 593 | 4.28125 | 4 | # Author: Dimgba Martha O
# @martha_samuel_
# 35 this code checks if a string is palindromic. Spaces and letters are ignored.
# A palindrome is a string that can be equally read from left to right or right to left,
# omitting blank spaces, and ignoring capitalization
def palindrome(input_string):
new_string = inp... |
812b8c29ab1c6ebc96b6a8ab6157639ae184b591 | JackieBinya/Bootcamp_ | /Prime-numbers/prime_numbers_list.py | 437 | 4.09375 | 4 | def primes(n): #creates a function primes
prime = [] #initializes the list
if type(n) is int: #only takes integers
if n < 2: #n starts from 2
return []
elif n > 1:
for num in range(2, n+1): # from 0 to n
if all(num % i != 0 for i in range(2, num)):
prime.append(num)
... |
cda43b29ee498693446f2a64245c4c350dd09318 | ayushchauhan09/My-Codes | /Codes/Python/Two-vs-Ten.py | 165 | 3.625 | 4 | T = int(input())
for _ in range(T):
num = int(input())
if num%10==0:
print(0)
elif num%5==0:
print(1)
else:
print(-1) |
a558f1376e5dc4e5f58e2de1dc03d4433239b5d5 | zhjw8086/MagikCode | /第二季/Turtle_project/house.py | 404 | 3.546875 | 4 | import turtle
import time
t = turtle.Pen()
t.color('green','red')
t.hideturtle()
t.begin_fill()
for x in range(3):
t.forward(100)
t.left(180-60)
t.forward(10)
t.right(90)
t.end_fill()
t.color('green','brown')
t.begin_fill()
for x in range(3):
t.forward(80)
t.left(90)
t.end_fill()
t.penup()
t.goto(30,-8... |
26083a8ecb1611301d329536516c2c4ba9b6e9fd | LuccasTraumer/pythonRepositorio | /CursoPython/Exercicios/Ex034.py | 597 | 3.890625 | 4 | '''Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento.
Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%'''
salar = float(input('Digite o Salário R$: '))
calc15 = (salar*15)/100
calc10 = (salar*10)/100
if salar ... |
189824b9b04c087071c07838e4e4d50c41367944 | harrietty/python-katas | /katas/replace_chars.py | 1,340 | 4.09375 | 4 | '''
In input string word(1 word):
replace the vowel with the nearest left consonant.
replace the consonant with the nearest right vowel.
P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see b... |
76c735fe149a3cd12f1bd050c8f659adbe51368b | jubic/RP-Misc | /System Scripting/Problem09/files/func3.py | 220 | 3.828125 | 4 | def combine(strlist):
string = ""
for item in strlist:
string = string+"<"+str(item)+">"
return string
if __name__ == "__main__":
print combine(["one", "two"]) # prints "<one><two>"
|
514f41727105045ab95ccda845cf7aa328e48e0c | rafaelperazzo/programacao-web | /moodledata/vpl_data/386/usersdata/268/83572/submittedfiles/ep1.py | 113 | 3.8125 | 4 | # -*- coding: utf-8 -*-
n= int(input('Digite o numero de equações: '))
cont=0
while(cont<n):
#ENTRADA
|
54d21bb5584ca82161bdc74fd517c8a36e1ff3e4 | afahad0149/How-To-Think-Like-A-Computer-Scientist | /Chapter 11 (LISTS)/exercises/problem_3.py | 97 | 3.96875 | 4 | a = [1, 2, 3]
b = a[:] # b is a clone of a
b[0] = 5
print(a) # [1, 2, 3]
print(b) # [5, 2, 3] |
f932662d9bff8a6635aaae9984c653ec635a5f00 | barcern/python-crash-course | /chapter5/5-1_conditional_tests.py | 1,534 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 11:07:41 2020
@author: barbora
"""
# Write a series of conditional tests. Print a statement describing each test
# and your prediction for the results of each test. Create at least 10 tests.
fave_animals = ['alpaca', 'duck', 'flying squirrel', 'goldcrest']
print("Te... |
23b5b3851d4ed02bfb0608aa61fd1f121803a209 | semi-cheon/programmers | /level2/201217_programmers_압축.py | 670 | 3.71875 | 4 | # python 코딩 테스트 연습
# 작성자: 천세미
# 작성일: 2020.12.17.T
# 문제: 압축
# 문제 url: https://programmers.co.kr/learn/courses/30/lessons/17684
def solution(msg):
total = [chr(i) for i in range(65,91)]
answer = []
temp = ''
for i in msg:
temp += i
if temp not in total:
total.append(temp)
... |
48b4a8366bdd570864d6b4b7c09e394bbd36c506 | cligraphy/cligraphy | /staging/commands/misc/sets.py | 965 | 3.890625 | 4 | #!/usr/bin/env/python
"""Print the intersection or union of two line-delimited data sets
"""
OPERATIONS = {
'union': lambda left, right: left.union(right),
'inter': lambda left, right: left.intersection(right),
'ldiff': lambda left, right: left - right,
'rdiff': lambda left, right: right - left,
}
d... |
da3f9a2e24fb8eb0f5dd5644bb39e6bca8c6c46c | bhavyakamboj/Programming-101-Python-2020-Spring | /week09/03.SQL-and-Python/demo/setup_users_database_with_plain_text_passwords.py | 938 | 3.734375 | 4 | import sqlite3
def create_users_table():
connection = sqlite3.connect('users_with_plain_passwords.db')
cursor = connection.cursor()
query = '''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(50),
password VARCHAR(100)
)
'''
... |
2886c188ac6576efc20fd1ac6a5cb7e28a008e68 | daks001/py102 | /7/Lab7b_Prog3.py | 1,887 | 4.125 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: DAKSHIKA SRIVASTAVA
# Section: 532
# Assignment: LAB 7b PROGRAM 3
# Date: 10 OCTOBER 2019
print("This prog... |
7ae81472b265f376b29fd0637536c505919ca441 | shrutisingh15/Udacity_Data_Analyst_Nanodegree | /Project P5/Intro to Machine learning/ud120-projects-master/datasets_questions/explore_enron_data.py | 3,344 | 3.59375 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
e596a6ede88bd112b726df5d05923aa31f97ceb4 | mutoulovegc/gaochuang123 | /桌面/day.4/xingxing.py | 552 | 4.34375 | 4 | #完成5行内容的简单输出
#分析每一行应该如何处理?每行显示的星星和所在的行数是一致的
#嵌套一个循环,专门处理每一行列的星星显示
#定义一个行号确认当前我在那一行
row = 1
while row <= 5:
#假设Python中没有字符串拼接这个功能
#每一行显示的星星和当前的行数要是一致的
#
#列数
col = 1
while col <= row:
print("*", end="")
col = col +1
#完成每一行输出增加一个换行
print(" ")
row = row + 1
|
8ad96578c5f5503b000c46812666a77de4db6b08 | Disherence/Python_study | /new.py | 529 | 3.5625 | 4 | import math
try:
a = eval(input("请输入a边长:"))
b = eval(input("请输入b边长: "))
c = eval(input("请输入c边长: "))
except NameError:
print("请输入正数数值")
if str.isdigit(a) == True:
print("输输字")
elif a < 0 or b < 0 or c < 0:
print("数据不可以为负数")
elif a+b <= c or a+c <= b or b+c <= a:
print("不符合两边之和大于第三边原则")
else:... |
b4a6c7edf7affd3f22221652f850f08af0099e33 | Sathvickm07/My-captain-assignment | /student_adminstration_My Captain.py | 1,408 | 3.953125 | 4 | # school administration tool
import csv
def write_into_csv (student_info):
with open('student_info.csv', 'a', newline='') as csv_file:
writer = csv.writer(csv_file)
if csv_file.tell() == 0:
writer.writerow( ["Name", "Age", "Contact Number", "E-Mail ID"])
writer.writerow(studen... |
f22b08b574dfe38d2ba3e2c77217df7999322135 | FelixMayer/functions_basic_2 | /functions_basic_2.py | 1,783 | 4.25 | 4 | # 1 Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
def countdown(num):
count = []
for i in range(num, -1, -1):
count.append(i)
return count
x = countdown(5)
print(x)
... |
8b404b33ae8035a7cd017f5f6908933ebf6ae454 | gan3i/Python_second | /Exceptions/Iteration and iterable/itertools.py | 396 | 3.796875 | 4 | from itertools import count, islice
d = [1,2,3,4,4,4,3,3,2,2,5]
c = islice(d,2)
print(c)
print(any([True,False,True,False]))
print(all([False,False,False,False]))
#for Synchronized iteration through two or more iterables,
a = ["hey", "grus", "bitta"]
b = ["Pal!","gott","shoun"]
def print_zip():
for item in... |
5af78ceff2661b9f79853be4abbba099776acc97 | Jane11111/Leetcode2021 | /022_3.py | 665 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021-07-07 17:14
# @Author : zxl
# @FileName: 022_3.py
class Solution:
def recGenerate(self,left_count,right_count,n,s,ans):
if len(s) == 2*n:
ans.append(s)
return
if left_count == right_count:
self.recGenerate(left_cou... |
1f2be3871e84cd9dabf34b121620920e5fa558d6 | saisai/tutorial | /python/techiedelight_com/backtracking/minisudo.py | 1,920 | 4.125 | 4 | '''
if the board contains no invalid cells, ie.cells that violate the rules:
if it is also completely filled out then
return true
for each cell in the board
if the cell is empty
for each number in {1,2,3}
replace the current cell with number
... |
2aebbcc2981ae488c0a134e034dd5cea7f3c2b8d | onegules/Number-Guessing-Game | /NumberGuessGame/NumberGuess.py | 501 | 3.625 | 4 | import numpy as np
class NumberGuess:
def __init__(self,high=101):
''' Initialize the function and generates a random number based on the
optional argument'''
self.number = np.random.randint(1,high=high)
self.high = high
def result(self,guess):
'''Calculates the result... |
9cec2c1ddc458fe3d2299b54737b69513f2a5225 | Gangadhar454/Leet-code-solutions | /Maximum sum of two numbers.py | 650 | 4 | 4 | import collections
##Given an array A consisting of N integers, returns the maximum sum of two numbers whose digits add up to an equal sum.
##if there are not two numbers whose digits have an equal sum, the function should return -1.
def MaximumSum(A):
table = collections.defaultdict(list)
for a in A:
... |
5910a1169441c6793996230536c5d9c7db53d11b | AyumiizZ/grad-school-work | /01204512-algorithm/implement-for-midterm/find-smallest.py | 757 | 4.09375 | 4 | """
File name: find-smallest.py
Author: AyumiizZ
Date created: 2020/10/24
Python Version: 3.8.5
About: find smallest number in decreasing and increasing sequence
"""
def find_smallest(arr):
n = len(arr)
if (n == 1):
return arr[0]
if (arr[1] > arr[0]): # increase only
r... |
409a509905021c502bae0b5a8b74e37980070a83 | nazaninsbr/Queue | /reverse_using_stack.py | 1,015 | 3.921875 | 4 | class Stack:
def __init__(self):
self.values = []
def push(self, x):
self.values.append(x)
def top(self):
if len(self.values)==0:
return -1
return self.values[-1]
def isEmpty(self):
return len(self.values)==0
def pop(self):
if len(self.values)==0:
return -1
x = self.values[-1]
del self.va... |
a5bfaac1466344b8ae5048a80e29fe7e9d3f2f6e | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_221.py | 852 | 4.15625 | 4 | def main():
degreesNum = float(input("please enter the temperature of the water: "))
degreesType = str(input("what type of measurement is that temperature in? "))
if degreesType == "K" and degreesNum >= 373.0:
print("at this temperature, water is a gas")
if degreesType == "K" and degreesNum <= 2... |
ebad80400781ed92bf01cd38f3c042d287ea3941 | Hoch3007/practisepython_org | /exercise20.py | 599 | 3.765625 | 4 | ##### practicepython.org: Exercise 20
# Binary Search
import random
liste = random.sample(range(1,100,1), 99)
liste.sort()
n = 55
def binary_search(liste, n):
while len(liste)>1:
l = len(liste)
if n<liste[l/2]:
liste = liste[0:l/2]
else:
liste = li... |
44e537375be7879105d4c0a834e56878ba1e966c | rpachauri/connect4 | /connect_four/problem/group.py | 3,373 | 3.625 | 4 | from connect_four.game import Square
from enum import Enum
from connect_four.problem.problem import Problem
class GroupDirection(Enum):
horizontal = 0
up_right_diagonal = 1
vertical = 2
up_left_diagonal = 3
# Maps (row_diff, col_diff) to a Group Direction.
# Note that the mappings are counter-intui... |
17fd3bfea6ab550b9927e0bf6e0b105746ba2aa7 | MzBrownie/CTI110 | /M3T1_AreasOfRectangles_PatriceBrowne.py | 749 | 4.34375 | 4 | # Calculate the area of rectangles
# 12 June 2017
# CTI-110 M3T1 - Areas of Rectangles
# Patrice Browne
#
# Area of rectangle is length * width
first_rectangle_length = int (input ("First Rectangle Length? "))
first_rectangle_width = int (input ("First Rectangle Width? "))
second_rectangle_lenth = int (inpu... |
5839a036f3937e85236bde57744a70916d21ca70 | mdhiebert/minichess | /minichess/games/atomic/pieces/multipiece.py | 1,066 | 3.5 | 4 | from typing import List
from minichess.games.abstract.piece import AbstractChessPiece, PieceColor
import numpy as np
class MultiPiece(AbstractChessPiece):
'''
A piece that keeps track of itself and 8 other non-pawn pieces surrounding it (up to 9 in total).
This piece keeps track of its pieces with... |
55929c51b5c30771926148837fe528d4b12c169b | frankieliu/problems | /leetcode/python/623/sol.py | 1,233 | 3.78125 | 4 |
Can my solution be improved? [Python]
https://leetcode.com/problems/add-one-row-to-tree/discuss/232356
* Lang: python3
* Author: anonymous36
* Votes: 0
```
class Solution(object):
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:r... |
6280163355e13b3b00f243661017262d7189a4d1 | FaisalAhmed64/Python-Basic-Course | /User input.py | 257 | 4.03125 | 4 | name_is = input("what is your name? ")
print("hi " + name_is)
name = input("What is your name? ")
Color = input("what is your favourite color? ")
print(name + " likes " + Color)
birth_date = input("birth year: ")
Age = 2021 - int(birth_date)
print(Age)
|
7daad8fd4ff333f49954a4b26e8a9b8aff7647e7 | fallcreek/open-edx | /solutions/Week6/p1.py | 720 | 3.6875 | 4 | import random
def answer(seed):
random.seed(seed)
a = random.randint(1,5);
b = random.randint(6,10);
# Solutions with variables converted to string
# Make sure you name the solution with part id at the end. e.g. 'solution1' will be solution for part 1.
solution1 = "{0}*(1+1/2+1/3+1/4+1/5)".format(a)
so... |
4fe9d7b1d738012d552b79fb4dc92a3c65fa7e53 | akhileshsantoshwar/Python-Program | /Programs/P08_Fibonacci.py | 804 | 4.21875 | 4 | #Author: AKHILESH
#This program calculates the fibonacci series till the n-th term
def fibonacci(number):
'''This function calculates the fibonacci series till the n-th term'''
if number <= 1:
return number
else:
return (fibonacci(number - 1) + fibonacci(number - 2))
def fibonacci_without_... |
f649c1141a33f2faebe8ba4b882cb4671c92b13a | gschen/sctu-ds-2020 | /1906101040-吴云康/作业3/03.py | 392 | 3.734375 | 4 | class Person():
def __init__(self):
self.name = "吴云康"
self.age = 20
self.gender = "male"
self.college = "信息与工程学院"
self.professional = "信息管理与信息系统"
def personInfo(self):
return "name:{},age:{},gender:{},college:{},professional:{}".format(self.name,self.age,self.gend... |
bf2ad03f6c974e1f32a6ad959387267ff8377990 | MaxSchmitz/online_translater_practice | /Problems/The median of three/main.py | 826 | 4.25 | 4 | def choose_median(start, middle, end):
# finish the method for finding the median
pivot = [start, middle, end]
pivot.sort()
return pivot[1]
def partition(lst, pivot, start, end):
# add necessary modifications
# don't forget to print the result of the partition!
pivot = lst.index(pivot)
... |
7e6c4038aa4740a1ce2d5b97e1863998e164ea68 | alisonbelow/ctci_py_cpp | /py/sorting/insertionsort.py | 1,198 | 4.28125 | 4 | from sorter import Sorter
import time
'''
Time Complexity: O(n^2)
Space Complexity: O(1)
Divide into sorted and unsorted parts
Iterate over unsorted segment, insert the element viewed into correct position of sorted list
Comparing unsorted to sorted elem 'x'. Move unsorted elem to correct position then first... |
63688571fbf63611e25d9ca0227f5b19e503a0a1 | LingB94/Target-Offer | /19正则表达式匹配.py | 792 | 3.71875 | 4 | def match(L, pattern):
if(not L or not pattern):
return False
return matchCore(L, pattern)
def matchCore(L, pattern):
if(L == pattern):
return True
if( L != '' and pattern == ''):
return False
if(len(pattern) >= 2 and pattern[1] == '*'):
if(L[0] == pattern... |
7c24fddcb94099b611dea79c5066809b14d9bc84 | pandre-lf/Python-ads41 | /Lista-I/Ex25_invertermetades.py | 361 | 4.09375 | 4 | '''
25 - Faça uma função que receba uma lista e exiba os elementos da última metade na frente
dos elementos da primeira metade.
'''
import math
lista_teste=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def inverter_metades(lista):
print(lista[int(len(lista)/2):len(lista)] + lista[0:int(len(lista)/2)])
print(f"Lista inverti... |
cd4a6d95e996ef9c08c44f8c6853acb90fe4a03b | davestudin/Projects | /Euler Problems/Euler Problems/Question 1.py | 325 | 3.578125 | 4 | from math import *
max=1000
def func1(max):
a=0
while a<max:
yield a
a = a+3
def func2(max):
b,c=0,0
while b<max:
yield b
b = b+5
diff=0
for n in func2(max):
if n%3==0 and n%5==0:
diff = diff +n
c = sum(func1(max))
d = sum(func2(max))
print c+d... |
b8c200f89e7e086c17d049c8c50c382cebbcec95 | sdvinay/advent_of_code | /2019_01.py | 1,078 | 3.9375 | 4 | INPUT_FILE='input/input_2019_01.txt'
TEST_INPUTS=[4, 12, 14, 1969, 100756] #inputs provided in problem
# fuel burned to transport mass (Part 1)
def fuel_burned(mass):
return ((int(mass/3)-2) if mass >= 6 else 0)
# fuel_required accounts iteratively for including the fuel in the mass (Part 2)
def fuel_required(mass):... |
c4055ff67f8d60a10bc5f0e3b42482d9b70257b5 | zihuaweng/leetcode-solutions | /leetcode_python/136.Single_Number.py | 793 | 3.53125 | 4 | # https://leetcode.com/problems/single-number/
# 第二种方法解释:
# Approach 4: Bit Manipulation
# Concept
# If we take XOR of zero and some bit, it will return that bit
# a \oplus 0 = aa⊕0=a
# If we take XOR of two same bits, it will return 0
# a \oplus a = 0a⊕a=0
# a \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = ... |
b63b8e22e69d6c0b108327c77a4779ca459b5131 | ramdanks/RandomDataGenerator | /Random Data Generator/Array.py | 1,390 | 3.59375 | 4 | class Array :
def __init__( self,size ) :
self.arr = [ int ] * size
self.size = int( size )
self.index = 0
self.set( None )
def print( self ) :
for i in range( self.size ) :
if ( self.arr[i] != None ) :
if ( i+1 < self.size ) and ( self.arr[i+1] != None ) :
print( self.arr[i],end='... |
2bb76007c295563fe5efc218134415ee1af42e57 | s-gulzar/python | /recursive.py | 309 | 3.984375 | 4 | def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x - 1)
a= 5
print("Factorial of ", a ," is:", factorial(a))
def naturalnum(x):
if x == 1:
return 1
else:
return x + naturalnum(x - 1)
b = 6
print("Sum of ",b, "Natural Numbers:",naturalnum(b)) |
bf76f247531a62b0acdddbb55c46761042c87ea8 | triplowe/CSV_Project | /sitka4.py | 1,445 | 3.515625 | 4 | import csv
import matplotlib.pyplot as plt
from datetime import datetime
open_file = open("death_valley_2018_simple.csv", "r")
csv_file = csv.reader(open_file,delimiter=",")
header_row = next(csv_file)
print(type(header_row))
for index, column_header in enumerate(header_row):
print(index, column_header)
#test... |
75fc083ef3621707afbc1faec5355db5b7b0bbf1 | linahammad/CodeAcademy | /python/BattleShip.py | 1,964 | 4.3125 | 4 | # Import function to generate a random integer
from random import randint
# Create the playing board
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
# Welcome and print the playing field
print "Let's play Battleship!"
print_board(board)... |
1913c3d09fc2d44a269fc972b8a2027e5345b72d | PVyukov/algorithms | /L1_intro/L1_web/task_1.py | 732 | 3.90625 | 4 | # https://drive.google.com/file/d/1bjjsw9tzi4cuL5vQPTmOcL6MHGtmpfbH/view?usp=sharing
# Начало
# Вывод("Введите два чисал")
# Ввод(Первое число)
# Ввод(Второе число)
# Если Второе число != 0
# То Частное = Первое число / Второе число
# Вывод(Частное)
# Иначе Вывод("Нет решений")
# Конец
print('Введите два числа')
a... |
ba6c648dbe1f6b8cc65b474f4542c44555293a47 | andresmiguel39/languages | /python/findHypotenuse/solution.py | 596 | 3.796875 | 4 | from typing import List
from math import sqrt
class Hypotenuse:
def findHypotenuse(self, hickA: List[int], hickB: List[int]) -> List[int]:
hypot = []
result = 0.0
if not hickA or not hickB:
return []
if len(hickA) == len(hickB):
for a in range(0, len(hickA)):... |
1267efb8f752ed1f5a6f99d5893a2ef1d3ce0427 | heartcored98/COMET-pytorch | /model.py | 11,218 | 3.5 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import math
#===== Activation =====#
def gelu(x):
""" Ref: https://github.com/huggingface/pytorch-pretrained-BERT/blob/master/pytorch_pretrained_bert/modeling.py
Implementati... |
bab636919505d7343174748045be495955649be3 | Afroderrell/Coin-Counter | /cash.py | 682 | 3.921875 | 4 | from cs50 import get_float
money = get_float("How much money is owed?")
while (money < 0):
print("Value must be a dollar amount greater than 0")
money = get_float("How much money is owed?")
if money > 0:
break
cents = round(money *100)
coin = 0
quarters = 25
dimes = 10
nickels = 5
pennies = 1
wh... |
b4eac7c3bcdbd4abc4190a75c0b560887b77825d | yesmkaran/Target-Game | /settings.py | 1,142 | 3.5 | 4 | class Settings:
"""A class to store all settings for Target."""
def __init__(self):
"""Initialize the game's static settings."""
# Screen settings
self.screen_width = 1000
self.screen_height = 650
self.bg_color = (239, 222, 205)
# Ship settings
self.ship_left = 3
# Bullet settings
self.bullet_hei... |
f6d85ebf342624fd80b1008bfe26c1590471a404 | tberhanu/RevisionS | /revision/15.py | 486 | 4.375 | 4 | """ 15. Check if string starts/ends with certain symbols
Replace or substitute sth in the middle of the statement
"""
string = "#starts with the hash!"
print(string.startswith("#"))
print(string.startswith("#s"))
print(string.endswith("!"))
print(string.endswith("hash!"))
print(string.endswith("@"))
print(string.s... |
4e457e9e9b7f0b14929b55be130857de1810f4de | nagask/Interview-Questions-in-Python | /UnionFind/FriendsCircle.py | 1,660 | 3.734375 | 4 | class Union:
friends = None
def __init__(self, i):
if isinstance(i, list):
self.friends = i
else:
self.friends = [i]
def mergeFriendCircle(self, b):
return Union(self.friends + b.friends)
def findFriendCircleOf(i, friend_circles):
for circle ... |
6dbf47f82f0b2ae6dd0673f29fc3956ee8b549ac | andrepadial/Phyton | /SegundaMenorNota/SegundaMenorNota.py | 1,597 | 3.546875 | 4 | from statistics import mean, median, mode, stdev
class Aluno:
def __init__(self, nome, nota):
self.nome = nome
self.nota = nota
def populaLista(qtd):
lista = list()
contador = 0
while(contador <= qtd - 1):
nome = str(input('Informe o nome do ' + str(contador + 1) ... |
0d3129e6e20382c80658d210693faa63201b445d | taketakeyyy/atcoder | /abc/131/c4.py | 528 | 3.546875 | 4 | # -*- coding:utf-8 -*-
import sys
from fractions import gcd
def f(a, x):
"""1以上a以下で、xで割り切れるものの数"""
return a // x
def lcm(a, b):
""" aとbの最小公倍数を返す """
return a*b // gcd(a, b)
def solve():
A, B, C, D = list(map(int, sys.stdin.readline().split()))
A -= 1
# CでもDでも割り切れないもの
b = B - f(B, C) ... |
bbcbb0ea67f34692c049687636d1765b1c562d82 | priyancbr/PythonProjects | /StringOperations.py | 156 | 3.59375 | 4 | Word = "I am a python developer"
print(Word)
Neelam = len(Word)
print(f"length of the string word is {Neelam}")
print('{lang} rules'.format(lang='Python'))
|
a0ddcc79ee0c9337bc6630e949312a7b688c8832 | Pogotronic/practicepython | /E13 Fibonacci.py | 310 | 4.125 | 4 | times = int(input('How many fibonacci numbers?'))
def make_fib(num):
fib = [1, 1]
if num == 0:
fib = []
if num == 1:
fib = [1]
if num > 1:
for i in range(num -2):
fib.append(fib[-1] + fib[-2])
print(fib)
return fib
make_fib(times)
|
9d0902193024debaee848865586cd84f1fba80c2 | xushubo/learn-python | /module-collections.py | 1,843 | 3.609375 | 4 | from collections import namedtuple
from collections import deque
from collections import defaultdict
from collections import OrderedDict
from collections import Counter
#namedtuple是一个函数,它用来创建一个自定义的tuple对象,
#并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.