blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
618e1fdc6d658d3fc80cff91737e74f6f8fc30a6 | benichka/PythonWork | /chapter_10/common_words.py | 553 | 4.25 | 4 | # Take a file and count occurences of a specific text in it.
text_file = input("Choose a text file from which to count occurences of a text: ")
occurence = input("What text do you want to count in the file?: ")
try:
with open(text_file, 'r', encoding="utf-8") as tf:
contents = tf.read()
except:
print("... |
d8947556c73c79505c31eb54718aecb20f1b1c2b | benichka/PythonWork | /chapter_10/addition.py | 787 | 4.28125 | 4 | # Simple program to add two numbers, with exception handling.
print("Input 2 numbers and I'll add them.")
while (True):
print("\nInput 'q' to exit.")
number_1 = input("\nNumber 1: ")
if (number_1 == 'q'):
break
try:
number_1 = int(number_1)
except ValueError:
print("\nOnly n... |
d580d634fe2d2bcb915e958d192069c254dcd2c0 | jjena560/Cracking_The_Code_Interview | /Arrays and Strings/Palindromepermutation.py | 755 | 4.03125 | 4 | def palindromePermutation(str):
hash = [0]*128
for i in range(len(str)):
val = ord(str[i])
hash[val] += 1
oddCount = countOdd(hash)
if oddCount > 1:
return 'NO'
else:
return 'YES'
def countOdd(hash):
count = 0
for i in range(len(hash)):
if hash[i] ... |
c77c04ac341a2eb7e0f99ab4fb30b2f134c790d6 | vit050587/Python-homework-GB | /lesson5.5.py | 1,475 | 4.125 | 4 | # 5. Создать (программно) текстовый файл,
# записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
def sum_func():
try:
with open('file_5.txt', 'w+') as file_num:
str_num = input('Введите цифры через пробел \n')... |
c784f929acaf46281b13823f334d98d8b5d4f00c | vit050587/Python-homework-GB | /lesson4.4.py | 1,349 | 3.75 | 4 | # 4. Представлен список чисел. Определить элементы списка, не имеющие повторений.
# Сформировать итоговый массив чисел, соответствующих требованию.
# Элементы вывести в порядке их следования в исходном списке.
# Для выполнения задания обязательно использовать генератор.
# Пример исходного списка: [2, 2, 2, 7, 23, 1, 44... |
0a0219f3d03b7b7739c72cbd2f9ac6bc8305b98c | vit050587/Python-homework-GB | /lesson1.py | 4,468 | 3.90625 | 4 | # 1 Поработайте с переменными, создайте несколько, выведите на экран.
# Запросите у пользователя некоторые числа и строки и сохраните в переменные, затем выведите на экран.
age = (input("Ведите ваш возраст: "))
name = (input("Введите ваше имя: "))
print(f"Привет, {name} ! Тебе уже - {age} года")
# 2 Пользователь ... |
743da3842931f1dddbd81a9fffbaea5600b9f30e | vit050587/Python-homework-GB | /lesson6.5.py | 2,224 | 3.8125 | 4 | # 5. Реализовать класс Stationery (канцелярская принадлежность).
# Определить в нем атрибут title (название) и метод draw (отрисовка).
# Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер).
# В каждом из классов реализовать переопределение метода draw.... |
2a40bab98304b4921bf563964a213d0e7bfc8e68 | vit050587/Python-homework-GB | /lesson8.7.py | 1,394 | 3.71875 | 4 | # Реализовать проект «Операции с комплексными числами». Создайте класс
# «Комплексное число», реализуйте перегрузку методов сложения и умножения
# комплексных чисел. Проверьте работу проекта, создав экземпляры класса
# (комплексные числа) и выполнив сложение и умножение созданных экземпляров.
# Проверьте корректность п... |
b7305b66ea76382833c020ea4f8931b031ec7032 | ndpark/PythonScripts | /mapIt.py | 312 | 3.515625 | 4 | #! python3
# mapIt.py - Launches a map in browser using address from clipboard
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
address = ' '.join(sys.argv[1:]) #Chops off the first element of the array
else:
address = pypreclip.paste()
webbrowser.open('https://www.google.com/maps/place/'+address)
|
864a1347b8b66d612559f9de4e643cdf9d529b57 | ndpark/PythonScripts | /new 1.py | 478 | 3.84375 | 4 | #! python3
# stopwatch.py
import time
print('Press Enter to begin, press Enter again to \' End \' the stopwatch. CTRL-C will quit')
input()
print('Started')
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
while True:
input()
lapTime = round(time.time()-lastTime,2)
totalTime = round(time.time-sta... |
8e0f68898778383bcc958dcade2b9f06910d1b61 | ndpark/PythonScripts | /dogs.py | 949 | 4.21875 | 4 | #range(len(list)) can be used to iterate through lists
dogs = []
while True:
name = input('Dog name for dog # ' + str(len(dogs)+1) + '\nType in empty space to exit\n>>')
dogs = dogs + [name] #Making a new list called name, and then adding it to dogs list
if name == ' ':
break
print ('The dog names are:')
for name ... |
8ade98a9e878e8ba1790be5e225372d9482b6cbb | ndpark/PythonScripts | /backupToZip.py | 859 | 4.21875 | 4 | #! python3
# backupToZip.py - Copies entire folder and its content into a zip file, increments filename
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) #Folder must be absolute
#Figures out what the filename should be
number = 1
while True:
zipFilename = os.path.basename(folder) ... |
2c22aa41aacee4b431f6bf6fa7f412d21ab3a395 | arkajain27/python | /main.py | 1,434 | 3.609375 | 4 | '''
import sequencesolver
def getList(sequence):
try:
list1=sequence.split(',')
sequenceList=list(map(int, list1))
return sequenceList
except:
return -1
def isQuad(numberList):
if len(numberList)>=4:
diff = numberList[2]-2*numberList[1]+numberList[0]
for i i... |
59b3abfc491c4926627e53332fce49f41c1579ca | jeffhn1992/Pymft | /exercise/S08/rectangel.py | 1,092 | 3.96875 | 4 | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# def get_width(self):
# return self.width
# def get_height(self):
# return self.height
def get_area(self):
area = self.width * self.height
return area
def ge... |
04eb261e7442d9e463cb65151ed77b04cbc75f2e | sayadi/iometrics | /iometrics/average_metrics.py | 1,553 | 3.640625 | 4 | #!/usr/bin/env python3
"""
## Class to store Generic Statistics.
Computes and stores the average and current value of some metric.
:copyright: (c) 2018 by Yaroslav Bulatov under The Unlicense <https://unlicense.org>
:copyright: (c) 2021 by Leo Gallucci under Apache License 2.0.
:license: Apache 2.0, see LICENSE for m... |
cba6c9b55963d5ce4e625ae24cb91f373b7e01d3 | KirillK-16/Z63-TMS | /students/shloma/003_homework_03/task_3_3.py | 98 | 3.640625 | 4 | # Task 3.3
# Input string
s = input()
if len(s) > 10:
print(s + "!!!")
else:
print(s[1]) |
62d6297c201da26c790b9def3627050426f0edc2 | KirillK-16/Z63-TMS | /students/aliakseyenkamikhail/task.py | 417 | 3.75 | 4 | # начало 4,10,2021
# 1 Ввсети н строк с консолиб найти самую короткую и самую длинную
n = int(input(' Enter n lines'))
x = []
for i in range(n):
x.append(input('inp: '))
max_=''
min_=x[0]
for i in x:
if len(i) >= len(max_):
max_= i
if len(i) < len(min_):
min_ = i
print('hello')
print(mi... |
e025ee4369f290573fa18e4a04229f282f7ff6a2 | sergegingras/cardgame | /codealong/cards.py | 451 | 3.515625 | 4 | import random
suits = ('Hearts','Diamonds','Spades','Clubs')
ranks = ('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace')
values = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':11}
player = True
class ca... |
c456b792ecd49a456d4b376950112b4c64a4129f | ekaapermataa/git-training-basic | /mushybear/Project-Euler-28.py | 309 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#Project Euler Problem 28
def g(n):
s = (n-1) // 2
return (16*s*s*s + 30*s*s + 26*s + 3) // 3
# In[4]:
n = int(input('Enter an odd side length ≥ 3?'))
print ("Sum of both diagonals for a square spiral with length", n, "=", g(n))
# In[ ]:
|
5048c67e1a98a418f7bbfcc9e55561860f9a4c47 | llors/validores-en-python | /ejercicio3_doble.py | 1,163 | 3.640625 | 4 | import os
#BOLETA DE VENTA
#declarar variables
cliente,pantalon,camisa,polo,precio_pantalon,precio_camisa,precio_polo="","","","",0.0,0.0,0.0
# INPUT
cliente=os.sys.argv[1]
pantalon=os.sys.argv[2]
camisa=os.sys.argv[3]
polo=os.sys.argv[4]
precio_pantalon=float(os.sys.argv[5])
precio_camisa=float(os.sys.ar... |
ef3371af0fad165579ed05daab1b07db8472d344 | jonasschui/thesis | /system/kladblok.py | 140 | 3.609375 | 4 | dict = {'Name': ['michal','Zara'], 'Age': 7}
dict2 = {'Sex': 'female', 'Name': ['Hansie'] }
dict.concat(dict2)
print("Value : %s" % dict)
|
a900e5c4b825a824bd207f91fe0bb48c270365ca | madhuripatil06/python_snake_and_ladder | /snake_ladder/snake_ladder_app/views/tile.py | 588 | 3.65625 | 4 | class Tile():
def __init__(self, position, is_snake, is_ladder, destination=None):
self.position = position
self.snake = is_snake
self.ladder = is_ladder
self.destination = destination
def is_snake(self):
return self.snake == True
def is_ladder(self):
return... |
cc178a653e02787a4b26ff46c08c6c2f3a7754cd | rhitik26/python1 | /python assignments/listing.py | 440 | 3.9375 | 4 | ob=[
{
"fname":"Sachin",
"lname":"Tandon",
"city":"bengaluru"
},
{
"fname":"Ramu",
"lname":"kaka",
"city":"Primecity"
},
{
"fname":"Rahul",
"lname":"Dravid",
"city":"bengaluru"
}
]
#--------------------------------------------------
def mysort(el):
print("mysort called for "... |
632a672805914b130a2de77eff69cc66af77c25c | rhitik26/python1 | /python assignments/day4b.py | 471 | 4.125 | 4 | def outer(a):
def inner():
print("this is inner!")
print(type(a))
a()
print("Inner finished execution!")
return inner
@outer #By adding this annotation the function will automatically become wrapper function(the concept is Decorator)
def hello():
print("hello World!")
@outer... |
ba24a583c5ce9bfc188b0bf35a09edac20264d14 | rhitik26/python1 | /python assignments/gig.py | 1,544 | 4.0625 | 4 | #write to a file
#old data gets overwritten so write "a"-apend instead of "w"-write
#fo = open('demo.text', 'w')
fo = open('demo.text', 'a')
fo.write("Hello Superman \n")
fo.write("Hello Batman \n")
fo.write("Hello saurav \n")
fo.close()
with open('demo.text', 'a') as fo:
fo.write("Hello Superman \n")
fo.write... |
cb104c8845e156387d52be482276d10b1c22495e | rhitik26/python1 | /python assignments/assignmentlambda.py | 557 | 3.828125 | 4 |
ob=[
{
"fname":"Sachin",
"lname":"Tandon",
"city":"bengaluru"
},
{
"fname":"Ramu",
"lname":"kaka",
"city":"Primecity"
},
{
"fname":"Rahul",
"lname":"Dravid",
"city":"bengaluru"
}
]
"""
#--------------------------------------------------
def mysort(el):
return el["fnam... |
2a634bc99860072f4a7373d7da77d0d54f329e8e | sanidhyag1/hyperskill_projects | /tic_tac_toe.py | 1,964 | 3.953125 | 4 | new_col = 0
new_row = 0
blank = " "
board = blank * 9
x_move = True
game_done = False
def draw_board(board):
print("-" * len(board))
print("|", " ".join(board[:3]), "|")
print("|", " ".join(board[3:6]), "|")
print("|", " ".join(board[6:]), "|")
print("-" * len(board))
def check_win(board):
s... |
5693c6c2a314df14d836b3307cf494c264282390 | CuriousLearner/Algorithms | /Sorting/BubbleSort.py | 381 | 4.09375 | 4 | def Bubble_Sort(alist):
'''
Sorting the alist through Bubble Sort
'''
for passnum in range(len(alist)-1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
return alist
def main():
alist = [6, 4, 2, 1, 7, 9,... |
c8befdb96cbf14ea3a42237649355b71f8e0268e | AndreeaNenciuCrasi/Python-Ask-Mate-with-CSV | /connection.py | 1,229 | 3.59375 | 4 | import csv
QUESTIONS_HEADER = ['id', 'submission_time', 'view_number', 'vote_number', 'title', 'message', 'image']
ANSWERS_HEADER = ['id', 'submission_time', 'vote_number', 'question_id', 'message', 'image']
def read_questions(csv_file):
with open(csv_file, 'r') as csvfile:
csv_reader = csv.DictReader(cs... |
081f6e59fc33a53ac11e37c209f64c49c97a8f84 | dojinkimm/AlgorithmPractice | /baekjoon/11729_hanoi_order.py | 441 | 3.65625 | 4 | # BOJ 11728 - 하노이 탑 이동 순서 - 분할 정복
import sys
def hanoi(n, from_rod, to_rod, aux_rod):
if n == 1:
movement.append([from_rod, to_rod])
return
hanoi(n - 1, from_rod, aux_rod, to_rod)
movement.append([from_rod, to_rod])
hanoi(n - 1, aux_rod, to_rod, from_rod)
N = int(sys.stdin.readline()... |
6de58d5841e40bac71d81414bfaa5f38f4a9048b | dojinkimm/AlgorithmPractice | /leetcode/29_divide_two_int.py | 603 | 3.5 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
isNegative = True
if (dividend < 0 and divisor < 0) or (dividend >= 0 and divisor >=0):
isNegative = False
dividend, divisor = abs(dividend), abs(divisor)
quotient, temp = 0, 0
for i in range(... |
d8a9d1c78c1221ffddcff3a5b02fd1b193f28cc7 | drkthakur/learn-python | /python-poc/python-self-poc/oop-test/object-life-cycle.py | 299 | 3.53125 | 4 | class PartyAnimal:
x=0
def __init__(self):
print("I'm initialized!")
def party(self):
self.x = self.x+1
print("so far:", self.x)
def __del__(self):
print("I'm destroyed !")
an = PartyAnimal()
an.party()
an.party()
an=42
print("an contains", an) |
c1ea90b62c4b57ef847fd1393d11300a2f03bd6c | drkthakur/learn-python | /python-poc/python-self-poc/even_odd_verify.py | 98 | 4.09375 | 4 | x = input("Enter Number please ? \n")
if int(x) % 2 == 0:
print("Even")
else:
print("Odd") |
f0de78586e06ab3b4a740b1e0ca181d1e3fcb819 | drkthakur/learn-python | /python-poc/python-self-poc/Calculator.py | 437 | 4.15625 | 4 | print(17/3)
print(17//3)
print(17%3)
height=10
breadth=20
print(height*breadth)
print (-3**2)
print ((-3)**2)
x=1 + 2*3 - 8/4
print(x)
if 2.0 < 2:
print("A")
elif 2.0 >= 2:
print("B")
else:
print("C")
score = input("Enter Score: ")
s = float(score)
if s >= 0.9:
print("A")
elif s >= 0.8:
print(... |
02e416f38c5bb26e4ed5db2dbad5171dbddb520c | drkthakur/learn-python | /python-poc/python-self-poc/map-ds-dictionary.py | 479 | 3.65625 | 4 | tel = {'jack': 4098, 'sape': 4139}
print(tel)
tel['guido']=4127
print(tel)
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k,v in knights.items():
print(k,v)
questions=['name','quest','favourite color']
answers=['lancelot','holy grain','blue']
for q,a in zip(questions,answers):
print('what is yo... |
13d7ab468faf1f3342bf8f221ca36e51437b131d | bloomsarah/Practicals | /prac_04/lottery_ticket_generator.py | 778 | 4.1875 | 4 | """
Generate program that asks for number of quick picks
print that number of lines, with 6 numbers per line
numbers must be sorted and between 1 and 45
"""
import random
NUMBERS_PER_LINE = 6
MIN = 1
MAX = 45
def main():
number_of_picks = int(input("Enter number of picks: "))
while number_of_picks < 0:
... |
e782f621e99250c67bd55398062408641ea01925 | nsa-yoda/meer.me | /app/lib/geo/conversion.py | 1,069 | 3.765625 | 4 | class Conversion(object):
conversions = {
'mi': {
'km': 0.621371,
'in': 0.0000157828,
'm': 0.000621371,
'cm': 0.00000621371
},
'km': {
'mi': 1.60934,
'in': 0.0000254,
'm': 0.001,
'cm': 0.00001
... |
7295efd491cd00f9d4ed85b6c20cf505fca05bac | glambertation/ToGraduate | /Leetcode/python/sort/qs.py | 1,593 | 4.0625 | 4 | """
Quick Sort
----------
Uses partitioning to recursively divide and sort the list
Time Complexity: O(n^2) worst case, O(nlgn) common case
Space Complexity: O(1) this version
"""
class Solution(Object):
def partition(self, nums, p, r):
x = nums[r]
i = p-1
for i in range... |
e76d7725e90b327bb303f66a4fef5921d52ef5b9 | mgabhishek06kodur/irriserve | /Python_PI/IrriServe/sensors/soil.py | 845 | 3.734375 | 4 | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
#GPIO SETUP
channel = 21
led = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led, GPIO.OUT) #led
GPIO.setwarnings(False)
print("Waiting for sensor to settle")
time.sleep(2) # to stabilize sensor
print ("Detecting moisture")
def callback(channel... |
6a3547651635d9a1c1779362a42ff4d27e0620b9 | timeeeee/project-euler | /15-lattice-paths/main.py | 680 | 3.734375 | 4 | # How many routes are there from one corner of a 20x20 grid to the opposite corner,
# only traveling right or down along grid lines?
def pathsNxN(n):
grid = [[0 for _ in range(n)] for _ in range(n)]
return pathsTo(grid, n - 1, n - 1)
# Paths to a point are sum of paths to both successive points
# Save solutio... |
a4fe0d90b2772844969b34ce6ffa103c294ddfa1 | timeeeee/project-euler | /4-largest-palindrome-product/main.py | 358 | 4.15625 | 4 | # Find the largest palindrome that is the product of 2 3-digit numbers.
def isPalindrome(x):
string = str(x)
return "".join(reversed(string)) == string
maximum = 0;
for a in range(111, 1000):
for b in range(111, 1000):
product = a * b
if isPalindrome(product) and product > maximum:
... |
206deca44b6fa1c1147d3c6d698d92ea2aee44ed | timeeeee/project-euler | /62-cubic-permutations/slow.py | 1,720 | 4.15625 | 4 | """
The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are cube.
"""
from ... |
176ff3c9ac7957122211639044db6b36c7ade2b8 | ryanhawker/project-euler | /p2.py | 713 | 4.03125 | 4 | #! /usr/bin/python
####### Problem Two #######
#Eacch new term in the Fibonacci sequence is generated by adding the previous two terms.
#By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
#By considering the terms in the Fibonacci sequence whose values do not exceed ... |
42c8dbb003fb328479f909864a5d1dcdcbb3a0c5 | shiva0987/square-root | /student_exam.py | 97 | 4.03125 | 4 | num=float(input("Enter a marks:"))
num_sqrt=num**2.5
print("The cube root of",num,"is",num_sqrt)
|
ddebbdc7c4ff63ac336e3f5d94488a44b26a1863 | MDOBreno/pythonteste | /aula10.py | 446 | 3.890625 | 4 |
nome = str(input('Qual é seu nome? '))
if 'BRENO' in nome.upper():
print('Que nome lindo você tem!')
print(f'Bom dia {nome}')
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2) / 2
print(f'A sua média foi {m:.1f}')
if m >= 6.0:
print('Sua nota foi boa! PA... |
476eecdc2f3d5a22894b667b15fa16c02a47528d | marcusorefice/-studying-python3 | /Exe112/utilidadescev/moeda/__init__.py | 2,327 | 3.71875 | 4 | def metade(valor=0, formato=False):
"""
-> Calcula a metade de um determinado preço.
:param valor: o preço que se quer reajustar.
:param formato: quer a saída formatada ou não?
:return: o valor reajustado, com ou sem formato.
"""
r = valor / 2
return r if formato is False else mo... |
d1c93f7e7a5e85e83928b7e2f3b19d86c23ed7cc | marcusorefice/-studying-python3 | /Exe106.py | 1,130 | 3.921875 | 4 | """Faça um mini-sistema que utilize o Interactive Help do Python. O usuário vai digitar o comando
e o manual vai aparecer. Quando o usuário digitar a palavra ‘FIM’, o programa se encerrará.
Importante: use cores."""
from time import sleep
c = ('\033[m', # 0 - sem cores
'\033[1;107m', # 1 - Branco.
... |
e4428338856573bd0a16aace2f207d712e21550b | marcusorefice/-studying-python3 | /Exe054.py | 500 | 3.84375 | 4 | '''Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas
ainda não atingiram a maioridade e quantas já são maiores.'''
from _datetime import date
dataa = date.today().year
s1 = 0
s2 = 0
for c in range(1, 8):
data = int(input(f'Digite o {c}º ano de nascimento: '))... |
facae185194b43bfe34f50e7105a7a00f3512386 | marcusorefice/-studying-python3 | /Exe017.py | 184 | 3.578125 | 4 | from math import hypot
co = float(input('Digite o cateto oposto: '))
ca = float(input('Digite o cateto adjacente: '))
print(f'O comprimento da hipotenusa é: {hypot(co, ca):.2f}')
|
8950c05b10765b505f5fde72b40de9d7bb486624 | marcusorefice/-studying-python3 | /Exe082.py | 680 | 3.90625 | 4 | """Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso, crie duas lista extras que vão conter apenas os valores pares e os valores impares
digitados, respectivamente.
Ao final, mostre o conteúdo das três listas geradas."""
lista = []
listap = []
listai = []
while True:
n = int... |
f85ccd4a5fc85b3d88d123f8cb313bcd43ba7438 | marcusorefice/-studying-python3 | /Exe019.py | 273 | 3.671875 | 4 | from random import choice
a = input('Digite o nome do 1º aluno: ')
b = input('Digite o nome do 2º aluno: ')
c = input('Digite o nome do 3º aluno: ')
d = input('Digite o nome do 4º aluno: ')
alunos = (a, b, c, d)
print(f'O aluno escolhido foi: {choice(alunos)}')
|
bc214250e9377ca6ea3207f5c7d03f266eb6dc08 | marcusorefice/-studying-python3 | /Exe068.py | 1,184 | 3.9375 | 4 | '''Faça um programa que jogue par ou impar com o computador. O joso só será interrompido
quando o jogador PERDER, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo.'''
from random import randint
print('-='*10, 'JOGO DO PAR OU IMPAR', '=-'*10)
cont = 0
while True:
n1 = randint(1,... |
6652b0fb9dee36b97934953d449a4874e459e4b9 | marcusorefice/-studying-python3 | /Exe007.py | 107 | 3.859375 | 4 | n = float(input('Primeira nota: '))
n1 = float(input('Segunda nota: '))
print(f'A média é: {(n+n1)/2}') |
5807c4d79b16a701d0b6664d9140d53ca1281f6a | marcusorefice/-studying-python3 | /Exe087.py | 775 | 4.09375 | 4 | """Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha."""
matriz = [[], [], []]
par = 0
soma = 0
for l in range(0, 3):
for c in range(0, 3):
matriz[l].append(int(input(f'Digite... |
c567c4696e580e5d1b38f6a62fae62efa50a4e75 | paimoe/stuff | /sudoku/sudoku.py | 2,387 | 3.765625 | 4 | """
Works with pretty simple solutions
@todo:
- check diagonals
- check each square
"""
def printer(full):
line = '+---+---+---+'
i = 0
for k,l in full.items():
if i % 3 == 0:
print(line)
first = ''.join([str(l) for l in l][0:3])
second = ''.join([str(l) for l i... |
1f260fa00e554a3030c2c08684177b38260abc7b | rahulbhadani/dadra | /dadra/utils/misc_utils.py | 1,700 | 3.625 | 4 | import numpy as np
import time
def format_time(t):
"""Formats time into string with minutes and seconds
:param t: The time in seconds
:type t: float
:return: Formatted string with minutes and seconds
:rtype: string
"""
time_string = time.strftime("%M:%S", time.gmtime(t))
time_list = t... |
dbf375f858c4d4d67079098f270fc473b7dbb23f | jaters/LCGame | /main.py | 923 | 3.6875 | 4 | from unicurses import *
stdscr = initscr() # initializes the standard screen
####### GAME FUNCTIONS #######
points = int(20)
##### MAIN FUNCTION ######
print "Welcome! I hear you're looking for a spaceship. "
print "Well you've come to the right place, let's build you a ship!"
name = raw_input("What do you want ... |
146f34e09ac3d2710987be4414ee6188d5588ff9 | ivan4oto/Python101 | /week09/day03/business_card_catalog/BusinessCardCatalog.py | 3,440 | 3.828125 | 4 | import sqlite3
def create_table(name):
connection = sqlite3.connect('bcc.db')
cursor = connection.cursor()
cursor.execute(
f'''
CREATE TABLE IF NOT EXISTS "{name}"
(
id INTEGER PRIMARY KEY UNIQUE NOT NULL,
full_name VARCHAR(25) UNIQUE NOT NULL,
... |
66ae1218cdd411d742b660518710eeece0ffc69c | mrcosta93/coursera_intoducao1 | /15_NIM.py | 2,007 | 3.921875 | 4 | def computador_escolhe_jogada(n, m):
tira = 1
while (n-tira) % (m+1) != 0 and tira < m:
tira += 1
n -= tira
print("")
print("O computador tirou", tira, "peça(s)")
print("Ainda resta(m)", n, "peça(s)")
return tira
def usuario_escolhe_jogada(n, m):
print("")
... |
fc26fc5ac65bb257a0615b6e53157e232987cfb1 | dymitrlubczyk/evoman_framework | /experiment.py | 1,710 | 3.546875 | 4 | import numpy as np
DEBUG = True
class Experiment:
best_solutions = np.array([[]]) # 2D array which stores best member/solution of every run
best_solutions_fitness = np.array([]) # array of best solution's fitness of every run
def __init__(self, _evolutionary_algorithm):
self.evolutionary_alg... |
a57639296615b6b493ef9e5a7067f044117fcbcf | dymitrlubczyk/evoman_framework | /mutation_selection.py | 1,308 | 3.640625 | 4 |
class MutationSelection:
# This class is used to select individuals to be mutated
"""
Creates the mutation set M
Randomly choose individuals from the selection - BEFORE or AFTER CROSSOVER has been applied?
Params:
-------
selection_ratio : relative number of in... |
2237df6ec7a272e44be3256a76f8caffae014b8f | mkuentzler/AlgorithmsCourse | /QuickSort.py | 2,018 | 3.71875 | 4 | import numpy
def pick_pivot_idx(a):
"""
Chooses a pivot index for the Quick Sort algorithm. Here, choose the median
of the first, last and middle element.
"""
mid = (len(a) - 1) / 2
median = numpy.median([a[0], a[mid], a[-1]])
if a[0] == median:
return 0
elif a[-1] == median:
... |
bdf59dd32d97144bc120404ab9e6e59a76ba1286 | mkuentzler/AlgorithmsCourse | /Prim.py | 1,588 | 3.65625 | 4 | import heaps
import random
def prim(graph):
"""
Applies Prim's algorithm to find a minimum spanning tree, and returns the
mst cost.
"""
cost_heap = heaps.Minheap()
mst_cost = 0
unvisited = {node: None for node in graph}
current_node = random.choice(graph.keys())
unvisited.pop(curre... |
319e95ee89071a5402aaa30aac4f77e2f34a9168 | mkuentzler/AlgorithmsCourse | /LinkedList.py | 771 | 4.1875 | 4 | class Node:
"""
Implements a linked list. Cargo is the first entry of the list,
nextelem is a linked list.
"""
def __init__(self, cargo=None, nextelem=None):
self.car = cargo
self.nxt = nextelem
def __str__(self):
return str(self.car)
def display(self):
if s... |
34fc4af582484187decddee97472735332f557d3 | charliekristiawan/week10 | /testing.py | 241 | 3.921875 | 4 | def calculate_area(width1,height1):
area1 = width1 * height1
return area1
print('Area calculator')
width1 = int(input('Enter width'))
height1 = int(input('Enter height'))
area1 = calculate_area(width1,height1)
print('Area =',area1) |
a0f3a6a6dd50b5037bebc2f6ab399f4ba9dc2455 | saichandrareddy1/WebScrapingWithAdvaceFeatures | /my_project.py | 3,239 | 3.59375 | 4 | #importing the modules
from urllib.request import urlopen as uReq
#importing urls from the web, through urllib.request pakage and opening through the urlopen and calling as the uReq
from bs4 import BeautifulSoup as soup
import urllib.request as urllib2
import requests
#import Beautifulsoup function from ... |
7c8be387143102e3aaab5db14d2b68de273f160b | juanpanu-zz/PM_DataScience | /Clases/Lamda/lamdas.py | 1,178 | 3.84375 | 4 | import requests
import json
import os
URL= "https://www.dolarsi.com/api/api.php?type=valoresprincipales"
def get_information(url):
response = requests.get(url)
content = json.loads(response.content)
dolar_value = float(content[0]['casa']['compra'].replace(',','.'))
return dolar_value
def run(url... |
73fd9f303ede817fb92b4307dc60beac883bf49c | juanpanu-zz/PM_DataScience | /Retos/Ordenar Lista/ordenarLista.py | 1,167 | 4.03125 | 4 | # Ejercicio #2: Ordenamiento en listas.
# Tecnologías sugeridas: Python o Javascript (elegir), Git
# Realizar un programa que dada un lista de números desordenada, retorne una lista con
# todos sus valores ordenados de menor a mayor. No se puede utilizar la función “sort” u
# otras existentes en Javascript para el orde... |
e2234e80173b0a4a386321069f7c7c0193e3e244 | simone-rizzo/Car-sharing-model-simulation | /src/main.py | 8,036 | 3.59375 | 4 | import simpy
import matplotlib.pyplot as plt
import random
from Car import Car
"""
Project CMCS 2021 Simone Rizzo
Modelling Car Sharing trought Discrete Event Simulation with Simpy
1 time-step = 1 minutes
"""
class Customer(object):
def __init__(self, env, avaible, dead, t_spawn, usage_tim... |
83e1e707b47bdc3fbfdb16f7a705928a6619d7e6 | mengtest/MengPyTest | /src/meng/base/TestContaine.py | 3,316 | 4.03125 | 4 | #!/bin/python
#coding=utf-8
'''
Created on 2014年4月23日
@author: Administrator
'''
# print("测试中 ! 容器");
# 容器就是用来存放一些对像的数据结构。根据使用方式的不同,python提供了列表(List),元组(trupe),字典(dict)
# 用来动态的存放对像,可以插入,删除,更新。使用[]来给表示,看上去像c的数组,
# 用起来像java的list(不是很准确,更像vector,不做过多解释)
# .定义:变量a=[]#空的列表或者变量b=[1,3,4,5,'iloveyou']
# #有值的列表,元素可以是不同的类型, 这和... |
462210b1fc38a8c413f2e416654f15db11556ec6 | darkar27/Hunter | /Game.py | 6,885 | 4.0625 | 4 | #!/usr/bin/env python
import random
class Game:
def __init__(self, name, number):
self.name = name
self.number = number
def level1(self):
print(
"\nBienvenido a la etapa numero 1 del examen de cazador, para poder pasar a la siguiente etapa deberas de contestar correctamente... |
283b4089d23fc42c4d2227240aa5cad2eb06a2e9 | SandroS22/Curso-Python | /Atividade68.py | 894 | 3.6875 | 4 | from random import randint
num = 0
result = 0
finalresult = str('')
vitorias = 0
while True:
esco = str(input('Impar ou par? ').upper())
num = int(input('Escolha um número de 0 a 10: '))
oponente = randint(0, 11)
resultado = num + oponente
if resultado % 2 == 0:
finalresult = 'Par... |
7cdc79ea8150bd9df6e4eae63527559ebdd5c4ed | SandroS22/Curso-Python | /Atividade34.py | 247 | 3.703125 | 4 | salario = float(input('Quanto vc recebe? '))
aum10 = (salario * (10/100)) + salario
aum15 = (salario * (15/100)) + salario
if salario >= 1250.00:
print('Vc receberá {}'.format(aum10))
else:
print('Vc receberá {}'.format(aum15))
|
43a5d6ca3431c87af401db8ceda677bca0a1a52e | AjsonZ/E01a-Control-Structues | /main10.py | 2,365 | 4.21875 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # print out 'Greeting!'
colors = ['red','orange',... |
9a41d15441feb0d157e1f5fae95648f385f82b5c | aishraghavan/hacker_rank | /love_letter_mystery.py | 1,034 | 3.9375 | 4 | """
https://www.hackerrank.com/challenges/the-love-letter-mystery/
"""
def test_number_of_changes_to_palindrome():
n = int(raw_input().strip())
array_str = []
for i in range(n):
string = str(raw_input().strip())
if len(string) != 0:
array_str.append(string)
for element in a... |
495ee4592e23c78140d8fccc77cb39328c05366f | aishraghavan/hacker_rank | /reduced_string.py | 2,723 | 3.65625 | 4 |
#Hacker rank solution:
def hacker_rank_reduced_string():
string = str(raw_input().strip())
if not string:
return None
count = 1
index = 0
output_str = ""
while index<len(string)-1:
#print index, string[index], string[index+1]
# next char equal
if string... |
65337ce16cd959f7cc56feadf4c23119302bb7b8 | prasanna82/GRIP | /Task2.py | 2,527 | 3.5 | 4 | # For reading data set
# importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import numpy as np
# reading a csv file using pandas library
task=pd.read_csv("https://raw.githubusercontent.com/AdiPersonalWorks/R... |
5d39e3a0ba0bc649b418525a31ea8d6ff6667774 | nangirvan/classical-cryptography | /vigenere-cipher.py | 1,760 | 4.09375 | 4 | # Function to set key based on the text
def setKey(text, key):
text = text.replace(" ", "")
key = key.replace(" ", "")
if (len(text) > len(key)):
length = len(text) - len(key)
for character in range(length):
key += key[character]
return key
elif (len(text) < len(key)):
length = len(key) - len(text)
ret... |
e8acb94d8db3e5107e38d8e4324bc57198741c65 | jerryxhe/coding-competitions | /running_median.py | 533 | 3.78125 | 4 | # https://www.hackerrank.com/challenges/find-the-running-median
from bisect import bisect_left
class SortedList:
def __init__(self):
self.list = []
def add(self, v):
i=bisect_left(self.list, v)
self.list.insert(i, v)
def median(self):
n_ = len(self.list)
if n_%2==0:
... |
c4137337e1f6def402d7ed40429731a0fd61ce07 | choes1209/test1 | /name.py | 234 | 3.75 | 4 | # Напишите программу, которая 10 раз выводит на экран Ваше имя, каждый раз с новой строки
name = input('Введите ваше имя: ')
print((name + '\n') * 10) |
2c720e5c551e16b438ed0a5f94e7b640e5e33ff7 | RichardJ16/Cormen-Introduction-To-Algorithms | /Chapter-2/Merge-Sort.py | 1,117 | 3.828125 | 4 | # Worst-Case Run-Time = O(n*log(n))
# Worst-Case Space-Complexity = O(n)
def MergeSort(A):
L, R = split(A)
if len(L) > 1:
MergeSort(L)
if len(R) > 1:
MergeSort(R)
i = 0
j = 0
k = 0
while i < len(L) and j < len(R):
if L[i] <= R[j]:
A[k] = L[... |
3dfafd6ae61f7699fb8904c3c36ddbc42aef90e3 | bakkerjangert/AoC_2017 | /Day 17/Day 17.py | 332 | 3.6875 | 4 | def run(data, steps, start):
val = max(data) + 1
index = (start + steps) % len(data) + 1
data.insert(index, val)
return data, index
puzzle_input = 369
data = [0]
start = 0
for i in range(2017):
temp_val = run(data, puzzle_input, start)
data = temp_val[0]
start = temp_val[1]
print(data[s... |
ab1feaaf2f8b0c882bb76c5224839c7dbf3ee90e | waditya/HackerRank_Algorithms_Sorting | /02_Intro_to_Tutorial_Challenges.py | 390 | 3.984375 | 4 | #!/bin/python3
##Basic Code for Sorting
import sys
def introTutorial(V, arr):
for i in range(0, len(arr), 1):
if arr[i] == V:
index = i
break
return(index)
if __name__ == "__main__":
V = int(input().strip())
n = int(input().strip())
arr = list(map(int, input().strip... |
81e08834fb6a84c4ef4d6ee18411574f404c9c43 | riverlee/Certificate-Program-in-Data-Science | /CSX433.7/HW2.py | 1,367 | 3.59375 | 4 | #!/usr/bin/env python
######################################
# User: Jiang Li
# Date: Sat Jun 9 17:00:00 PDT 2018
######################################
"""
HW2:
Recreate the graph and visualize it in Tensorboard using:
1. Placeholder for an input array with dtype float32 and shape None
2. Scopes for the input, mid... |
afd4c3f4d648df693110ecc0eb3d12d821ba05c2 | parth1999-coder/bank-managment-system | /bank management system.py | 4,336 | 3.640625 | 4 | print("_______________________________")
print("\t Bank Management System")
print("_____________________________________")
import mysql.connector
mydb=mysql.connector.connect(user="root",passwd="parth",host="localhost",auth_plugin="mysql_native_password")
mycursor=mydb.cursor()
mycursor.execute("create database i... |
9ebc5c4273361512bd5828dee90938820b41f097 | Andrew-2609/pythonbasico_solyd | /pythonbasico/aula11-tratamento-de-erros.py | 872 | 4.21875 | 4 | def is_a_number(number):
try:
int(number)
return True
except ValueError:
print("Only numbers are allowed. Please, try again!")
return False
print("#" * 15, "Beginning", "#" * 15)
result = 0
divisor = input("\nPlease, type an integer divisor: ")
while not is_a_number(divisor):... |
0e72781464e28a78af58d8d4c02c6230721a53a9 | wahello/benchmarkSearch | /method/curdData.py | 1,422 | 3.75 | 4 | import sqlite3
from method import getConfig
def insertList(tableName,columnList,valueList):
db = getConfig.getJson("dataDb")
conn = sqlite3.connect(db)
# 字典
def insertDict(tableName,columnList,valueDict):
db = getConfig.getJson("dataDb")
conn = sqlite3.connect(db)
sql = "insert into... |
735c741f0aa67b648cece5f9960d2420aa8d9240 | YuefanZhu/Interesting-Interview-Questions | /find_median.py | 668 | 3.984375 | 4 | # you are given a sorted (ascending) array and integer k
# find the median of subarray that contains values less than or equal to k
from math import floor
def find_median(arr,k):
if(arr[1]>k):
return 'illegal input';
if(arr[-1]<=k):
if (len(arr) % 2 == 1):
return arr[len(... |
e13cf66b8a661d322d46ede5e2722c6da82967a5 | YuefanZhu/Interesting-Interview-Questions | /bfs.py | 915 | 3.734375 | 4 | #input a matrix(n,n), (i,j)=1 means i zombie and j zombie knows each other, (i,j)=1 means dont know
#if i know j, j know k, i is in the same cluster with k.
#Count how many clusters for a input matrix
def zombieCluster(zombies):
zombies = [list(z) for z in zombies]
n = len(zombies)
visited = set()... |
41d13e039fc0038a30221a507a97e6feaf16fcd9 | amrutra07j/abnamro | /hard5.1.py | 71 | 3.515625 | 4 | n = int(input("enter in inches"))
f = n/12
print "in meters", f*0.30 |
bdc98a6f01d7d4a9663fd075ace95def2f25d35c | BipronathSaha99/GameDevelopment | /CurrencyConverter/currencyConverter.py | 608 | 4.34375 | 4 | # >>-----------CurrencyConverter-------------------<<
#To open currency list from text file .
with open("currency.txt") as file:
lines=file.readlines()
#to collect all information create a dictionary
currencyDic={}
for line in lines:
bipro=line.split("\t")
currencyDic[bipro[0]]=bipro[1]
... |
de7b5cf067d91e7b1389f37bb8859a0b0247db53 | Sairafatima/smalltasks.py | /project 4 largest palindrome.py | 836 | 3.859375 | 4 | a=100 # Startin limit of first number
b=100 # Startin limit of Second number
print("Palindrom numbers are,")
def panlindrom(int):
b=100
while b<1000: # Ending limit of second number
product=a*b # Product of both numbers
String=str(product) # Converting Product to String
... |
2791f2e289bfa9f6063911fa2840bc9d56ed4a64 | BrucePython/Deep_Learning | /06_Deep_Learning/24_cnn_mnist.py | 5,962 | 3.640625 | 4 | """
卷积模型(确定网络结构和参数):
两层卷积池化和一层输出层
第一层
卷积:32个filter、大小5*5、strides=1、padding="SAME"
激活:Relu
池化:大小 2x2、strides = 2
第二层
卷积:64个filter、大小5*5、strides=1、padding="SAME"
激活:Relu
池化:大小 2x2、strides = 2
全连接层
重点:计算每层数据的变化
梯度爆炸:
1. 调整参数w,b的值
2. 使用tf.train.AdamOptimizer()
"""
import tensorflow as tf
from te... |
ede0e78157adb07b7d7a292143738ace947e7221 | BrucePython/Deep_Learning | /01_Machine_Learning/04_主成分分析_PCA.py | 692 | 4.03125 | 4 | # 主成分分析:压缩维度
from sklearn.decomposition import PCA
import pandas as pd
def pca_test():
pca = PCA(n_components=0.95)
# n_components=int, 减少到int个特征
# = 小数,减少到的百分比
data = pca.fit_transform([[2, 8, 4, 5],
[6, 3, 0, 8],
[5, 4, 9, 1]])
print(... |
6bb9ff35009594cd1d1ecf0eb03247a0ca9c8314 | BrucePython/Deep_Learning | /02_Machine_Learning/07_转换器.py | 617 | 3.578125 | 4 | # fit获取【训练数据】的均值和方差, 为后面的transform做准备,
# transform测试和训练数据都能用, 使用均值和方差进行无量化
# fit_transform 仅限训练数据使用
# 测试数据的均值和方差用fit获取,然后在用transform进行无量化
# 先划分,再特征工程
from sklearn.preprocessing import StandardScaler
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2,3],[4,5,30]])
std1 = StandardScaler()
data1 = st... |
3e219c794ce22d0d97aaa6b45717717b337d0ca5 | 2019-fall-csc-226/a02-loopy-turtles-loopy-languages-mualcinp-a02 | /a02_mualcinp.py | 1,447 | 4.28125 | 4 | # Author: Phun Mualcin
# Username: mualcinp
# Assignment: A02: Exploring Turtles in Python
# Purpose: Draw something that brings a smile to your face using uses two turtles and one loop
import turtle
wn = turtle.Screen()
wn.bgcolor('black')
shape = turtle.Turtle()
turtle.color('blue')
turtle.pensize(20)
turtle... |
0fa67daf4e49de157e26c21a9bdbb07c34905332 | wjy5446/Hacker-rank | /30-Days-of-Code/Day-8-DictionariesAndMaps.py | 355 | 3.8125 | 4 | number_name = int(input().strip())
dict_phone = {}
for i in range(number_name):
name, phone = input().strip().split(" ")
dict_phone[name] = phone
for i in range(number_name):
query_name = input().strip()
if query_name in dict_phone:
print("{}={}".format(query_name, dict_phone[query_name]))
... |
1643714aa591824054283f7b42a9191af770ff96 | Mich-ikarus/Pyprojects | /11-1.py | 159 | 3.609375 | 4 | school = {'1a':20, '2б':21, '3в':22, '4г':23, '5д':24, '6а':25, '7б':26, '8в':27, '9г':28, '10д':29, '11а':30}
print(school)
print(school['2б'])
|
8a87a199187459bc7867b674dc1c612fef9d91e4 | ArnolValadez/python-exercises | /list_comprehensions.py | 4,580 | 4.4375 | 4 | # 17 list comprehension problems in python
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# Example for loop solution to add 1 to each number in the list
numbers_plus_one = []
for number in numbers:
... |
af78eff8f8144b921b6292df8dfdc2e1faf3d6fb | tonton06/python | /exercicios/ex038.py | 409 | 3.96875 | 4 | print('-'*30)
print('COMPARADOR DE NÚMERO INTEIROS')
print('-'*30)
n1 = int(input('Digite o primeiro número inteiro: '))
n2 = int(input('Digite o segundo número inteiro: '))
print('-'*30)
if n1 > n2:
print('O primeiro número é MAIOR!'.format(n1, n2))
elif n2 > n1:
print('O segundo número é MAIOR!'.format(n2, n1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.