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 |
|---|---|---|---|---|---|---|
01667c714c2976cc4ab6e279157274bde23eeabd | tonton06/python | /exercicios/ex040.py | 509 | 3.890625 | 4 | print('--'*15, '\033[32m')
print('MÉDIA')
print('\033[m-=-'*15, '\033[34m')
note1 = float(input('Digite a primeira nota: '))
note2 = float(input('Digite a segunda nota: '))
print('\033[m--'*15)
m = (note1 + note2) / 2
print('--'*15, '\033[31m')
if m < 5:
print('Sua média foi {:.1f}, você está REPROVADO!'.format(m))... |
ca6f78c628ddeb705adfff85e8477202ff47fcae | tonton06/python | /exercicios/ex061.py | 396 | 3.671875 | 4 | from time import sleep
print('--'*25)
print('PA')
print('--'*25)
valor = int(input('Valor inicial: '))
razao = int(input('Razão: '))
print('--'*25)
conta = 10
soma = valor
print('{}'.format(valor), end='')
while conta != 1:
soma = soma + razao
conta -= 1
print(' - {}'.format(soma), end='')
print('... |
a11b892ce73a4fa41c6f3f9d11afa15e8532bed5 | tonton06/python | /exercicios/ex049.py | 118 | 3.953125 | 4 | n = int(input('Digite um número inteiro: '))
for c in range(11):
print('{} x {:>2} = {:>2}'.format(n, c, n * c))
|
15a36f7c1ba5e6086cd60fc8df740f07096fe15f | tonton06/python | /exercicios/ex081.py | 488 | 3.96875 | 4 | values = []
choice = ' '
while choice != 'N':
num = int(input('Digite um número: '))
values.append(num)
choice = ' '
while choice not in 'SN':
choice = str(input('Continuar? [S/N] ')).upper().strip()[0]
values.sort(reverse=True)
print(f'Você digitou {len(values)} números')
print(f'Lista em o... |
8c29efd2a47c9a3c6c1e83b62e672acdc2eb0d4e | tonton06/python | /exercicios/ex054.py | 334 | 3.78125 | 4 | from datetime import date
cont = 0
cont2 = 0
for c in range(1, 8):
year = int(input('Digite o ano de nascimento da {}° pessoa: '.format(c)))
age = date.today().year - year
if age >= 21:
cont += 1
print('\n\033[32m{} pessoas são MAIORES de idade\n\033[31m{} pessoas são MENORES de idade'.format(cont, ... |
a5658d19bd8b14358d109317b266a59cc3dbc0e6 | tonton06/python | /exercicios/ex007.py | 131 | 3.78125 | 4 | n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
d = (n1 + n2) / 2
print('A média = {:.1f}'.format(d))
|
fc5f756c408f381f025de0b6f5953f3064c9f746 | tonton06/python | /exercicios/ex058.py | 493 | 3.640625 | 4 | from random import randint
pc = randint(0,10)
print('--'*15)
print('De 0 a 10, tente adivinhar o número que o computador pensou')
print('--'*15)
count = 0
num = 11
while num != pc:
num = int(input('Faça sua escolha: '))
count += 1
if num != pc:
if pc - num > 0:
print('\033[34mMais...... |
12ac8fbf3cd36200da3a8624a4a80372613f9bec | tonton06/python | /exercicios/ex045.py | 1,413 | 3.5 | 4 | from random import choice
from time import sleep
print('\033[34m-=-'*15)
print('JOKENPÔ')
print('-=-'*15)
print('VOCÊ vai jogar jokenpô com o computador!')
list = [1, 2, 3]
pc = choice(list)
print('-=-'*15)
print('\033[31m-=-'*15)
print('[ 1 ] PEDRA')
print('[ 2 ] PAPEL')
print('[ 3 ] TESOURA')
player = int(input('Esco... |
d8f6aaa3fceb269a4771522f46efcbf3e49470b7 | JenishPatel99/CMPUT274 | /Weekly Exercise/Deck of Cards/deck.py | 5,563 | 4 | 4 | import sys
import os.path
class Deck:
'''
Stores playing cards
'''
def __init__(self, cards):
# Intializes attribute deck to object self.
self.__deck = list(cards)
def deal(self):
''' Deals out the top card in the deck. In this case the top card
is index 0 of self... |
5539aff59a144f14cdf5fb1779bfd3fa9effc8cf | zdenekmaxa/scripts-utils | /other/mp3_sort_transfer.py | 2,126 | 3.5625 | 4 | """
MP3 disk sort script.
Copies album folders from two source locations to a third, sorted one,
into alphabetical subdirectories.
Run from the MP3 disk root.
"""
import os
import sys
import shutil
def process_dir(base_dir, dir_name, target_dir):
"""
Process 1 album directory.
Sort according it's i... |
3fbb4c019bae973d5181e0f5c16168f2b4a79d83 | jetkoooo/COMP4621-2016S | /lab2/thread-server.py | 937 | 3.625 | 4 | import socket
import threading
class ServerThread(threading.Thread):
def __init__(self, client_socket, addr):
self.socket = client_socket
self.addr = addr
threading.Thread.__init__(self)
def run(self):
# receive no more than 1024 bytes from the client
line = self.socket.recv(1024)
# send the reversed ... |
44b1b2af47b75a71a5fd37f284730a0cd5b29690 | LENAYL/pysublime | /MyStack_225.py | 2,482 | 4.1875 | 4 | # 用队列实现
#
# from queue import Queue
# class MyStack(object):
#
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.q1 = Queue()
# self.q2 = Queue()
#
# def push(self, x):
# """
# Push element x onto stack.
# :type x: int... |
1fda48ef83af42a4f383fc1c1b3ab1ce31a2e9f8 | bell-bot/BinaryTree | /Node.py | 858 | 4.09375 | 4 | class Node:
def __init__(self, value):
self.parent = None
self.left = None
self.right = None
self.value = value
def insert(self, value):
if value < self.value:
#Insert into left subtree
if self.left is None:
self.left = Node(valu... |
1da76f8ce2e80ab5fd58a60b15c0370bdf667001 | cxjdavin/cryptopals | /challenge12.py | 4,219 | 3.578125 | 4 | '''
URL: http://cryptopals.com/sets/2/challenges/12
Title: Byte-at-a-time ECB decryption (Simple)
Copy your oracle function to a new function that encrypts buffers under ECB mode using a consistent but unknown key (for instance, assign a single random key, once, to a global variable).
Now take that same function and ... |
a7be90ce0dfe84e623bfe633c307d63672c8310f | farokr/i-ching | /hexagram_key.py | 2,006 | 3.8125 | 4 | odd = "_____________"
even = "_____ _____"
Trigrams = {
(odd, odd, odd):'Heaven',
(even, even, odd):'Thunder',
(even, odd, even):'Water',
(odd, even, even):'Mountain',
(even, even, even):'Earth',
(odd, odd, even):'Wind',
(odd, even, odd):'Fire',
(even, odd, odd):'Lake',
}
Hex_Meaning = {
("Heaven", "Heave... |
2ac3917d0fc7f22b63d0930f9630d305b0332cdf | ravigupta19/HackerRank | /Strings/Designer_Door_Mat.py | 466 | 3.5 | 4 | #Mat size must be X. ( is an odd natural number, and is times .)
#The design should have 'WELCOME' written in the center.
#The design pattern should only use |, . and - characters.
N = 11
M = 33
#N, M = map(int,input().split()) # More than 6 lines of code will result in 0 score. Blank lines are not counted.
for i in ... |
a9565f7fb5ad58b625b79eb71cf30050b722b059 | mohithsai28/DataStructuresAnd-Algorithm-Implementation | /Recursion-Algorithm/Recursion.py | 506 | 3.875 | 4 |
def recursion(global_counter):
print(global_counter)
if(global_counter>3):
return "Done"
global_counter += 1
return recursion(global_counter)
#011234
def fibanocci(n):
if(n<2):
return n
return fibanocci(n-1)+fibanocci(n-2)
def reversestring(string):
n=len(string)
if(n... |
213e1d396a2af39afa1b4d3e7f22a95089338f4a | mohithsai28/DataStructuresAnd-Algorithm-Implementation | /Sorting-Algorithm/Sorting.py | 2,086 | 3.578125 | 4 |
def bublesort(num):
for k in range(len(num)):
for m in range(len(num)-1):
if(num[m]>num[m+1]):
temp=num[m]
num[m]=num[m+1]
num[m+1]=temp
else:
continue
return num
def selectionsort(num):
for n in range(len(num... |
7cc989b91937f5e057f0b60679bce34608d5f938 | dliedtka/basketball | /221_code/code/algorithm/stats/rmse.py | 453 | 3.671875 | 4 | def compute_rmse(list1, list2):
list_length = len(list1)
assert list_length == len(list2)
compute_list = []
# subtract
for i in range(list_length):
compute_list.append(list1[i] - list2[i])
# square
for i in range(list_length):
compute_list[i] = compute_list[i] ** 2.
# ... |
ae91aed3e0a57da23e13a1547c39dd487a445653 | FERCAMPSIL/TesteBack-End-FCAMARA | /exercicio6.py | 936 | 3.765625 | 4 | class Retangulo:
def __init__(self, ladoA, ladoB):
self.ladoA = ladoA
self.ladoB = ladoB
def trocaLados(self, ladoA, ladoB):
self.ladoA = ladoA
self.ladoB = ladoB
def retornaLados(self):
return (self.ladoA, self.ladoB)
def perimetro(self):
return 2 * self.... |
eb4f58535ef87535e43ce24bdc7b275100c86879 | AlpacaMax/Algorithm_Miscellaneous | /Algorithms/QuickSort.py | 840 | 3.8125 | 4 | import random
def QuickSort(lst):
def partition(lst, low, high):
left = low
mid_value = lst[high]
while (lst[left] < mid_value):
left += 1
right = left
while (right <= high):
if (lst[right] < mid_value):
lst[left], lst[right] = lst[ri... |
95ebef60b694084d7ada5b487efa06dca6d99e36 | dnslab/Sypy | /interpreter/constraintstack.py | 5,268 | 3.953125 | 4 | """
Implementation of the constraint stack.
"""
class Constraint(object):
"""
This class is an abstract representation of
a constraint.
"""
__rvalue = None
__lvalue = None
__op = None
__connective = None
__type = None
__explored = False
def __init__(self, l, r, op, l_s=True... |
972bb913ddd1cf4c4d351b57bd0756952f1a5ada | chiefmo/csb351 | /a4/player.py | 7,627 | 3.625 | 4 | #!/usr/bin/python3
### CSCI-B 351 / COGS-Q 351 Fall 2021
### Framework code copyright 2020 B351/Q351 instruction team.
### Do not copy or redistribute this code without permission
### and do not share your solutions outside of this class.
### Doing so constitutes academic misconduct and copyright infringement.
... |
d95d3026e72ce7b26d255b457068a1ed7ab78857 | Dermot10/Dice_roll_program | /dice_roll_app.py | 1,127 | 3.875 | 4 | import tkinter
import PIL
from PIL import ImageTk
from PIL import Image
import random
# Initialisation of window
window = tkinter.Tk()
window.geometry('400x400')
window.title('Dermots Dice Roll')
l0 = tkinter.Label(window, text="")
l0.pack()
l1 = tkinter.Label(window, text="Hello from Dermot!",
... |
106a4e344c2372f849e26c0ec58358d57bf288eb | shaygrose/Planets-Aliens-Explosions | /planets-aliens-explosions.py | 18,360 | 4.03125 | 4 | #CMPT 120 D100
#SHAYNA GROSE
#STUDENT ID: 301308729
#PLANETS, ALIENS and EXPLOSIONS
#CHOOSING WHICH FILE TO OPEN
def choosing_board(board):
if board=="d": #default board
the_file = "PlanetsData1.txt"
else:
the_file=board #user can choose another board
return the... |
033efafabba4f32c38483af61e04b833392ca45f | LuthfiSugara/python-numpy | /testcase1.py | 130 | 3.609375 | 4 | import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = [1, 2, 3, 4, 5]
print(a)
print(b)
a = a + 1
b = b + [1]
print(a)
print(b) |
191450c16b2d250fab6a0b0bc79e9128f7e647e2 | sbr00ks/sandPit | /wip/pyCookBook.py | 2,783 | 3.640625 | 4 | import os
import sys
#print(os.environ)
#==============================================================================
# print(sys.argv)
# l=[1,2]
# for n in range(10):
# l.append(l[-1]+l[-2])
#
# a,b= 0,1
#==============================================================================
#while b <10:
# ... |
163d79e904d442ee971f10f698b79a7ee7bf85fa | micahjonas/python-2048-ai | /game.py | 2,514 | 4.3125 | 4 | # -*- coding: UTF-8 -*-
import random
def merge_right(b):
"""
Merge the board right
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_right(test)
[[0, 0, 2, 8], [0, 2, 4, 8], [0, 0, 0, 4], [0, 0, 4, 4]]
"""
def reverse(x):
return list(reversed(x))
t = m... |
7a58b41dc03f70d6a1cc96541e180c13fbfec8b0 | alexander-deb/Calculator-3.0 | /main.py | 2,400 | 3.625 | 4 | import math
def solve_primer(primer):
operation = []
numbers = []
last_key = 0
flag = False
for key in range(len(primer)):
if primer[key] < "0" or primer[key] > "9":
if (key > 0 and primer[key] == "-" and (primer[key-1] < "0" or primer[key-1] > "9")) or key == 0 and primer[key] ... |
aa8e0c892653fa7206dfa9f4333d6b07ae3ffaa0 | Czypser/Sigil | /API/Budget.py | 1,895 | 3.75 | 4 | def Budget(body)
WeeklyBudget = 15
DailyBudget = 10
currency = "$"
splittest = Budget.split()
for InputWords in splittest:
word = InputWords.lower()
if word == "weekly":
word = "We found the word weekly"
keyword = "weekly"
break
if word == "daily":
print ("we found t... |
af70e97d7ff53746e3476ca0fdcbb975c155f4bb | HamPUG/meetings | /2023/2023-04-12/adc_1.py | 1,221 | 3.546875 | 4 | """
MicroPython program for Raspberry Pi Pico module
A 100ohm trim pot is between +3.3V and Ground.
Adjusting the pot changes the voltage fed to the Analog to Digital converter.
Micropython produces a 16 bit value of the voltage, which is then converted to 12 bit.
Reference:
https://github.com/micropython/micropython/... |
6205d4a230221917c9bd7f1485d004987b397245 | HamPUG/meetings | /2022/2022-11-14/ian/prime_number_locator.py | 37,717 | 3.53125 | 4 | #!/usr/bin/env python3
#
# Program: prime_number_locator.py
#
# Objective: Digital Technologies - NCEA Level 3 - example program
# Locates prime numbers.
# Uses the tlinter GUI
# Progress bar uses determinate mode while locating prime
# numbers
#
# Written... |
99d6b46244f9b61f3e0d41b56abfdd455c3eecfa | HamPUG/meetings | /2015/2015-07-13/ian/messagebox_demo.py | 10,344 | 4.03125 | 4 | # messagebox_demo.py
# Program to demonstrate functionality of the tkinter.messagebox module
# https://github.com/HamPUG/
# Presentation for Hamilton Python User Group meeting - 2015 July 13
# Author: Ian Stewart
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
HELP_MESSAGE = """Help Infor... |
f6422f0594441635eac2fd372428aa160ca3bbb3 | HamPUG/meetings | /2017/2017-05-08/ldo-generators-coroutines-asyncio/yield_expression | 1,190 | 4.53125 | 5 | #!/usr/bin/python3
#+
# Example of using “yield” in an expression.
#-
def generator1() :
# failed attempt to produce a generator that yields an output
# sequence one step behind its input.
print("enter generator")
value = "start"
while value != "stop" :
prev_value = value
print("abo... |
b7fa25a2ed070098cc0efdf0b1a99244b40f1b78 | gh-sim/2020-Python-Code | /ch04/04-06nestedmenu.py | 701 | 3.609375 | 4 | #커피와 주스 선택 이후 메뉴 선택
category = int(input('원하는 음료는? 1. 커피 2. 주스'))
if category == 1:
menu = int(input('번호 선택? 1.아메리카노 2. 카페라테 3. 카푸치노'))
if menu == 1:
print('1. 아메리카노 선택')
elif menu == 2:
print('2.카페라테 선택')
elif menu == 3:
print('3.카푸치노 선택')
else :
menu = int(in... |
809f98346436046cf7c796ea3937eeb5721be42e | harshgeek4coder/Movie-Recommendation-System-Using-Collaborative-Filtering | /Movie Recommendation System Using Collaborative Filtering.py | 2,994 | 3.796875 | 4 | # %%
"""
# COLLABORATIVE BASED MOVIE RECOMMENDER SYSTEM :
"""
# %%
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import sparse
from sklearn.metrics.pairwise import cosine_similarity
# %%
ratings=pd.read_csv('ratings.csv')
movies=pd.read_csv('movies.csv')
# %... |
681386bf8e11b83cc6c254584c4c71a1e1262684 | stjordanis/statinf | /statinf/GenerateData.py | 988 | 3.65625 | 4 | import numpy as np
import pandas as pd
def generate_dataset(coeffs, n, std_dev, intercept = 0.0):
# We calculate the number of predictors, and create a coefficient matrix
# With `p` rows and 1 column, for matrix multiplication
p = len(coeffs)
coeff_mat = np.array(coeffs).reshape(p, 1)
# Similar as ... |
2e24dc984ef31980077772305e0610e3fb8e64b6 | trofiv-IFMO/IFMO-Theory-Of-Decisions-Making | /org/trofiv/lab2/lab2.py | 1,458 | 3.703125 | 4 | # coding=utf-8
from colorama import Fore, Style
from nash import Game
from numpy import array
def nash_equilibrium(*args):
"""
Calculates the Nash equilibrium
:param arr: game matrix
"""
if len(args) == 1:
rps = Game(args[0])
elif len(args) == 2:
rps = Game(args[0], args[1])
... |
a5dc998f2fce218c3f7f85cc211d1a9fffdb4b49 | harshildp/python_oct_2017 | /eric.jones/Mathdojo/mathdojo.py | 822 | 3.796875 | 4 | class MathDojo(object):
def __init__(self):
self.result = 0
def add(self, arg1, *arg2):
self.result += arg1
for idx in list(self.recursetree(arg2, (list, tuple))):
self.result += idx
return self
def subtract(self, arg1, *arg2):
self.result -= arg1
... |
809821c877f452cfffc42a13fe5ed818c2f05621 | MukundhBhushan/micro-workshop | /tectpy/pyeg/pop.py | 268 | 3.71875 | 4 |
#! python
# huge list making
nn=1000000
a = []
i=0
while i
#! python
# Using Lists as Stacks
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print stack
x=stack.pop()
print "popped ",x
print stack
x=stack.pop()
print "popped ",x
x=stack.pop()
print "popped
|
3af6228c9d8dcc735c52ae7d8375f007145ffe98 | MukundhBhushan/micro-workshop | /tectpy/if.py | 235 | 4.15625 | 4 | num=int(input("Enter the number to be tested: "))
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
|
8798004b0384fe23490e41a6874f9b38801c122b | micdsol/PythonCrashCourse | /chapter5.py | 6,081 | 4.3125 | 4 | #chapter 5 - dictionaries
# chapter: completed - test: complete
# chapter 5 - if statements
# 5-11 try it yourself
# 5-11. Ordinal Numbers:
# numbers = ['1','2','3','4','5','6','7','8','9']
#
# for number in numbers:
# if number == '1':
# print(numbers[0] + "st")
# elif number == '2':
# pri... |
f9a1d761abdadf199cecbc2e79d71c689cb157f1 | pbhattar/Reinforcement-Learning-Research | /count2.py | 1,003 | 3.515625 | 4 | '''Finds number of combs for BlocksWorld'''
def subset_sum_recursive(numbers,target,partial, combinations):
s = sum(partial)
partial = sorted(partial)
#check if the partial sum is equals to target
if s == target and partial not in combinations:
#print "sum(%s)=%s"%(partial,target)
#print pa... |
01161066374f4d39a7de50681c3d297fd8719bc1 | rachelissmart/python | /gitpro/python/ex18.py | 1,140 | 4.03125 | 4 | class organism(object):
def __init__(self):
self.can_die=True
self.propogation=True
def ppt1(self):#properties1
print "As an organism \n\t-They can die.\n\t-They can propogate.\n"
class animal(organism):
def __init__(self):
super(animal,self).__init__()
self.can_move=True
self.dont_need_water=False
... |
0d8725cf7b5499b7ba1cd06400d34faea4e0cccd | rachelissmart/python | /gitpro/python/ex4.py | 375 | 3.703125 | 4 | #ex4.1
pi=3.14
r=6378*1000
c=2*pi*r
print "the circumference of the Earth's equator: %f" %c,"m"
#ex4.2
x="I like you."
y="You hate me."
print y+x
print x*2
print y*3
#ex4.3
a1="g"
a2="o"
a3="o"
a4="d"
print a1,a2, a3,a4
print a1+a2+a3+a4
#ex4.4
print"I am 5'8\" tall \'a \" b \n c \r c "
shoppingList= "list:\n\t*cat ... |
b11cfcd31d69969da135bdacae8caa6377dd15cc | JohnBSmith/misc | /math/generic/complex.py | 2,278 | 3.65625 | 4 |
class Complex:
def __init__(self, x, y):
self.re = x
self.im = y
def __str__(self):
return "Complex({}, {})".format(self.re, self.im)
def __repr__(self):
return "Complex({}, {})".format(self.re, self.im)
def __eq__(self, rhs):
if isinstance(rhs, Complex):
... |
49be0ff4752cfacace01a69eeb722b07b6b64e53 | shuysman/Rosalind | /transcribe_dna_rna.py | 309 | 3.5625 | 4 | #!/usr/bin/python3
# http://rosalind.info/problems/rna/
dna_file = open("/home/steve/Dropbox/Rosalind/rosalind_rna.txt")
dna_string = dna_file.readline().strip()
base_key = {"A": "A", "G": "G", "C": "C", "T": "U"}
rna_string = ""
for base in dna_string:
rna_string += base_key[base]
print(rna_string)
|
736547d9c7bd32c9b2dca662c287cedb11e407be | ryotokuro/hackerrank | /algorithms/solved/hurdleRace.py | 1,093 | 3.765625 | 4 | # Dan is playing a video game in which his character competes in a hurdle race.
# Hurdles are of varying heights, and Dan has a maximum height he can jump.
# There is a magic potion he can take that will increase his maximum height by unit for each dose.
# How many doses of the potion must he take to be able to jump al... |
a4539d4d5d6e979b2dd473ce01271e5af7f47984 | ryotokuro/hackerrank | /algorithms/solved/angryProfessor.py | 1,298 | 3.84375 | 4 | # HACKER RANK CHALLENGE: https://www.hackerrank.com/challenges/angry-professor/problem
# A Discrete Mathematics professor has a class of students.
# Frustrated with their lack of discipline,
# he decides to cancel class if fewer than some number of students are present when class starts.
# Arrival times go from on time... |
6feb4826d93d7085b66184e026622a0d52ad866a | ryotokuro/hackerrank | /algorithms/solved/repeatedString.py | 1,405 | 3.90625 | 4 | # PROBLEM
# Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.
# Given an integer, n, find and print the number of letter a's in the first n letters of Lilah's infinite string.
# EXAMPLE
# If the string s = 'abcac' and n = 10,
# The substring we consider is 'abcacabcac', the f... |
8fc620212aeb8af5522d4fbd782a7f0bf640f25f | ryotokuro/hackerrank | /algorithms/solved/timeConversion.py | 325 | 3.703125 | 4 | def timeConversion(s):
twentyFour = s[:-2]
if s[-2:] == "PM":
if s[:2] != "12":
twentyFour = str(int(s[:2]) + 12) + s[2:-2]
else:
if s[:2] == "12":
twentyFour = "00" + s[2:-2]
return twentyFour
if __name__ == '__main__':
s = input()
print(timeConversion... |
cbb04cf8cb95ba848632201b8cc7f58d13d1a905 | ryotokuro/hackerrank | /algorithms/unsolved/circularArrayRotation.py | 1,348 | 3.6875 | 4 | # circularArrayRotation has the following parameter(s):
# - a: an array of integers to rotate
# - k: an integer, the rotation count
# - queries: an array of integers, the indices to report
# INPUT FORMAT
# The first line contains 3 space-separated integers:
# 1. n (the number of elements in the integer array)
# 2. k (... |
f9f0e8f9212598847750967c8898eefed9e441ed | ryotokuro/hackerrank | /interviews/arrays/arrayLeft.py | 900 | 4.375 | 4 | #PROBLEM
# A left rotation operation on an array shifts each of the array's elements unit to the left.
# For example, if left rotations are performed on array , then the array would become .
# Given:
# - an array a of n integers
# - and a number, d
# perform d left rotations on the array.
# Return the updated array ... |
f332b97e2430d129056a851da47abb13eb2c2f95 | ryotokuro/hackerrank | /algorithms/solved/staircase.py | 259 | 3.90625 | 4 | def staircase(n):
for i in range(1, n+1):
for spaces in range(n-i):
print(" ", end="")
for tags in range(i):
print("#", end="")
print("")
if __name__ == '__main__':
n = int(input())
staircase(n)
|
9af20e6ee68952b2f0b61685ce406d13c770cc00 | ryotokuro/hackerrank | /w36/acidNaming.py | 828 | 4.1875 | 4 | '''
https://www.hackerrank.com/contests/w36/challenges/acid-naming
Conditions for naming an acid:
- If the given input starts with hydro and ends with ic then it is a non-metal acid.
- If the input only ends with ic then it is a polyatomic acid.
- If it does not have either case, then output not an aci... |
67eccc154fbefe3dd8704335a80fa5685f9b1ac7 | garvitsaxena06/Learning-Paths-Content | /Add 2 numbers/app.py | 159 | 4.15625 | 4 | #to take 2 numbers from user and print their sum
number1 = float(input("Enter number1: "))
number2 = float(input("Enter number2: "))
print(number1 + number2)
|
3a9f486d54fe15bcea60d916047e4c478ca20f85 | fillipe-felix/ExerciciosPython | /Lista02/Ex004.py | 355 | 4.3125 | 4 | """
Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
"""
letra = str(input("Digite uma letra para verificar se é vogal ou consoante: ")).upper()
if(letra == "A" or letra == "E" or letra == "I" or letra == "O" or letra == "U"):
print(f"A letra {letra} é uma vogal")
else:
print(f"A l... |
13fe9b2fd17e5155735605ec521b60c05787ed25 | fillipe-felix/ExerciciosPython | /Lista01/Ex006.py | 205 | 4.03125 | 4 | """
Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
"""
raio = float(input("Digite a area do circulo: "))
area = 3.14 * (raio ** 2)
print(f"A area do circulo é de {area}") |
a6467f4c2433d69827d7dffd4152fbab324bd168 | fillipe-felix/ExerciciosPython | /Lista02/Ex013.py | 582 | 3.984375 | 4 | """
Faça um Programa que leia um número e exiba o dia correspondente da semana.
(1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido.
"""
dia = int(input("Digite o dia da semana Ex: 1 = \"Domingo\": "))
if(dia == 1):
print("Domingo")
elif(dia == 2):
print("Segunda-Feira")
elif(di... |
b9140c8a165ef5eb1e6e49679acd2f0f0c42b2a8 | callambulance/music_library | /main_program.py | 3,540 | 3.875 | 4 | import file_handling
import display
import music_reports
def main():
option = None
while option != '0':
menu()
try:
option = user_input("\nType an option: ")
options(option)
except KeyError:
print_massege("\nThere is no such option!")
except ... |
6b3263a49fe44121dbd451844d6f2d0616b5ce99 | BenPalmer1983/libBP | /libBP/data/elements.py | 2,899 | 3.8125 | 4 | #!/usr/bin/python
#################################################################################
# Python Script
#
#################################################################################
# Import
import os, sys, time, shutil, string;
def subString(inputStr, start, length):
a = start-1
output = inputSt... |
669722835768c712e1e57ddc3b1ad44a2548a6f6 | blueninj0r/python-euler | /solution3.py | 638 | 3.71875 | 4 | import math
import itertools
def naiveprimes():
primes = [2]
yield 2
curr = 3
while True:
for p in primes:
if curr % p == 0:
break
else:
primes.append(curr)
yield curr
curr+=1
print(primes)
def primefactors(n):
pri... |
227d6df3bb63b4f76ce79ada15b017a9bab593bc | packiashri/blackjack | /blackjack.py | 5,702 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 11:10:10 2021
@author: sree
"""
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'... |
62ad0cdecbb43d25fbae24b2514210a2cd9e56dc | amarjeet-kaloty/Data-Structures-in-Python | /linkedList.py | 1,320 | 4.125 | 4 | class node:
def __init__(self, data=None):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head = node()
#Insert new node in the Linked-List
def append(self, data):
new_node = node(data)
cur_node = self.head
while (c... |
efb5746c5ebea6ef1085a43998618e5ea5039450 | kaizer1v/pyback | /pyback.py | 1,508 | 3.671875 | 4 | '''
This is a command line application to compress/backup folders
USAGE
`python pyback path/to/source -d compressed_file_name`
'''
import os
import argparse
from shutil import make_archive
# _DESTINATION = '/Users/i536332/Documents/personal_p/py/DEFAULT_DEST_FLDR'
_FORMATS = ['tar', 'gztar', 'zip', 'bztar', 'xztar'... |
9e08e1dd950692a5703393a369c8ef8c6aa229a4 | xaar1982/codesignal | /commonCharacterCount.py | 356 | 3.59375 | 4 | def commonCharacterCount(s1, s2):
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","r","s","t","u","w","q","x","y","z"]
common_sum = 0
num = 0
for i in alphabet:
s1_num = s1.count(i)
s2_num = s2.count(i)
num = min(s1_num,s2_num)
common_sum+... |
1df650fcbe6d4bdc28776aa059cc059e09b055da | xaar1982/codesignal | /isLucky.py | 289 | 3.515625 | 4 | def isLucky(n):
dl = len(str(n))
half = int(dl/2)
int_to_string = str(n)
first_half = list(map(int, int_to_string[:half]))
second_half = list(map(int, int_to_string[half:]))
if sum(first_half) == sum(second_half):
return True
else:
return False
|
5dcf5f52a0dc8a563e863feee89709db27f6688d | nstoltzfus3/migrationReport | /src/PsycoConnection.py | 1,965 | 3.546875 | 4 | import psycopg2
class PsycoConnection:
'''
Custom wrapper for Psycopg2 connection with a postgres database. Facilitates making connections and
maintaining cursors for ease of use.
'''
def __init__(self, PSQLdb):
self.psqldb = PSQLdb
self.conn = None
self.establishConnectio... |
51a785d5904ceb5d9e432a17c5e002a90156d272 | Sinchiguano/repo_project | /src/thesis_pkg/yumi_main/src/numpypractice/boolean_indexing.py | 1,211 | 3.890625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 Cesar Sinchiguano <cesarsinchiguano@hotmail.es>
#
# Distributed under terms of the BSD license.
"""
"""
import numpy as np
# create a 3x2 array
an_array = np.array([[11,12], [21, 22], [31, 32]])
print(an_array)
# create a filter w... |
473bc9cb99ddb647b9553d5d2fb51d05436317a3 | Sinchiguano/repo_project | /src/thesis_pkg/yumi_main/src/sources/old/python_refresher_ML/temp1.py | 2,052 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 Cesar Sinchiguano <cesarsinchiguano@hotmail.es>
#
# Distributed under terms of the BSD license.
"""
"""
x = 4
y = 5
z = x + y
print(z)
#Python Collections
my_list=list()
my_list = ['a', 'b', 'c', 'd']
print('my list ',my_list)
varie... |
95754c0f8dfaeb8b76f2ed013793d5e533646b0d | amacuga/python-fundamentals | /functions.py | 161 | 3.765625 | 4 | def gcd(a, b):
"""
Returns the greates conmmon divisor of a and b.
"""
while b > 0:
a, b = b, a % b
return a
print(gcd(50, 20))
print(gcd(22,143)) |
ad8bd715dbf9035dcfce5304792a1bc980a2f3dc | ROODAY/playground | /textadventure.py | 1,374 | 3.890625 | 4 | running = True
class Room(object):
first = None
second = None
description = None
isend = False
visited = 1
def __init__(self, desc, isend):
self.desc = desc
self.isend = isend
def setConnects(self, first, second):
self.first = first
self.second = second
def checkend(self):
if self.isend:
return... |
da4e43d0cadfc4137a4f92da26d32203a9c07e54 | GilbertoSavisky/Python | /estruturas-de-dados.py | 580 | 4.15625 | 4 | pessoa_1= {'nome':'Gilberto Savisky', 'idade': 41, 'peso': 75}
pessoa_2 = {'nome':'João Arruda', 'idade': 28, 'peso': 65}
pessoa_3 = {'nome':'Reinaldo Cavalcante', 'idade': 53, 'peso': 87} # dicionario (dict)
lista_pessoas = [pessoa_1, pessoa_2, pessoa_3] # lista (list)
minha_tupla = ('Amadeu', 'Lourenço') # Tupla (t... |
eda28fb6db29f379911a18a97fc319c8996847f6 | GilbertoSavisky/Python | /aula 5-estruturas-de-laco.py | 1,076 | 3.984375 | 4 |
lista_times = [
'América Mineiro','Atlético Mineiro','Atlético Paranaense','Bahia','Botafogo','Ceará','Chapecoense','Corinthians','Cruzeiro','Flamengo','Fluminense','Grêmio','Internacional','Palmeiras','Paraná','Santos','São Paulo','Sport','Vasco da Gama','Vitória']
#for simples
for i in lista_times:
print(i)
pri... |
c613d2e1e647c5aa8493ebc48bb8f71287f6335b | present0603/Hardway | /ex32.py | 522 | 3.53125 | 4 | # -*- coding: utf8 -*-
the_count = [1, 2, 3, 4, 5]
fruits = ['사과', '귤', '배', '살구']
change = [1, '십원', 2, '백원', 3, '오백원']
# 첫 번째 for 문은 list를 따라 돕니다.
for number in the_count:
print "이 수는 %d" % number
for fruit in fruits:
print "과일 종류: %s" % fruit
#
for i in change:
print "받은 잔돈 %s" % i
#
elements = []
#
for i ... |
e84ebb478878b0eba4403ddca10df99dda752a82 | martinloesethjensen/python-unit-test | /star_sign.py | 960 | 4.125 | 4 | def star_sign(month: int, day: int):
if type(month) == int and month <= 12 and type(day) == int and day <= 32: # todo: test case on .isnumeric()
if month == 1:
if day <= 20:
return "Capricorn"
else:
return "Aquarius"
elif month == 5:
... |
1a5387c3862973d9dbca75774628f559c46bf3cf | poojithayadavalli/Dynamicprograming | /sum as k integers.py | 792 | 3.609375 | 4 | """
Given N and K. The task is to find out how many different ways are there to represent N as the sum of K non-zero integers.
Input:
First line contains N
nextline contains K
Output:
print the number of ways
Example:
Input:
5
3
Output:
6
Explanation:
The possible combinations of integers are:
( 1, 1, 3 )
( 1, ... |
2bae5b3aaa3901a9746e858f7a920f05da6851d1 | Snehashis100/Mini-Python-Projects | /Health Management/Health_Management_System.py | 3,886 | 3.796875 | 4 | def showDate():
import datetime
return datetime.datetime.now().strftime("%Y-%m-%d [%H:%M]")
def retrieveData(file_name):
with open(file_name) as f:
content = f.read()
if len(content) == 0:
print("*****empty*****")
else:
print(content)
f.close()
def i... |
a3e2b4f8cc6579e40037549c7fa0849a5f2748a0 | lemonking21/Python-Templates | /selectFileFromDir.py | 1,273 | 3.828125 | 4 | ################################################################################
# Created By Kyle Krug
# Created on 7/9/2019
# Created to form a tempate on how to Select a file from the computer Directory
# using a diaolog box
################################################################################
from ... |
e04765266241dc275d6c6ee30dd29d9bddd27a4e | Zarro1008/groupLearning-Python-100-Days | /Day21-30/practice_code/R_Day_23.py | 2,717 | 3.6875 | 4 | import sqlite3
def disp_menu():
print("學生資料編輯")
print("".center(50, "-"))
options = ["1.新增", "2.編輯", "3.刪除", "4.顯示所有學生", "0.結束"]
for i in options:
print("{:<s} {:<2s}".format(i, ''), end='')
print()
print("".center(50, "-"))
def append_data():
while True:
no = int(input("... |
313ff1ca69912ad0528550bf71c56e14c8076411 | Zarro1008/groupLearning-Python-100-Days | /Day01-15/pratice_code/R_DAY_06.py | 3,792 | 4.21875 | 4 | '''
計算 C 的 m 取 n
m=7 n=3
'''
m=int(input("m = "))
n=int(input("n = "))
fm=1
fn=1
fm_n=1
for num in range(1,m+1):
fm*=num
for num in range(1,n+1):
fn*=num
for num in range(1,m-n+1):
fm_n*=num
print(fm//fn//fm_n)
# '''
# 運用函數,完成上面的例子
# '''
def fac(num):
# facterial 求階乘
result=1
for i in range(1... |
aa6238587df98b1aede514d9bede62b127b56a4d | Houssem12-ai/Taquin-dfs-bfs-A- | /Solver.py | 6,261 | 3.53125 | 4 | import random
import itertools
import collections
import time
from tkinter import *
class Node:
def __init__(self, puzzle, parent=None, action=None, cout=None, heuristique=None):
self.puzzle = puzzle
self.parent = parent
self.action = action
self.heuristique = heuristique
... |
97576164d90a21a3c9d70ef96143fcec62261687 | badooga/Programs | /functions.py | 19,927 | 3.90625 | 4 | from random import randint, choice
from subprocess import check_call
from fractions import Fraction
"""
This file was made by badooga years ago as programming practice.
"""
#For all input-related functions, prompt = what you want to ask
class Data(object):
"""
Used to turn a list/tuple/etc of numbe... |
ae52562c1f6513f484e599166b54df966b4bd574 | stanford713/Python0714 | /D13/inputnumber2.py | 733 | 3.546875 | 4 | def inputnumber():
try:
x=float(input('請輸入分子:'))
y=float(input('請輸入分母:'))
z=x/y
except ValueError as e:
print('錯誤類型:',e.__class__.__name__)#內置方法
print('你輸入的不是數字,請重新輸入')
inputnumber()
except ZeroDivisionError as e:
print('錯誤類型:',e.__class__.__name__)
... |
cda47bf25fbe3d6402b360ff79835195c0094647 | stanford713/Python0714 | /D16/selectrecord.py | 604 | 3.5625 | 4 | import sqlite3
conn=sqlite3.connect('demo.db')
cursor=conn.cursor()
#表格蘭為名稱(Table Meta-info)
cursor.execute('PRAGMA TABLE_INFO({})'.format('lotto'))
metainfo=cursor.fetchall()
print('metainfo:',metainfo)
names=[t[1]for t in metainfo]#id,n1,n2...
print('names:',names)
for name in names:
print(name,end='\t')
prin... |
e52532ea25e0e6cf99de5d8ab9d6d1a0f0578288 | stanford713/Python0714 | /D07/DefDemo4.py | 428 | 3.609375 | 4 | #自動會將所以分數全部+10
def add10(scores):
for i in range(0,len(scores)):
scores[i]+=10
def add10_singleValue(s):
global score
score=s+10
def add10_singleValue2(s):
return s+10
if __name__=='__main__':
scores = [50,60,70]
add10(scores)
print(scores)
score=90
add10_singleValue(scor... |
97e5c5cd0fba733063572290712f41d2d6e3cba3 | stanford713/Python0714 | /D04/stringDemo3.py | 151 | 4.0625 | 4 | word='she sell sea shell on the seashore'
word=word.capitalize()
print(word)
print(word.istitle())#每一個字首是否大寫
print(word.find('she'))
|
76d3b44639cdaa2f75960a31b9f2a575910617c1 | stanford713/Python0714 | /D12/012.py | 568 | 3.640625 | 4 | class JPY:
def __get__(self, instance, owner):
return instance.TW/0.28
def __set__(self, instance, value):
instance.TW=value*0.28
class USD:
def __get__(self, instance, owner):
return instance.TW/30.5
def __set__(self, instance, value):
instance.TW=value*30.5
class Exchan... |
178b5b6a6e116efe5989662b3bf02ba049198c66 | stanford713/Python0714 | /D04/whilepractice.py | 100 | 3.78125 | 4 | import random
x=0
while x%3==0:
x=random.randint(1,9)
print(x)
if x%2==0:
break
|
26e5e00555b12fc396a0c102e2c6a8f016f8ae87 | stanford713/Python0714 | /D18/treeviewstudent.py | 547 | 3.703125 | 4 | import tkinter
from tkinter import ttk
import sqlite3
win=tkinter.Tk()
win.title('資料庫')
tree=ttk.Treeview(win,columns=['1','2'],show='headings')
tree.heading('1',text='id')
tree.heading('2',text='name')
tree.column('1',width=100,anchor='center')
tree.column('2',width=100,anchor='center')
#資料匯入
conn=sqlite3.connect... |
1b809ac960f11db4d9b2d75aff1704740c2c7a3a | hiphp7/hs_code | /xml/yield_test.py | 552 | 3.78125 | 4 | def createGenerator():
for i in range(3):
print(1111)
# 使用yield关键字 可以将数据返回 并且保存当前的状态 下次调用的时候还是会从当前的状态往下运行
yield i*i
# 当调用createGenerator这个方法的时候,方法内部的代码并不会立马执行 只是会返回一个生成器对象
mygenerator = createGenerator()
# 当使用for进行迭代的时候 函数中的代码才会真正的执行
for i in mygenerator:
print(i)
"""
输出结果:
1111
... |
7ffb1231b4a6d9f81e3ec3c07fff63b9e037bae1 | breathfisheva/pygamelearning | /day6.py | 1,683 | 3.734375 | 4 | '''
pygame.draw.rect(Surface, color, Rect, width=0)
pygame.draw.polygon(Surface, color, pointlist, width=0)
pygame.draw.circle(Surface, color, pos, radius, width=0)
pygame.draw.ellipse(Surface, color, Rect, width=0)
pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1)
pygame.draw.line(Surface, color,... |
6b48a8c42325cb71a20bf52074057bea4d1fa99b | ZXQYC/random-shooter-game | /src/game.py | 1,012 | 3.6875 | 4 | """The main game program"""
import sys
import pygame
from screens.main_screen import MainScreen
from utils import WINDOW_SIZE
from leaderboard import Leaderboard
class Game:
"""Controls the main game loop"""
FPS = 30
SIZE = WINDOW_SIZE
def __init__(self):
"""Creates the Game object"""
... |
b0b83d427803e5bab07e9f96dec0204b8d76e744 | JiangHaoyang/AdvExample | /pytorch_toturial/builtInData.py | 1,081 | 3.5 | 4 | import torch
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms
to_pil_image = transforms.ToPILImage() #transform function: from tensor data to PIL data
#define how an PIL image transforms into the network input
inputTransformer=transforms.Compose([transf... |
18043ad3174fe9e19221a66cabe5a5529a7be65b | asaferrosenthal/Backpropogation | /Model.py | 10,228 | 3.96875 | 4 | """
Aaron Safer-Rosenthal | 17asr | 20068164
Backpropogation network which uses gradient descent and sigmoid activation
"""
import random
import numpy as np
class Network():
#Initializes the network object
def __init__(self, sizes):
self.numLayers = len(sizes)
self.sizes = si... |
2e99e7a24fa53ad663d8d62ee3b2b59d06cf9f11 | Izzle/learning-and-practice | /Misc/decorators_ex.py | 2,915 | 4.53125 | 5 | """
*************************************************
This function shows why we use decorators.
Decorators simple wrap a fucntion, modifying its behavior.
*************************************************
"""
def my_decorator(some_function):
def wrapper():
num = 10
if num == 10:
p... |
3860b7a119aea5d8e3007e420c2e5187159d696e | Izzle/learning-and-practice | /python_programming_net/tkinter_fun.py | 3,151 | 3.8125 | 4 | # Exercise 38, 39, 40, 41, 42
# Tkinter basics: windows, buttons, event handling, menus,
# and images and text
#
# I know that my 'obvious' inline comments violate strict PEP8,
# but I'm learning and its easier for me to follow myself in this case.
# I'm sure Guido would approve.
#
from tkinter import *
from PIL impor... |
9fd1d80b44dcea4693cb39f43ddc45a25e654a26 | Izzle/learning-and-practice | /theHardWay/ex6.py | 1,727 | 4.5625 | 5 | # Example 6
# Declares variable for the '2 types of people' joke
types_of_people = 10
# Saves a Format string which inputs the variable to make a joke about binary
x = f"There are {types_of_people} types of people."
# Declaring variables to show how to insert variables into strings.
binary = "binary"
do_not = "don't"... |
6de6480495a77156e84c0fd60f62494613c8e3e6 | Izzle/learning-and-practice | /python_programming_net/urllib_test.py | 1,551 | 3.875 | 4 | # Exercise 35
# urllib
import urllib.request
import urllib.parse
# =======================================
# Example GET
# =======================================
# .urlopen() must start with HTTP or HTTPS
x = urllib.request.urlopen('https://www.google.com')
print(x.read())
# ===========================... |
5fd329e733441ca67be649f8f604538c6697f6a3 | Izzle/learning-and-practice | /python_programming_net/sendEx05.py | 668 | 4.21875 | 4 | # Exercise 5 and 6
# While and For loops in python 3
# Basic while loop
condition = 1
while condition < 10:
print(condition)
condition += 1
# Basic For loop
exampleList = [1, 5, 6, 5, 8, 8, 6, 7, 5, 309, 23, 1]
for eachNumber in exampleList: # Iterates each item in the list and puts it into the variable ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.