blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9c65a6f49e76540c6f32c00f5c3d4e424031ab78 | SaulsCoding/Python-Exercises | /ex1.py | 554 | 4.0625 | 4 | import random
num = random.randint(1, 20)
tries = 1
print('I am thinking of a number between 1 and 20. ')
print('Take a guess.')
guess = int(input(''))
while guess != num :
tries += 1
if guess > num :
print('Your guess is too high. ')
print('Take a guess.')
guess = int(input(''))
... |
c769371d904e8bb594ce68d9d535f5a63a6798f0 | dpeacockk/SnakeGame | /game.py | 4,354 | 3.59375 | 4 | #Created by: Daniel Peacock
#The classic Snake Game in Python.
#Rules: Move up, down, left, right with W, S, A, D, respectively.
# You cannot run into yourself or the walls, or you must restart.
# The objective is to eat apples until you are as long as the entire screen.
import pygame
import sys
import t... |
9f86f1a5df0f1deb2b0033e55442ccea8bf75bfc | gabriellaec/desoft-analise-exercicios | /backup/user_328/ch88_2020_06_16_14_16_50_963183.py | 850 | 3.71875 | 4 | class Retangulo:
def __init__(self, ponto1, ponto2):
self.ponto_inferior_esquerdo= ponto1
self.ponto_superior_direito= ponto2
def distancia(self):
x_ponto= (self.ponto_superior_direito.x - self.ponto_inferior_esquerdo.x)**2
y_ponto= (self.ponto_superior_direito.y - self.ponto_inf... |
62595c09a048b9774de7967b5d53cfbceb8503d5 | balajisaikumar2000/Python-Snippets | /dfds.py | 1,660 | 4.03125 | 4 |
marks = 0
question_1 = "what is the national bird of india? \na)peacock b)crow c)sparrow d)pigeon"
print(question_1)
ans_1 = input("correct option is:")
if ans_1 == "a":
print("correct")
marks += 1
else:
print("wrong")
print("--------------------------------------------------------------------------------------... |
117c4b06e75f1432034dd23ee9662a34a2aca07c | bharathkotari/python_training | /database/db2.py | 291 | 3.84375 | 4 | import sqlite3
conn=sqlite3.connect('employee.db')
cursor=conn.execute("SELECT id,name,address,salary from EMPLOYEE")
for row in cursor:
print("id=",row[0])
print("name=",row[1])
print("address=",row[2])
print("salary",row[3])
print("operaton done successfully")
conn.close() |
a5a6ccb2e03097fd4d8ba2d145948fe3f0cc09db | Elegant-Smile/PythonDailyQuestion | /Answer/空空如也/20190520_加密题.py | 594 | 3.96875 | 4 | '''
Enter data to be encryted: 2345
Encrypted number: 0987
'''
__author__ = 'Xixin He'
__email__ = 'xixin.he@gmail.com'
number = input('Enter data to be encryted: ')
basic_element = list(range(10))
dictionary = dict(zip(basic_element, basic_element[5:] + basic_element[:5]))
encrypted_number = [str(dictionary[int(dig... |
6bddd1916a6d084ff0556685162213c9980b7fe9 | mattbv/tls_occlusion | /tls_occlusion/utils/geometry.py | 4,178 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Matheus Boni Vicari (2017).
"""
from numba import autojit
import numpy as np
@autojit
def point_in_facet(P, facet):
"""
Function to test if a point lies inside a facet defined by 3 vertices.
The algorithm was based on a solution presented by the user blackpawn.
... |
747a2a8cd29b5a9ed55982a47fac71f5a89828e1 | reginbald/kth-master-thesis-project | /graph_partitioning/Partition.py | 1,732 | 3.75 | 4 | class Partition:
def __init__(self, identifier):
"""Partition Constructor."""
self.identifier = identifier
self.forward_partitions = list()
self.backward_partitions = list()
self.nodes = set()
self.forward_nodes = set()
self.backward_nodes = set()
def __s... |
b7a9429d52ad4e222e656e1db2478912b13f2a4a | miguelvitores/tfg-code | /bin/analysis.py | 1,763 | 3.5625 | 4 |
class Analysis:
def __init__(self):
self.tiempo_ejecucion = 0
self.espacio_utilizado = 0
self.comparaciones = 0
self.intercambios = 0
def sum_te(self, cant: int):
self.tiempo_ejecucion += cant
def sum_eu(self, cant: int):
self.espacio_utilizado += cant
... |
ce9edd982604f368f2eefdc08ae9daedb4ce04f0 | drbothen/SPSE | /Module_1/Lesson_4/for.py | 274 | 3.953125 | 4 | names = ['josh', 'john', 'neil', 'andy']
for name in names:
print name
hybrdidList = [1, 'josh', 2, 'neo', [1,23,3]]
for item in hybrdidList:
print item
print range(10)
print range(1, 10)
print range(1,10,2)
for item in range(1,10,2):
print item
|
0fed4e2def1c1c45914920859e96643c5540e7fe | intellivoid/CoffeeHousePy | /deps/scikit-image/doc/examples/filters/plot_denoise_wavelet.py | 4,331 | 3.6875 | 4 | """
=================
Wavelet denoising
=================
Wavelet denoising relies on the wavelet representation of the image.
Gaussian noise tends to be represented by small values in the wavelet domain
and can be removed by setting coefficients below a given threshold to zero
(hard thresholding) or shrinking... |
6721fa2e0915fee897b3b95bbbf9523888c06330 | sheldonldev/python_basic_practice | /intermediate.py | 3,236 | 3.8125 | 4 | """Lists
"""
"""Tuples
"""
"""Dictionaries
"""
"""Sets
"""
"""Strings
"""
"""Collections
"""
# from collections import Counter, namedtuple, defaultdict, deque
# a = "aaaaabbbbccc"
# my_counter = Counter(a)
# print(my_counter)
# print(list(my_counter.elements()))
# Point = namedtuple('Point', 'x, y')
# pt = Point... |
5f2489978993f5f1cc7ee51eddd434cc33e9ab6f | GorobetsYury/Python_beginning | /lesson_4_task_3.py | 432 | 4 | 4 | # Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
# Способ №1
array = [number for number in range(20, 241) if number % 20 == 0 or number % 21 == 0]
print(array)
# Способ №2
result = filter(lambda number: number % 20 == 0 or number % 21 == 0, range(20, 241))... |
1c4e7bf09af67655c22846ecfc1312db04c3bfe1 | dks1018/CoffeeShopCoding | /2021/Code/Python/Tutoring/Challenge/main.py | 967 | 4.125 | 4 | import time
# You can edit this code and run it right here in the browser!
# First we'll import some turtles and shapes:
from turtle import *
from shapes import *
# Create a turtle named Tommy:
tommy = Turtle()
tommy.shape("turtle")
tommy.speed(10)
# Draw three circles:
draw_circle(tommy, "green", 50, 0, 100)
draw... |
e24d3a9aed51e84296797729914592e3b82c3031 | iagotito/hacktoberfest | /python/quadrante.py | 321 | 3.890625 | 4 | x = float(input())
y = float(input())
if x == 0 and y == 0:
print("origem")
elif x == 0:
print("no eixo y")
elif y == 0:
print("no eixo x")
elif x > 0 and y > 0:
print("quadrante 1")
elif x and y < 0:
print("quadrante 3")
elif x > 0 and y < 0:
print("quadrante 4")
else:
print("quadrante 2")... |
0db7e295895b3e344a61dd34ebea1cbec732d0d7 | jamesta99/congenial-waddle | /investment.py | 298 | 3.96875 | 4 | def calculate_apr(principal, interest_rate, years):
'''Calculates the APR of an investment given the principal amount, the interest rate, and the time in years'''
apr = 0.0
if principal < 0 or interest_rate < 0 or years < 1:
return False
apr = principal*(1+interest_rate)**years
return apr
|
dd57b596005b49ebd9e652661ac37d5f9c3b2a92 | sudhapotla/untitled | /Python Function arguments.py | 2,116 | 4.53125 | 5 | #python Functions
def greet(name, msg):
"""This function greets to
the person with the provided message"""
print("hi", name + ', ' + msg)
greet("Kiran", "Good morning!")
greet("Kiran","Good morning")
#greet()
def greet(name, msg="True friends are rare!"):
"""
This function greets the friends nature
... |
a9303213d65c4630d7e2fa9a80843a8997429cf5 | dvp-git/Python-Crash-Course | /classes-9.2.py | 1,236 | 4.5 | 4 | ## Exercise 9.2 Three Restaurants
## Making a class called Restaurant
class Restaurant():
"""Summarizing what is needed for the restaurant class"""
def __init__(self, restaurant_name,cuisine_type):
""" Saving the attriubutes in the object instance"""
self.restaurant = restaurant_name
... |
384e985feb53960ad8b28dc3ca340df55fb14b93 | LNZ001/Analysis-of-algorithm-exercises | /leetcode_ex/re_ex145.py | 669 | 3.875 | 4 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
r, stack = [], root and [root] or []
while stac... |
cd12058a40ade881b94acef53f038e2c9649d77b | sudikshyakoju/sudikshya_lab | /final_project/management_system.py | 370 | 3.703125 | 4 | from tkinter import *
root=TK()
root.title("Pharmacy Management System")
class pharmacy_management_system:
def __init__(self,root):
self.root=root
title=Label(self.root,text="PHARMACY MANAGEMENT SYSTEM",bd=15,relief=RAISED,font=("times new roman",40
,"bold"),bg="light blue"... |
1befc81e3e43973f9576198eb96b167a076574c0 | zhuo-c/first | /考核3.py | 3,104 | 3.6875 | 4 | # coding = utf-8
class Product:
'''This is a class for the information of product. '''
def __init__(self, number, name, price):
self.number = number
self.name = name
self.price = price
def initDict(dict):
fi = open("product.txt", "r")
for line in fi.readline():
lis = lin... |
35b4eeeed37c01c831608786ab1785d52e0ea0e1 | sangziteng/smallPythonProj | /Assignment 2/reviews.py | 3,991 | 4.34375 | 4 | # -*- coding: utf-8 -*-
import pandas as pd # This is the standard
import re
def analyze(reviewFile, stopwordFile, numWords = 20):
'''reviewFile: the path to a .txt file containing customer reviews.
The format is assumed to be the same as the test data sets attached to this assignment.
st... |
8d1f3c2be05fb07d044affb6f4c3a556fbc7bf18 | JaderAzevedo/PythonCursos | /Manipulacao_arquivos/io_v4.py | 418 | 3.5625 | 4 | # Usando try e finally para garantir o fechamento do arquivo
try:
# Abertura e leitura por stream
arquivo = open('pessoas.csv')
for registro in arquivo:
# Atenção: Quebra na "," e extração dos dados com "*"
# Strip : retira espaços em braco e \n,\t ,etc... das borda das strings
pri... |
d065a8f379272b2f832e2ac6c4521e1c98091bcc | PGatak/basics | /python/wyszukiwanie_binarne.py | 569 | 3.6875 | 4 | import math
def binary_search(list, item):
low = 0
high = len(list) - 1
loop = 0
while low <= high:
loop += 1
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return loop
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
... |
fdf2642bddf0aadb559ae02f38c77ceac0714f15 | leodan87/EjerciciosPython | /trianguloImpares.py | 357 | 3.765625 | 4 | '''
1
3 1
5 3 1
7 5 3 1
9 7 5 3 1
'''
num=int(input('Ingrese un número: '))
cont1,cont2=1,1
while cont1<=num:
auxCont1=cont1 #Add
while cont2<=cont1:
numImpar=auxCont1*2-1 #Add
auxCont1-=1 #Add
print(numImpar, end=' ')
cont2+=1
print() #Hacemos un salto de línea
cont2=1 #... |
6f2193ae99d4a739ef549ff729ffb6c53b6cc4ac | aleciodalpra/aprendizado | /Exerc 2/e13_pesoIdeal.py | 839 | 3.921875 | 4 | # https://wiki.python.org.br/EstruturaSequencial
while True:
s = input('Informe seu sexo ("F" ou "M"): ')
if s.lower() in 'm f':
break
else:
print('Informe "F" ou "M"!')
try:
h = float(input('Informe sua altura: '))
if s == 'm':
pesoIdeal = (72.7*h) - 58
elif s == 'f':
pesoIdeal = (62.1*h) - 44.7
... |
c4fd4291d7c6ff4ebe40d28579192478fb776e80 | bisharma/Binay_Seng560 | /converter.py | 622 | 4.03125 | 4 |
import math # This will import math module
# Now we will create basic conversion functions.
def decimal_to_binary(decimal_num):
result = bin(decimal_num)
return result
def binary_to_decimal(binary_num):
result = int(binary_num)
return result
def decimal_to_octal(decimal_num):
... |
58217bea1f27c4965ed46e85b867b559a5c00089 | DerrickWango/Projects-final | /Alg/Userdb.py | 551 | 3.65625 | 4 | import sqlite3
def userdb():
with sqlite3.connect('maindb.db') as db:
cursor=db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS User(
username VARCHAR(20) NOT NULL,
firstname VARCHAR(20) NOT NULL,
surname VARCHAR(20) NOT NULL,
p... |
973f7c9a174360b31c9ad6c8bbca924e0c0a7204 | bappi2016/selenium_webdriver_python | /Actions/MouseHovering.py | 2,010 | 3.546875 | 4 | from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import time
class MouseHovering():
def test(self):
#for firefox at first we have to show the path where is the Geckodriver located
#we set a variable "driverlocation" which will ... |
6604fe2fa9dd89b85774eca7f467f8d465c309cb | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4126/codes/1747_1536.py | 202 | 3.890625 | 4 | from math import*
x = float(input("numero real:"))
k = int(input("numero inteiro:"))
soma = 0
m = 0
while(m < k):
soma = x - (x**2/2) + (x**3/3) - (x**4/4) + (x**5/5)
m = m + 1
print(round(soma,10))
|
9887ed4b32ea850bbc6bf196d63fa4f0e810db5a | amirtip/laitecpython | /Tam2/tam2.py | 180 | 4 | 4 | x=int(input("Enter The Num:"))
for i in range(1,x+1):
print(" "*(x-i),end='')
print(" * "*i," ")
for i in range(x,0):
print(" "*(x-i),end='')
print(" *"*i)
|
4fc667c1896bba6a70bc097d76ab091185bd840b | BTJEducation/LifeDecisions | /1_Life decisions.py | 195 | 3.5 | 4 | #Life decisions
import random
decisions=["Stay in bed","Go for a walk","Go clothes shopping","Hang out with friends","Do some programming!"]
print("What to do today: ",random.choice(decisions))
|
784d35e356a136ab13650a6ec296a8d18ee4997f | Nihit13/Step-calculator | /step calculator.py | 414 | 4.5 | 4 | print("step calculator")
pi = 3.14
distance = float(input("distance to be covered :"))
diameter = float(input("The diameter of the wheel:"))
step_angle = float(input("The step angle:"))
circumference = diameter * pi
total_revolutions = distance/circumference
steps_in_one_revolution = 360/step_angle
total_steps ... |
078a2eb52917b1af6c48bff7e9cddeeb62c9b417 | helloShen/programming-paradigms | /assignment-8/assn-8-align/align.py | 3,007 | 3.9375 | 4 | #!/usr/bin/env python
import random # for seed, random
import sys # for stdout
# Computes the score of the optimal alignment of two DNA strands.
def findOptimalAlignment(strand1, strand2):
# if one of the two strands is empty, then there is only
# one possible alignment, and of course it's optimal
if len(stra... |
ddec4342868c5638d7c53e8bce28524da02070ac | SafwatImran/DepthOfTree-Recursive | /tree-height.py | 1,422 | 3.53125 | 4 | import threading
import sys
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Node :
def __init__(self,data=None,parent=None,depth=None):
self.parent=parent
self.child=[]
self.data=data
... |
b9e7f7acd669f4a8c8c83597e191b3c701e47416 | lius6219/Test | /Test/NC512.py | 1,187 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding=UTF-8 -*-
"""
众所周知,牛妹非常喜欢吃蛋糕。
第一天牛妹吃掉蛋糕总数三分之一(向下取整)多一个,第二天又将剩下的蛋糕吃掉三分之一(向下取整)多一个,
以后每天吃掉前一天剩下的三分之一(向下取整)多一个,到第n天准备吃的时候只剩下一个蛋糕。
牛妹想知道第一天开始吃的时候蛋糕一共有多少呢?
"""
# @param n int整型 只剩下一只蛋糕的时候是在第n天发生的.
# @return int整型
#
import math
class Solution:
def eatCake(self, total... |
61306abb942c7fc664586badd87da395b792b3b8 | elielouis/2011-2012-projects | /SchoolApps/armapp.py | 2,850 | 3.59375 | 4 | from colorama import Fore, Back, Style, init
import random
import os
init()
def GetCalc(difficulty):
operation = random.randint(1, 3)
if operation == 1:
# Operation : +
maximum = 10 ** difficulty
firstnum = random.randint(1, maximum)
secondnum = random.randint(1, maximum)
strcalc = "{0... |
62122323cc4a8586a9a2e3ba09524c5669eaef10 | garou93/algorithms-python-collections | /combler-trous.py | 527 | 3.703125 | 4 | # haithem ben abdelaziz: haithem.ben.abdelaziz@gmail.com
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 01:40:22 2021
@author: haihem
"""
def fill_blanks(nums):
valid = 0
res = []
for i in nums:
if i is not None:
res.append(i)
... |
86193dc6debb85699c4568d5e1137290c7ee2af6 | AndreyDementiev1989/geekbrains_hw02 | /task8.py | 1,123 | 3.828125 | 4 | # coding=utf-8
'''Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры'''
'''Матем'''
a = int(input('Введите последовательность чисел:'))
trg = int(input('Введите число которое необходим... |
9cc71af4614154650034c31c7402dee539afe193 | geektime-selfstudy/FromZeroToLearnPython | /src/zoudiac.py | 973 | 3.9375 | 4 |
# 采用元祖来存储星座,小写的u表示unicode编码
zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座',
u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
# 存储每个星座开始和结束的日期
zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22), (7, 23),
(8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
pri... |
a07d800fa58d544b19a7f34588d0e69c8aeda9cb | irekpi/lekcje | /python-mid/rozbudowa_kodu/11.eval.py | 237 | 3.8125 | 4 | import math
argument_list = []
for i in range(100):
argument_list.append(i / 10)
formula = input("Please enter a formula, use 'x' as the argument: ")
for x in argument_list:
print("{0:3.1f} {1:6.2f}".format(x, eval(formula))) |
e0c78467cf89592eebe9e48b0d93efd15267e1fe | stergiosbamp/nlp-review-rating-prediction | /download.py | 1,881 | 3.65625 | 4 | import gzip
import pathlib
import shutil
import urllib.request
class Downloader:
"""Class for downloading files in a specific directory.
Attributes:
dest_dir: The destination directory where every file is stored.
"""
def __init__(self, dest_dir="data/"):
self.dest_dir = pathlib.Path... |
b01a36b0e9d7ea0670a510b01c19ea4631c3501c | BMariscal/study-notebook | /ds_and_algos/sorting/countingsort.py | 1,348 | 3.890625 | 4 |
# In computer science, counting sort is an algorithm for sorting a collection of objects
# according to keys that are small integers; that is, it is an integer sorting algorithm.
# It operates by counting the number of objects that have each distinct key value, and using
# arithmetic on those counts to determine the p... |
2d5855c46226e493deeed0530e48ea12dc20a4fc | DavyOLearyF/Lowest_Common_Ancestor_Python | /LCA Test.py | 1,248 | 3.65625 | 4 | import unittest
from Lowest_Common_Ancestor_Python import Node
from Lowest_Common_Ancestor_Python import findLCA
class LCATest(unittest.TestCase):
#testing a normal case
def test1(self):
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)... |
a5e7eff7fcf4de7160eb9d27950b2f95c1186234 | Tritium13/Bioinformatik | /reverse_complement.py | 738 | 4.09375 | 4 | # Creating reverse complement of a DNA sequence
input_sequence = str(input("Input sequence: "))
input_sequence = str.upper(input_sequence)
#input_sequence = "AAAACCCGGT"
reverse_complement = ""
n = len(input_sequence) - 1
while n >= 0:
if input_sequence [n] == "A":
reverse_complement += "T"
n = n... |
ee097eac2d4b3d4d6ef74c5cfc5b41c10edc0d6d | qilin-link/test | /test/tkinter/鼠标进入与离开事件.py | 467 | 3.5625 | 4 | #!/usr/bin/env python
#_*_ coding:utf-8 _*_
import tkinter
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title('Test')
#设置大小和位置
win.geometry('400x400+500+200')
#<Enter>鼠标光标进入控件时触发
#<Leave>鼠标光标离开控件时触发
label = tkinter.Label(win, text='slash is a good man.', bg='red')
label.pack()
def func(event):
print even... |
4921bee99a45e36659b2d432e7b1f6134443aac4 | Ansh-Kumar/Project-Euler-Python | /Other Projects/HomeWorkTracker.py | 1,798 | 4.1875 | 4 | import sqlite3
import time
import datetime
import random
conn = sqlite3.connect("HomeworkAssignment.db")
c = conn.cursor()
def createTable():
c.execute("CREATE TABLE IF NOT EXISTS mainTable (NameOfClass TEXT, AssignmentName TEXT, DateReceived TEXT, DateDue TEXT, InPowerSchool TEXT, AssignmentAmount INTEG... |
c745ad2ee475f7e14d97415bd2671b6d52555fd9 | JNPRZ2000/-LFP-Proyecto1_201807201 | /metodos/metodos.py | 347 | 3.578125 | 4 | from tkinter import filedialog
def openFile():
try:
file = filedialog.askopenfilename(title = "Seleccione su archivo", filetypes=(("PXLA FILES","*.pxla"),("TXT FILES","*.txt"),))
content = open(file, "r").read()
return content
except FileNotFoundError:
return None
except IO... |
8ff5f95fe9566b8eb1e8047d817f76004613ae77 | NBakalov19/SoftUni_Python_Fundamentals | /01.Python_Intro_Functions_And_Debugging/greatingByGender.py | 293 | 3.859375 | 4 | age = float(input())
gender = input()
result = None
if age < 16:
if gender == 'm':
result = 'Master'
elif gender == 'f':
result = 'Miss'
else:
if gender == 'm':
result = 'Mr.'
elif gender == 'f':
result = 'Ms.'
print(result)
|
18af551eadab0eba4cdb34dbfd239aee2cfb4e86 | keikosanjo/lesson | /python/problem28.py | 217 | 3.734375 | 4 | def calculate_diagonal_numbers(N):
answer = 1
for i in range(3, N+1, 2):
for j in range(4):
answer += ( i * i ) - ( i - 1 ) * j
return(answer)
print(calculate_diagonal_numbers(1001))
|
04ca1c70973876b4c1c1b7ee7fcb841701d6f759 | JideUt/LearnPythonTheHardWay | /exer20.py | 1,441 | 4.4375 | 4 | # Exercise 20
# Learn Python The Hard Way (LPTHW)
# Functions and Files
# Page 74 (page 91 pdf)
# straight up practice, using functions and files together
from sys import argv
script, input_file = argv
# created a function to apply read() method to a file and print it all
def print_all(f):
print( f... |
06a6e75b4b4f150a753b632df084da9fbb8c5a39 | viltsu123/basic_python_practice | /TicTacHoe.py | 2,721 | 3.921875 | 4 | #The tic tac toe game begins
print('\n'*10)
print("Welcome to Tic Tac Hoe!")
print()
#player symbol selection
player1 = input("please choose X or O for Player 1:")
player2 = ""
if player1 == "X":
player2 = "O"
else:
player2 = "X"
print("Thank you\nPlayer 2 is now {}".format(player2))
print("")
#player symb... |
b94ee3840fa572c8c2732d74dabd5c9f31e3cb97 | scottmaccarone2/CodeWars | /sum_two_ints.py | 317 | 3.6875 | 4 | """
Create a function that returns the sum of the two lowest positive numbers given
an array (list?) of at least 4 positive integers (no floats or non-integer values will
be passed).
"""
def sumFn(list):
smallest1 = min(list)
list.remove(smallest1)
smallest2 = min(list)
return smallest1 + smallest2
|
1ffe31bd50d616a9f6f8a8de208312a3609a736e | noob-ja/sem-vi | /WID3001 Functional and Logic Programming/tutorial 2.py | 466 | 3.6875 | 4 | import re
def valid_password():
instr = input('String:')
if re.search('[A-Z]', instr) is not None and re.search(
'[a-z]', instr) is not None and re.search(
'[0-9]', instr) is not None and len(instr) >= 8:
print('valid')
else:
print('invalid')
import random
greetings = ['hello','hi',"'s up",'hey he... |
028600efda2ce7db4960177adbd3f9d24b72eb77 | shingpeach/iii | /homework3.py | 3,903 | 4.03125 | 4 | #3-1
def power(x, n):
count = 1
total = 1
while True:
if count <= n:
total *= x
count += 1
else:
break
print(total)
def main():
power(5,3)
main()
#3-2
def my_fun(x, n):
sum = 0
for j in range(1, n+1):
count = 1
total = 1
... |
e6a6c25106548c1591d35d2de85bffa4a447c440 | jasperan/python | /ex42_inheritance.py | 1,282 | 4.0625 | 4 | class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init__(self, name):
self.name = name
self.hairs = None
def setHairs(self, hairs):
self.hairs = hairs
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
class... |
22aacd2c06cfcd6685924568cf5876133387da64 | MattMannEC/Wild-West-Pong | /paddle.py | 1,378 | 3.609375 | 4 | import pygame
import settings
from pygame.sprite import Sprite
class Paddle(Sprite):
def __init__(self, pong_game, position):
super().__init__()
self.screen = pong_game.screen
self.screen_rect = pong_game.screen.get_rect()
self.settings = pong_game.settings
self.rect = pyga... |
e375a19743c988bc85042a46f25f31adf912a27e | LoganDBarnes/OOP-ldbarnes | /shield/shieldtest.py | 1,299 | 3.6875 | 4 | import unittest
from shield import Shield
class ShieldTest(unittest.TestCase):
def testDefaultShield(self):
style : str = "round"
material : str = "steel"
weight : int = 10
color : str = "silver"
thrown : bool = False
shield : Shield = Shield(style, material, weigh... |
951346ae6d3018c26fe75e1d837325f02638c381 | RaguRamG/100DaysOfCode | /Array/two_number_sum.py | 1,040 | 4.3125 | 4 | #Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
#If any two numbers in the input array sum up to the target sum,
#the function should return them in an array, in sorted order.
#If no two numbers sum up to the target sum, the function should return an e... |
b921c41ad33f04b43a9871f54be06442cbfdf4d7 | RRisto/pytorchnlpbook | /chapters/chapter_8/8_5_NMT/src/vectorizer.py | 6,503 | 3.671875 | 4 | import numpy as np
from .vocabulary import SequenceVocabulary
class NMTVectorizer(object):
""" The Vectorizer which coordinates the Vocabularies and puts them to use"""
def __init__(self, source_vocab, target_vocab, max_source_length, max_target_length):
"""
Args:
source_vocab (Se... |
91dc37c3817c2c7405062c8ec923d5daabbdddbd | renbstux/geek-python | /Collection_Counter.py | 4,876 | 4.21875 | 4 | """
Módulo Collections - Counter
https://docs.python.org/3/library/collections.html?highlight=collections#collections.Counter
Collections -> High-perfomance Container Datetypes
Counter -> Recebe um interável como parâmetro e cria um objeto do tipo Collections Counter que é parecido
com um dicionário, contendo como c... |
c161b6de1ac3ee7d1bea7f4dce86294d0bd8002c | pfiziev/pythonlibs | /pfutils.py | 3,016 | 3.71875 | 4 | import datetime
import json
import os
import math
__author__ = 'pf'
def std(X):
xbar = sum(X) / float(len(X))
return math.sqrt(sum((x - xbar)**2 for x in X)/(len(X) - 1))
def mean(array):
return float(sum(array))/len(array)
def strongtype(method):
"""
Decorator for strong-typing methods.
U... |
211dfccf6a6644c94a6822ccf580811ece0b75fa | baxiyi/python-learning | /面向对象编程/examples/test.py | 4,112 | 4.15625 | 4 | # 类和实例
# class Student(object):
# pass
# st = Student()
# st.number = 1
# print(st.number) # 1
# class Student(object):
# def __init__(self, name, score):
# self.name = name
# self.score = score
# st = Student('mzw', 100)
# print(st.name, st.score) # mzw 100
# class Student(object):
# def __init__(sel... |
08a9f84aa78aeb9c75f86809c4e34bb65ba6c5b2 | karpagma/learning | /python/udemy-flask-api/pyintro/lists_tuples_sets.py | 383 | 3.71875 | 4 | lists = [7, 1, 2, 3, 8, 7]
tuples = (7, 1, 2, 3, 8, 7)
sets = {7, 1, 2, 3, 8, 7}
tuples = tuples + (100, )
sets.add(6)
#print('lists :', lists)
#print('tuples :', tuples)
#print('sets :', sets)
set1 = {1, 2, 3, 4, 5}
set2 = {1, 3, 5, 7, 9, 11}
#print(set1.intersection(set2))
#print(set1.union(set2))
#print(set1.dif... |
d64b7ff87fe032cde8c1d248856124a88fc83f6a | dibya-the-coder/My_python-tutorial_files | /file writting.py | 386 | 3.703125 | 4 | # w for write mode
# r for read mode
# a for append mode (add lines to the content)
# f = open("lol me.txt", "w")
# a = f.write("whats up i am fine ok bro\n ")
# print(a)
# f.close()
# r+ for read and write both
f = open("lol me.txt", "r+")
f.write("whats up i am fine ok bro\n ")
f.write("thank ... |
b49a7bd9635e2511d40dbc9480c4d321864bd6d3 | dddcko/untitled | /day05/demo2.py | 850 | 4.21875 | 4 | # 判断101-200之间有多少个素数,并输出所有素数。
# 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),
# 如果能被整除,则表明此数不是素数,反之是素数。
list = []
for i in range(101,200):#遍历101-200
bool = True #定义一个布尔类型的变量,方便判断
for j in range(2,i): #遍历2到这个数,用这个数循环%小于自己的所有正整数
if i%j==0:#判断能不能被整除,如果整除了,bool值变成false,则该数不是质数
bool = False
if(bool):#判断... |
284a6d3c90f928b1d7f1116aa7801295ae52f477 | marcomerc/Deep-Learning | /Convolutional_Neural_Networks/con.py | 2,772 | 3.828125 | 4 | # Marco Mercado
# Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D # package for the convolutional layers. there is a 3D dimention look at documentation
from keras.layers import MaxPooling2D #this is for pooling the features f... |
827e76a7a9585e2aa529d9f17d7070108b4c4df5 | brunsond/IntegerPrograms | /ContFrac.py | 733 | 4.09375 | 4 | import math
# Prints out a list of the first N coefficients for the continued
# fraction expansion of the square root of n for n irrational.
# Prints None if n is a perfect square.
n = float(input("Enter the number n so that the cont'd fraction is for sqrt(n). "))
N = int(input("Enter the number of desired terms for... |
bfab8a98e9471ce4bee6f02660c776ee03955b01 | herolibra/PyCodeComplete | /practice/ai/distance/hm_distance.py | 528 | 3.609375 | 4 | #!/usr/bin/env python
# coding=utf-8
# author: zengyuetian
# 汉明距离
def hmd4str(s1, s2):
"""字符串的汉明距离"""
if len(s1) != len(s2):
raise ValueError("不等长")
return sum(el1 != el2 for el1, el2 in zip(s1, s2))
def hmd4int(x, y):
"""整数的汉明距离"""
z = x ^ y
count = 0
while z != 0:
if z ... |
72147d6c9adc7ebd9407228ca61f5662b74a84df | wayonyourlifeto/OOP-and-some-cods | /OOP.py | 3,691 | 4.0625 | 4 | class Car:
#atribute of class
car_count = 1
#method
def start(self, name, make, model):
print('engine start up')
self.name = name
self.make = make
self.model = model
Car.car_count += 1
@staticmethod
def get_class_details():
print('this is class C... |
1e28ea892c999b4a1a4f230dea67728d65d8a496 | altoid/leetcode | /py/continuous_subarray_sum_523.py | 1,516 | 3.515625 | 4 | #!/usr/bin/env python
# url for problem here
import unittest
from pprint import pprint
import random
def solution(nums, k):
if not nums:
return False
if len(nums) < 2:
return False
if k == 1:
return True
prefix_sums = []
prefix_to_i = {}
i = 0
partial_sum = 0
... |
8f5c94c91b2a0e7fe409ecad2fcc7129750ac61e | bizarout/TP_python_master | /TD_1_exercice_4.py | 319 | 3.921875 | 4 | """ Exercice N: 4
Auteur : Hamid.BEZZOUT
"""
# variable d'entrée : nombre choisi par l'utilisateur
n = int(input(" entrer un nombre "))
""" calcul si ce nombre est paire ou non """
modulo = n % 2
if (modulo==0):
print(" le nombre est paire ")
else :
print(" le nombre est impaire")
|
5045c30b1913f87d7038b484cbbaf6777943456b | ImperishableMe/Line_of_Action | /LOA/board.py | 5,963 | 3.703125 | 4 | import pygame
from queue import Queue
from .constants import *
from .checker import Checker
class Board:
dir_arr = [(0, 1), (0, -1), (-1, 0), (1, 0), (1, 1), (-1, 1),(1, -1), (-1, -1)]
def __init__(self):
self.board = []
self.white_left = self.black_left = ROW - 2
self.create_board()
... |
2bad680727c8efefe1ea0f8432dd80d32c1747f6 | nikitiwari/Learning_Python | /hcf_lcm.py | 420 | 4.0625 | 4 | print "Enter two numbers to find hcf and lcm"
x = raw_input("Enter m :")
y = raw_input("Enter n :")
try :
m= (int)(x)
n=(int)(y)
if m == n:
print "HCF is ", m
elif m > n :
a=m
b=n
elif m<n :
a=n
b=m
while a%b != 0 :
r=a%b
a=b
b=r
... |
b1e9556f91838303be2fec4042f768b1e5b5cd2d | mahuanli/1808.py | /1808/06day/01-new方法.py | 250 | 3.5 | 4 | class Cat():
def __init__(self):
print('init')
self.name = name
self.money = 1000
def __str__(self):
print('str')
return 'str'
def __del__(self):
print('del')
def __new__(cls):
return super().__new__(cls)
cat = Cat
print(cat.name)
|
39512094df76ba081c3a0918125f1313b632d9d3 | akashgupta-ds/Python | /13. Inner Class.py | 943 | 4.5 | 4 | # ----------- Inner Class -------------
# The class which is defined inside another class is called Inner Class.
# Without existing of one type of objects ,If there is no chance of existing of another type of objects then we should go for Inner Class.
# Inner class object is always associated with outer class object... |
5ebec7f4ec5d447f62a793d2a959f53e0c247408 | mknotts623/BioinformaticsAlgorithms | /Chapter_1/FindClumps.py | 1,364 | 3.90625 | 4 | from FrequencyTable import FrequencyTable
def find_clumps(text, k, l, t):
'''
Finds all k-mers that are clumped in text at least t times in a sequence by examining a widow
of size l. Moves the l sized window along the text to find all k-mers in all possible l sized
clumps that appear at least k times. A... |
bb745507bb31e19fff7441445aa092d9a6423286 | jgalanl/nlp | /nltk/stopwords.py | 291 | 4.21875 | 4 | import nltk
from nltk.corpus import stopwords
stop_words = set(stopwords.words("english"))
sentence = "Backgammon is one of the oldest known board games."
words = nltk.word_tokenize(sentence)
without_stop_words = [word for word in words if not word in stop_words]
print(without_stop_words) |
ca5b1f7bdc0e9b44415020b5363085feab5b9647 | svmihar/30-days-of-python | /nltk-learning/01-python-data-analysis/numpy-learning.py | 3,196 | 3.6875 | 4 | import numpy as np
# creating arrays
# my_list = [1,2,3]
# x = np.array(my_list)
# y = np.array([4,5,6])
m = np.array(([7,8,9],[10,11,12]))
# print(m.shape)
n = np.arange(0,30,2)
print(n)
n = n.reshape(3,5)
print(n)
print(np.zeros((2,3)))
print(np.ones((3,2)))
# indexing
s = np.arange(13)**... |
a989a2e944ef932bb5aea5e0e1e5dd81e205e9fe | micktymoon/P7_GrandPy_Bot | /app/wikipedia/wiki_api.py | 2,143 | 3.5625 | 4 | # /usr/bin/env python
# -*- coding:utf-8 -*-
import requests
def get_page_id(latitude, longitude):
""" Returns the ID of a Wikipedia page.
Get the ID of the Wikipedia page of a place given by its latitude and
longitude.
:param latitude: The latitude of the place.
:type latitude: float
:para... |
722993c3859f3a31586ee8fb69369e98a2d852f5 | KeeanBenjamin/PingPong | /PongGame.py | 6,533 | 3.625 | 4 | import pygame, sys
from pygame.locals import *
import math, random
# Sets the colors that are used later for the triangles
RED = (255, 0, 0)
BLUE = (0,0,255)
DARKRED = (192,0,0)
GREEN = (0, 150, 0)
BLACK = (0, 0, 0)
YELLOW = (255, 215, 0)
WHITE = (255, 255, 255)
ORANGE = (255,165,0)
PURPLE = (128,0,128)
TE... |
167fbc0ea1753a7d8407b02c032fd5f9738e8af6 | eleus-apon/HackerRank_Python | /print_function.py | 150 | 4 | 4 | if __name__ == '__main__':
n = int(input())
print (*range(1, n+1) sep="")
#* is used to unpack a iterable(list, string,tuple etc) in python
|
4400c65c834ffd234ad237edaf17f9a3f19b0b67 | yhsol/TIL | /note/algorithm/concept/Graph/graph.py | 1,566 | 3.71875 | 4 | # summer - john
# summer - justin
# summer - mike
# justin - mike
# john - justin
# justin - may
# may - kim
# tom - jerry
key = input()
graph_info = {
"summer": ["john", "justin", "mike"],
"john": ["summer", "justin"],
"justin": ["summer", "john", "mike", "may"],
"mike": ["summer", "justin"],
"... |
5ee4dbad56e9b8f03f61bf15e23fb353e1338853 | Aasthaengg/IBMdataset | /Python_codes/p02833/s689412905.py | 134 | 3.640625 | 4 | n=int(input())
if n%2==1:
print(0)
exit()
cnt=0
n//=2
fact=1
while n>=5**fact:
cnt+=n//(5**fact)
fact+=1
print(cnt)
|
9f7c232fc3e85e19be592dd6551f79ec7a632e13 | eronekogin/leetcode | /2020/largest_divisible_subset.py | 1,221 | 3.796875 | 4 | """
https://leetcode.com/problems/largest-divisible-subset/
"""
from typing import List
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
"""
1. Sort the input nums first.
2. Suppose dp[i] is the largest divisible subset with nums[i] as its
large... |
f82fa1244e49f0e18823252b77414c78c408af78 | sivaprasadkonduru/Python-Programs | /Dreamwin5/pangram.py | 198 | 4 | 4 | s = "abcdefghijklmnopqrstuvwxyz"
s1 = "The quick brown fo jumps over the lazy dog"
for i in s:
if i not in s1:
print("Not a Panagram")
break
else:
print("It's a Panagram")
|
a510a8a4bde68f46735e4d3e07c5c487787e4beb | alexsanjoseph/riemann-divisor-sum | /riemann/counterexample_search.py | 676 | 3.734375 | 4 | '''Search for a witness that the Riemann Hypothesis is false.'''
import math
from riemann.divisor import divisor_sum
from riemann.divisor import witness_value
SEARCH_START = 5041
def search(max_range: int, search_start: int = SEARCH_START) -> int:
'''Search for a counterexample to the Riemann Hypothesis.'''
... |
f5aa180f9297816baff477d85a842083cb0fd638 | toaa0422/python_leetcode | /leetcode_daily/101_isSymmetric_isMirror.py | 1,256 | 4 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root) -> bool:
def dfs(root1,root2):
if root1==root2:return True
if not root1 or not... |
f257a63a0a5f364ef663e9969590868cf1e05f89 | subham-paul/Python-Programming | /complexNo_58.py | 506 | 4.0625 | 4 | """print("Addition of two complex numbers : ",(4+3j)+(3-7j))
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
print("Division of two complex numbers : ",(4+3j)/(3-7j))
"""
import cmath
print("Addition of two complex numbers : ",(10A)+(20A... |
4ce1471acd3799c1f3121f82a6d3a7a38fcbb483 | teju85/programming | /rosalind/MER.py | 711 | 3.625 | 4 | import sys
from common import readArrayFromLine
def mergeSorted(a, b):
i = 0
j = 0
la = len(a)
lb = len(b)
out = []
while i < la and j < lb:
if a[i] < b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
for t in range(i... |
4a98a008c4c1c4c8ee0f34e60624b50de4fcb320 | seeprybyrun/project_euler | /problem0026.py | 1,567 | 3.765625 | 4 | # A unit fraction contains 1 in the numerator. The decimal representation
# of the unit fractions with denominators 2 to 10 are given:
#
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6)
# 1/7 = 0.(142857)
# 1/8 = 0.125
# 1/9 = 0.(1)
# 1/10 = 0.1
# Where 0.1(6) means 0.166666..., and has a 1-di... |
c3c6935d2b65296c000c94a20062a3eaa610ed19 | Yaoaoaoao/LeetCode | /algorithms/274_h_index.py | 601 | 3.515625 | 4 | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
citations = sorted(citations, reverse=True)
h = 0
for c in range(len(citations)):
if citations[c] >= ... |
bc21d25e2004e118572d56c7c1464d49900baef3 | DashKoester/NeuralNetFinal | /perceptron.py | 3,597 | 3.6875 | 4 | #!usr/bin/env python
__author__ = 'Dashiell Koester'
''' Implementation of a Perceptron class trained to recognize one digit'''
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import numpy as np
class Perceptron:
def __init__(self, class_label, bias = .5):
self.class_label ... |
409d61a2ad41352b232d589549a1c1cd68ebda2e | BrianPaur/Work-Projects | /driver.py | 1,046 | 3.734375 | 4 | import requests
import datetime
from datetime import date
#imports date and then formats to string so that we can take out dashes.
today = date.today()
today_str = datetime.datetime.strftime(today,'%Y%m%d')
#url with f string so that we can insert todays date from above
url = f"https://marketdata.theocc.com/... |
981e18875ab6b36378e7fe90a593206cf7967a11 | autsav/pthon_basic | /while_loop.py | 374 | 3.96875 | 4 | i=1
while(i <= 6):
print(i)
i +=1
#using flag t stop looping
i = ""
name = "Write any name. \n"
while(i != 'q'):
i = input(name)
#infinite loop
#the loop that doesnot stop,
j=1
while(j <= 6):
user = input("What is your name?")
print("You inserted " + user)
if(user == "John"):
break
... |
854cbfeb649a04686382057a36f11795209e7cf9 | nomorehugs/Programming0-1 | /HW/Week1/Part 5/sum_digits.py | 187 | 3.65625 | 4 | n = input("Enter N: ")
n = int(n)
last_n = n % 10
part_n = n // 10
sum = 0
while part_n != 0:
sum = sum + last_n
last_n = part_n % 10
part_n = part_n // 10
sum += last_n
print(sum)
|
46a197d5d25a0f18c28ce84a1654dc4cf883bdb3 | ErenBtrk/PythonNumpyExercises | /Exercise30.py | 207 | 3.796875 | 4 | '''
30. Write a NumPy program to create a 4x4 matrix in which
0 and 1 are staggered, with zeros on the main diagonal.
'''
import numpy as np
x = np.zeros((4, 4))
x[::2, 1::2] = 1
x[1::2, ::2] = 1
print(x) |
3738ae55cff0a5a414119cb941933c9e244656dd | pedrocambui/exercicios_e_desafios | /python/cursoemvideo/ex084.py | 1,960 | 3.71875 | 4 | lista = list()
dados = list()
maior = menor = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso: ')))
if len(lista) == 0:
maior = menor = dados[1]
else:
if dados[1] > maior:
maior = dados[1]
if dados[1] < menor:
menor = dados[... |
5b51c6648c9aea05bc0e250756c7d6d41a63a196 | nehatomar12/Data-structures-and-Algorithms | /LinkedList/12.merge_sorted_LL.py | 2,559 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __lt__(self, other):
# Override < operator
# Error while comparing Node objects
# TypeError: '<' not supported between instances of 'Node' and 'Node'
return self.data < other.data
class ... |
801b5b9b601561c0c38d3a610c3ccb64fc26f9cd | dohyun93/python_playground | /section11_(유형)_Greedy문제들/11-3.문자열 뒤집기.py | 993 | 3.703125 | 4 | # string은 0또는1로 이루어진 문자열.
# 1과 0의 군을 나누고, 더 적은 군을 갖는 집단의 군 수를 구하면 된다.
# 이 수가 곧 뒤집어주는 횟수고 그것이 답이다.
string = input()
if len(string) == 0:
print(0)
else:
curNum = string[0]
zeroGroup = 0
oneGroup = 0
# 먼저 현재 숫자 그룹 수 +1. 이렇게 했기때문에 다음에 새로등장한 그룹수부터 카운트.
if curNum == '0':
zeroGroup = 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.