blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
475f967db45980d01d6e4543c84cadd53f30b061 | JeroenGoddijn/Coding-Exercises | /WEEK01/Thursday/square.py | 179 | 3.65625 | 4 | from turtle import *
# move into position
up()
forward(50)
left(90)
forward(50)
left(90)
down()
# draw the square
for i in range(4):
forward(100)
right(90)
mainloop() |
01418cc85b76c51e5cbad92b8900ddac79d781df | jnavb/codewrs | /lib/katRanking.py | 612 | 3.625 | 4 | import math
def binary(items, value):
startIndex = 0
stopIndex = len(items) - 1
middle = math.floor((stopIndex + startIndex)/2)
while(items[middle] != value and startIndex < stopIndex):
if value < items[middle]:
startIndex = middle + 1
else:
stopIndex = middle - 1
middle = math.floor((stopIndex + star... |
b1c1383202ce9729bdecd46fa21b7cdc49cd9bd3 | ArtemonCoder/Python-Projects | /ugadaka_tsvet.py | 433 | 3.765625 | 4 | colors = ["фиолетовый", "оранжевый", "синий"]
guess = input("Угадайте цвет: ")
if guess in colors:
print("Вы угадали!")
else:
print("Не угадали, давайте еще раз.")
guess2 = input("Угадайте цвет: ")
if guess2 in colors:
print("Вы угадали!")
else:
print("Не угадали, давайте еще раз.")
... |
2c44a8f6489d86345d409df9b4d60d5bf1ff81b3 | ArtemonCoder/Python-Projects | /Elif_home.py | 385 | 4.0625 | 4 | home = input("Введите город, где живёте: ")
if home == "Чуркистан":
print("Э, Чурка!")
elif home == "Владимир":
print("Дарова, Богомаз!")
elif home == "Саранск":
print("хехе, Мухосранск!")
elif home == "Москва":
print("Hello, Moscow!")
else:
print("Привет, Землянин!")
|
dbb50e6f43709b11c1eb7a88dbbded360574ec6d | ArtemonCoder/Python-Projects | /vvod_chisla.py | 431 | 3.921875 | 4 | n = input("Введите число:")
n= int(n)
if n % 2 == 0:
print("n - чётное.")
else:
print("n - нечётное.")
n= input("Введите число:")
n= int(n)
if n % 2 == 0:
print("n - чётное.")
else:
print("n - нечётное.")
n= input("Введите число:")
n= int(n)
if n % 2 == 0:
print("n - чётное.")
el... |
17c392448fa0515680d48d5d51d8e8c5686e1d2f | leemoispace/netease_news_spider | /TED/TED.py | 3,961 | 3.578125 | 4 | from bs4 import BeautifulSoup
import sqlite3
import time
import os
#www.ted.com/talks
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
#python3 里面已经是用request了:http://stackoverflow.com/questions/2792650/py... |
3e61ceb9cbac7c449f5027da456b72d39fde0c0b | jlshix/leetcode | /problems/125-valid-palindrome.py | 706 | 3.59375 | 4 | # https://leetcode-cn.com/problems/valid-palindrome/
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s == '':
return True
s = self.beautify(s)
i, j = 0, len(s) - 1
while i < j:
if s[i] =... |
5af51bc892d2a20fa1c7caa3ae860de745229069 | kingson311/DistributedAI | /notebooks/Python/DistrubutedAI/computing/SaveCNNmodel.py | 3,572 | 3.703125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data",one_hot = True)
import tensorflow as tf
import os
#Parameters
learning_rate = 0.1
training_epochs = 5
batch_size = 100
display_step = 1
#Network Parameters
n_input = 784
n_classes = 10
#tf Graph input
x = tf.p... |
94e27f415262a49f5aca8cc4d0762083916e57e2 | qmazhar77/FirstRepo | /InheritanceOfClass.py | 1,185 | 4 | 4 | class Cars(): # Parent calss
def __init__(self,modlename,yearn,price): # this is the constructer
self.modlename = modlename
self.yearn = yearn
self.price = price
def price_inc(self): # this is function created in the class
self.price = int(self.price*1.15)
class SuperCar(Cars)... |
fb7e04ae9c850d0d23b8e69a6d1c29533514f771 | ToddDiFronzo/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 575 | 4.125 | 4 | """ INTERSECTION OF MULTIPLE LISTS
1. Understand:
Goal: find intersection of multiple lists of integers
Test case
---------
Input: list of lists
[1,2,3,4,5]
[12,7,2,9,1]
[99,2,7,1]
Output: (1,2)
2. Plan:
NOTE: skipping this one.
"""
if __... |
0f12c136eb165f73e16dbc9d3c73d647ac6aa708 | hamzai7/pythonReview | /nameLetterCount.py | 302 | 4.25 | 4 | # This program asks for your name and returns the length
print("Hello! Please enter your name: ")
userName = input()
print("Hi " + userName + ", it is nice to meet you!")
def count_name():
count = str(len(userName))
return count
print("Your name has " + count_name() + " letters in it!")
|
4c9ae12c70a0170077b60a70a2339afbd85a9e52 | ctwillson/algo | /python/sorting/InsertSort/InsertSort.py | 563 | 4.21875 | 4 | '''
插入排序
动画来源:https://visualgo.net/en/sorting?slide=9
'''
import numpy as np
LENGTH = 10
a = np.random.randint(10,size=LENGTH)
print(a)
# print(list(range(10,0,-1)))
#后面的元素往前插入
def InsertSort_demo(arr):
'''
i 控制从第几个元素开始比较,j控制第几个元素往前比较
'''
for i in range(1,LENGTH):
for j in range(i,0,-1):
... |
3a55237ee2f95f66677b00a341d0b5f3585bb3d3 | rayramsay/hackbright-2016 | /01 calc1/arithmetic.py | 922 | 4.28125 | 4 | def add(num1, num2):
""" Return the sum """
answer = num1 + num2
return answer
def subtract(num1, num2):
""" Return the difference """
answer = num1 - num2
return answer
def multiply(num1, num2):
""" Return the result of multiplication """
answer = num1 * num2
return answer
def... |
bbed46e2dd6184df10bd0b0938b9d86dd4b7c835 | VipulLGaikwad/PPL_Lab | /Assingment_6/shapes.py | 3,011 | 3.890625 | 4 | class shapes:
def __init__(self,side):
self.side = 4
def set_sides(self, side):
self.sides=side
def perimeter(self):
pass
class shapes2(shapes):
def area(self):
pass
class shapes3(shapes):
def volume(self):
pass
def surface_area(self):
... |
f4799b52179b2ec9bf66808ce2c7d4838f39da90 | ah20776/CE903-Group-Project | /scripts/preprocess.py | 2,829 | 3.5625 | 4 | """Script to preprocess the data"""
from pandas import read_csv, DataFrame
from numpy import append
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from outlier_detection import remove_outlier
from oversample_data import oversample_data
def get_data_from_dataframe... |
e108be0506af12e4720e00419b433f58f9dc3b0d | FredrikRahn/Advent-of-code | /day-2/corruption_checksum.py | 933 | 3.59375 | 4 | import sys
import itertools
def corruption_checksum_part1(input):
with open(input + '.txt', 'r') as file:
matrix = [map(int,line.split()) for line in file]
print sum([max(row) - min(row) for row in matrix])
def corruption_checksum_part2(input):
checksum = 0
with open(input + '.txt', 'r') a... |
9cd21183cb9de8dda7a8125e3a782d4dc6032739 | goodgodth/Automation-scripts | /desktop_break_notifier/desktop_break_notifier.py | 1,532 | 3.625 | 4 | from plyer import notification
from time import sleep
import argparse
# the main function
def main(args: argparse.Namespace) -> None:
# creating a title
title = 'Time for a break!'
# fetching the message
message = args.message
# fetching the delay
delay = args.delay
# if delay is less t... |
688515b9841939afa83fae85554d65715a24cb42 | goodgodth/Automation-scripts | /image_downloader/main.py | 566 | 3.53125 | 4 | import requests
from PIL import Image
from io import BytesIO
import os
download_path = os.path.dirname(os.path.abspath(__file__))
count = 1
while True:
url = input("Enter Image URL: ")
try:
res = requests.get(url)
except Exception:
print("Invalid URL / Can't Access The URL")
continu... |
e50391caec16e74d1821dfe904eb2d552fe1849a | goodgodth/Automation-scripts | /credit_card_generator/cc_generate.py | 3,617 | 3.609375 | 4 | # flake8: noqa
import sys
import random
def digits_of(number):
return [int(i) for i in str(number)]
def checksum_luhn(card_number):
digits = digits_of(card_number)
odd_digits = digits[-1::-2] # From right
even_digits = digits[-2::-2] # From right
total = sum(odd_digits)
for digit in even_digits:
total += su... |
11c52de6150db50b8f5de372bb0547e060243abf | goodgodth/Automation-scripts | /bmi_calculator/Calculator.py | 2,190 | 3.78125 | 4 | import tkinter as tk
from tkinter import messagebox
def reset_entry():
age_tf.delete(0, 'end')
height_tf.delete(0, 'end')
weight_tf.delete(0, 'end')
def calculate_bmi():
kg = int(weight_tf.get())
m = int(height_tf.get()) / 100
bmi = kg / (m * m)
bmi = round(bmi, 1)
bmi_index(bmi)
d... |
9f43f42182f77499ac92510020964ce53715f224 | paulnicholsen27/Euler | /eulertools.py | 1,362 | 3.703125 | 4 |
import itertools, string
def prime(n):
#determines if n is prime
if n == 1:
return False
factor_list = [1,n]
for divisor in range(2,int(n**.5)+1):
if n % divisor == 0:
return False
return True
def pandigital_generator(n, start=1):
#returns all pandigitals using all integers from start to n
... |
b26714273c293d0c63efca0c17b024ebb9c15f4b | paulnicholsen27/Euler | /40 - Champernowne's Constant.py | 549 | 3.8125 | 4 | '''An irrational decimal fraction is created by concatenating
the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the
value of the following expression.
d1 d10 d100 d1000 d1000... |
c877706ba843168fd0b0905b6f884870eff50e45 | paulnicholsen27/Euler | /23 - Abundant.py | 834 | 3.734375 | 4 | import math
def abundant(n):
abundant_numbers = []
for number in range(n):
factor = 1
sum = 0
while factor < (int(math.sqrt(number)) + 1):
if number % factor == 0:
if number != factor:
sum += factor
if number / factor != factor and number/factor != number:
sum += (number/factor)
facto... |
f11ae61306f20808bf4cdfea54c5418188d2db4f | Phazoning/weeko-EOI | /source/folderbackup.py | 3,443 | 3.5 | 4 | from os import listdir, path, makedirs
from datetime import date
from .filebackup import FileBackup
import logging as log
class FolderBackup:
def __init__(self, folder: str, exceptions: list, verbose: bool, logfile: str):
"""
Constructor method for the class
:param folder: path to the ... |
d855e311917d7f9117145317f3ce8c72d416de82 | leohohoho/11-puzzle | /puzzle-solver.py | 6,735 | 3.828125 | 4 | #Leo Ho - lmh575
import math
""" Function to find the coordinate of a given number """
def find(lst,x):
for i in range(len(lst)):
for j in range(len(lst[0])):
if lst[i][j] == x:
return i,j
""" Function to join the puzzle number list into a string """
def joinstr(lst):
sep =... |
43ff1d9bd4e3b0236126c9f138da52c3edd87064 | Jordonguy/PythonTests | /Warhammer40k8th/Concept/DiceRollingAppv2.py | 1,716 | 4.59375 | 5 | # An small application that allows the user to select a number of 6 sided dice and roll them
import random
quit = False
dice_rolled = 0
results = []
while(quit == False):
# Taking User Input
dice_rolled = dice_rolled
dice_size = int(input("Enter the size of the dice you : "))
dice_num = int(input("Ente... |
42263bd6be69e6fcf2f6dfedf2f0cf13d39f2fd4 | TianyuDu/IEEE_CIS_Fraud_Detection | /notes/copy_df.py | 646 | 3.84375 | 4 | import pandas as pd
def f(df):
# Copy dataframe to local scope.
# In this case, the dataframe df in the global scope.
# will not be modified
df = df.copy()
df.drop(columns=["a"], inplace=True)
print(df)
def f2(df):
# In this case the dataframe in the global scope
# will be changed.
... |
aad85a086ac31e130b10e8cc48be817e76ad96aa | Eragon5779/CodeForReference | /Python/Sort/CocktailSort.py | 396 | 3.5 | 4 | def cocktailsort(A):
for k in range(len(A)-1, 0, -1):
swapped = False
for i in range(k, 0, -1):
if A[i]<A[i-1]:
A[i], A[i-1] = A[i-1], A[i]
swapped = True
for i in range(k):
if A[i] > A[i+1]:
A[i], A[i+1] = A[i+1], A[i]
... |
a71699afc4fde4900965c8448b9f4d9ce7f0c0a3 | Eragon5779/CodeForReference | /Python/Sort/CountingSort.py | 511 | 3.703125 | 4 | def countingsort(sortablelist):
maxval = max(sortablelist)
m = maxval + 1
count = [0] * m # init with zeros
for a in sortablelist:
count[a] += 1 # count occurences
i = 0
for a in range(m): # emit
for c in range(count[a]): # - emit 'count[a]' c... |
19bba05f0ec8b435be7639f014449df1ec504ddf | Eragon5779/CodeForReference | /CodeWars/8kyu/arrows.py | 142 | 3.71875 | 4 | def any_arrows(arrows):
for x in arrows:
if "damaged" not in x or x['damaged'] == False:
return True
return False
|
4b6876cdfd2d05bda139fe319a0b0652138c99df | Eragon5779/CodeForReference | /CodeWars/8kyu/slope.py | 160 | 3.703125 | 4 | def find_slope(points):
x = points[0] - points[2]
y = points[1] - points[3]
if x == 0:
return 'undefined'
else:
return str(y/x)
|
ab4928101474e3d6fd546a3539a65c8607570742 | cn-qlg/python-tricks | /dict_merge.py | 565 | 4 | 4 | """合并两个dict"""
# dict.update(),本地更新,键相同,则更新
d1 = {"a": 1, "b": 2}
d2 = {"b": 22, "c": 3}
print("Before")
print(d1, id(d1))
print(d2, id(d2))
d1.update(d2)
print("After")
print(d1, id(d1))
print(d2, id(d2))
# 直接新建一个新的dict
d1 = {"a": 1, "b": 2}
d2 = {"b": 22, "c": 3}
d3 = {**d1, **d2}
print(id(d1), id(d2), id(d3))
prin... |
da764f60e7165734fbff1df13836d5b1f370b1f8 | captainedpanoramix/heap-sort-lesson | /heapsort-initial.py | 5,129 | 3.84375 | 4 | import math # needed for floor function
# debug stuff
# ------------------ components of pR() debug print function
sp4=" " # really only 1
hy4="-"
sp8=" " # really only 5
hy8="----"
sp16=" " # really only 14
sp14=" "
hy16="-----------"
sp18=" "
sp32=" ... |
6eebecc79d5a7b9ccf0da07efc200508a472f616 | eminetuba/14.Hafta-Odevler | /page-number.py | 1,060 | 3.609375 | 4 | #
# Complete the pageCount function below.
#
class Page:
def __init__(self, left, right):
self.leftPage = left
self.rightPage = right
class Book:
def __init__(self, pageNumber):
self.pages = []
if pageNumber > 0:
firstPage = Page(0, 1)
self.pages.append(f... |
42aa71caddda536bd51b2b70e485d50dfe1da79d | tehreem09/SaylaniAssignment | /assignment03.py | 1,272 | 3.984375 | 4 | # question01
val1 = input("Enter first number > ")
operator = input("Enter operation to be applied (from + - * / e) > ")
val2 = input("Enter second number > ")
if operator == 'e': operator = '**'
result = eval(val1+operator+val2)
print("Resultant value > ", result)
# question02
list1 = [2.5, 'banana', 'x', True, 55, '... |
89304e06ebe4363216f89a0daa98616f81d5836b | jacobcheatley/Euler | /Problems 001 - 050/Problem 042.py | 569 | 3.734375 | 4 | alphabet_values = {char: index + 1 for index, char in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}
def trianglenumbers(iterations):
number = 1
step = 2
for i in range(iterations):
yield number
number += step
step += 1
def valueofword(string):
return sum(alphabet_values[char] for ... |
92f1617f70f1e118ad2bf4ec20c792afb71df0ad | jacobcheatley/Euler | /Problems 001 - 050/Problem 038.py | 250 | 3.59375 | 4 | largest = 0
for i in range(9000, 10000):
temp = str(i) + str(i * 2) # must have max multiplier of 2
if '0' not in temp:
if len(set(temp)) == 9:
if int(temp) > largest:
largest = int(temp)
print(largest)
|
346be7331181603511731dd511189c8bf42aee1b | jacobcheatley/Euler | /Problems 051 - 100/Problem 056.py | 218 | 3.578125 | 4 | from custom.math import digits
highest_sum = 0
for a in range(100):
for b in range(100):
length = sum(digits(a ** b))
if length > highest_sum:
highest_sum = length
print(highest_sum)
|
05632a4fcb53d8c91133f0425dc84c421939abb2 | jacobcheatley/Euler | /Problems 001 - 050/Problem 034.py | 193 | 3.703125 | 4 | from custom.math import digits
from math import factorial
def is_curious(n):
return sum([factorial(d) for d in digits(n)]) == n
print(sum([x for x in range(3, 100000) if is_curious(x)]))
|
7c52f2078bbd257898bf5bcb18da0f668eae9c6a | VladTano/code-study | /pepe.py | 567 | 3.734375 | 4 | """
Завдання №2
Дано цілі p та q. Вивести на екран всі дільники числа q, взаємно прості з
p."""
p = int(input("Минимум: "))
q = int(input("Максимум: "))
a = []
for i in range(1,q+1):
if q%i == 0:
a.append(i)
b = []
for i in range(1,p+1):
if p%i == 0:
b.append(i)
b=set(b)
d= []
for i in range(le... |
a4720d13bb654710000ccfb3a644af6914969c90 | VladTano/code-study | /LABA 5.py | 1,251 | 4.15625 | 4 |
#Програма. Дана послідовність, що містить від 2 до 20 слів,
#в кожному з яких від 2 до 10 латинських букв; між сусідніми словами -
#не менше одного пробілу, за останнім словом - крапка. Вивести на екран
#всі слова, відмінні від останнього слова, попередньо видаливши з таких
#слів першу букву.
x = input()
x = x.split... |
357f8920264f67fa6e6e17debdcc454856291139 | miohsu/AdvancePython | /Chapter_01/1-2.py | 1,436 | 4.09375 | 4 | """
1.
for i in lst: 这个语句背后其实用的是iter(lst)
而这个函数的背后则是 lst.__iter__()方法
通过内置函数(例如 len, iter, str)时不仅会调用特殊方法,通常还提供额外的优化,尤其是对于内置类
2.
__add__ 和 __mul__ 函数实现了 + 和 * 操作;
这两个方法的返回值是新创建的对象,原值不动;
中缀运算符的基本原则是不改变操作对象,而是产出一个新值
3.
默认情况下自定义的对象总被认为是True,除非该类自定义类 __bool__ 或 __len__ 方法;
如果... |
5512ce7117315dea671e79b11553303d6ca22287 | miohsu/AdvancePython | /Chapter_16/16.1.py | 1,367 | 3.734375 | 4 | """
协程
协程与生成器类似,都是定义体中包含 yield 关键字的函数。在协程中,yield 通常出现在表达式的右边,可以产出值也可以不产出值。
如果 yield 后面没有表达式则返回 None。
协程可以从调用方接收数据,不过调用方把数据提供给协程使用的是 .send() 方法。
1.
yield 是一种流程控制工具,使用它可以实现协作式多任务: 协程可以把控制器让步给中心调度程序,从而激活其他协程。
2.
仅当协程处于暂停状态时才能调用 .send 方法,如果协程还没激活,则必须使用 next() 激活协程,或者调用 .send(None)。
预激协... |
e95bbf06f83154e1167524ff6570588c9987bb14 | miohsu/AdvancePython | /mooc/Chapter_04/duck_model.py | 722 | 4 | 4 | class Cat(object):
def say(self):
print('cat')
class Dog(object):
def say(self):
print('dog')
class Duck(object):
def say(self):
print('duck')
animals = [Cat, Dog, Duck]
for animal in animals:
animal().say()
print('=' * 20)
class Company(object):
def __init__(self, ... |
a5f58ae0af216cde539de076f0545d6cc794b828 | mezcalfighter/NE-221-2-UNIVA | /python/variables.py | 516 | 3.796875 | 4 | name = "Emanuel Camarena"
year = 2021
print(name)
print(year)
#One line comments
'''
Multi-line
comment
(for
multiple
comments)
'''
"""
Multi-line
comment
(for
multiple
comments)
"""
#Each variable has its own value
first_name, last_name, role = "Emanuel","Camarena","Student"
print(first_name)
print(last_name)
... |
0c7a6214b2989e97eab514343c5b91d47f4549be | Luucx7/POO-P3 | /3146.py | 288 | 3.984375 | 4 | # -*- coding: utf-8 -*-
entrada = float(input()) # Recebe o valor de entrada e converte para ponto flutuante
circunferencia = 2 * 3.14 * entrada # Aplica a fórmula da circunferência, considerando pi = 3.14
print("%.2f" % circunferencia) # Imprime o resultado com duas casar decimais
|
67f8e22e2eed2c08dbff24c5f2e9c19029e9dc94 | JameaKidrick/Data-Structures | /binary_search_tree/binary_search_tree.py | 3,673 | 3.578125 | 4 | import sys
sys.path.append('../queue_and_stack')
from dll_queue import Queue
from dll_stack import Stack
# CONSISTENT PROBLEM
# I kept coding return BinarySearchTree(left.value).insert(value) instead of just left.value.insert(value)
class BinarySearchTree:
def __init__(self, value):
self.value = value
... |
02d2314aed384f53481bf216d5657d4c461d3e27 | gaomingyang/machine-learning-basic | /Project2-Python-Movie-Pages/media.py | 584 | 3.59375 | 4 | #!/usr/local/bin/python
#coding:utf-8
#电影网站 定义Movie类
import webbrowser
class Movie():
"""This class is used to create Movie object"""
def __init__(self,title,storyline,poster_image,release_date,trailer_url):
"""init movie class with title、storyline、poster_image、release_date、trailer_url"""
self.title = title
se... |
dbdc1e6abb718044f405d0da07cd938976b78f1f | Geverson-commits-to/Python-bimestre | /notas.py | 233 | 3.921875 | 4 | value = []
for i in range(0, 5,1):
print(i + 1)
entrada = float(input('digite a Sua nota, do Enem de acordo com o numero inciar: '))
value.append(entrada)
print((value[0] + value[1] + value[2] + value[3] + value[4]) / 5)
|
27c86f9d6542477466149e3f0b4d9c59589c5f5c | shusingh/My-Python | /next.py | 678 | 3.734375 | 4 | from sys import argv #that's how you import stuff here
#using command line arguments
script, filename = argv
print("We are now going to truncate this file...")
myfile = open(filename, "w")
myfile.truncate() #that's how we truncate file guys
print("let us check out that the file exist in which we want to write data")... |
172607053de3d302179eeadafe18f4331246fe9d | shusingh/My-Python | /dict.py | 1,952 | 4.34375 | 4 | # in this module we will learn about awesome dictionaries
# defining a dictionary
en_hin = {"good":"accha", "sit":"baithna", "walk":"chalna", "love":"pyar"}
# now let's check our eng-hindi dictionary
print(en_hin["good"])
print(en_hin["sit"])
print(en_hin["love"])
print(en_hin) # there is no ordering in dictionaries
... |
46b87a04484fa98d3d7073d848d09f5705003e31 | AaronGordon87/Decision-Maker | /DecisionMaker.py | 1,931 | 3.71875 | 4 | #!/usr/bin/python3
from collections import Counter
from random import randint
import webbrowser
print('How many of you are there?')
people = input()
destinations = ['the cinema', 'the pub', 'for dinner', 'bowling', 'a drive']
answers = []
results = []
winner = []
print('Please enter your postcode (without spaces).'... |
c2c45c537a70fb3f6f19606501a809f3f27d8795 | AdamBures/MICROBIT-PYTHON | /Other Microbit Projects/number_guesser.py | 1,340 | 4 | 4 | tries = 0
score = 0
number = randint(0, 10)
def on_button_pressed_a():
global score
score += 1
if score > 10:
score = 0
basic.show_number(score)
basic.show_number(score)
input.on_button_pressed(Button.A, on_button_pressed_a)
def on_gesture_logo_down():
global score, number
scor... |
9c877f54f5ce87383000affff9c463d2c58c8718 | karthikv792/PlanningAssistance | /planner/mmp/src/ME_select/Search.py | 1,447 | 3.609375 | 4 | #!/usr/bin/env python
'''
Topic :: Search methods
Project :: Explanations for Multi-Model Planning
Author :: Tathagata Chakraborti
Date :: 09/29/2016
'''
from Queue import PriorityQueue
import copy
'''
Method :: Astar Search
'''
def astarSearch(problem):
startState = problem.getStartState(... |
46921a59e1d8d5423a563d1e01f9014716aaf1b4 | austind/pyplus-ons | /day4/csv_excel/solutions/exercise2/exercise2.py | 490 | 3.5625 | 4 | from openpyxl import load_workbook
def main():
wb = load_workbook("exercise2.xlsx")
print(f"Workbook Sheets: {wb.sheetnames}")
for sheet in wb.sheetnames:
print(f"{sheet} sheet has {wb[sheet].max_row} rows and {wb[sheet].max_column} columns")
devices = wb["Devices"]
device_list = []
f... |
8a531edaf49eb3b33578c0aa772fc9e3d6bdce73 | NamanSood07/c146-project_-fibonacci-series | /Fibonacci c146- project.py | 844 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 11 17:10:53 2021
@author: HIMALINAMAN
"""
from tkinter import*
root=Tk()
root .title("Fibonacci")
root.geometry("300x300")
label_num=Label(root, text="Enter a number", )
num = Entry(root)
label_series =Label(root, text="Fibonacci Series :" )
result=Labe... |
229a1abee09db4eeaa76dd66320a4dd7a67e0b7e | sethah/deeptennis | /deeptennis/features/court.py | 4,924 | 3.625 | 4 | import numpy as np
from typing import Optional, NamedTuple, Tuple, Iterable
class Point(NamedTuple):
x: float
y: float
class Line(object):
def __init__(self, slope: float, intercept: float):
self.slope = slope
self.intercept = intercept
def solve_point(self, x: float = None, y: flo... |
90ff8bcc34a2e380db6f0b71dd113e83dd764c46 | EricksonGC2058/all-projects | /todolist.py | 704 | 4.15625 | 4 | print("Welcome to the To Do List! (:")
todolist = []
while True:
print("Enter 'a' to add an item")
print("Enter 'r' to remove an item")
print("Enter 'p' to print the list")
print("Enter 'q' to quit")
choice = input("Make your choice: ")
if choice == "q":
break
elif choice == "a":
todoitems = inp... |
3d41cd141696e4b6cd4c7c11382a81fd006eef54 | Thevenkster/Sweepstakes | /Sweepstakes.py | 2,658 | 3.90625 | 4 | '''
This python script can be used to randomly assign teams to players using an
excel spreadsheet as input. Please ensure that the input files/sheets/columns
follow the naming conventions of the code to avoid errors/exceptions.
What this script does:
1. Opens an xlsx spreadsheet X
2. Reads the column with participants... |
06d0cd3e7bda67622711829d46b887b60d6ffe21 | dominiks/sitecheck | /sendmail.py | 1,431 | 3.890625 | 4 | '''
Configuration and methods for sending mails.
'''
import smtplib
from email.mime.text import MIMEText
SMTP_SERVER = "localhost"
replyto = "noreply@example.com"
server = None
def connectToServer():
""" Establish a connection to the specified smtp server. """
global server
if server is not None:
... |
0b919077f5b41dcc50bd2f9e49ea568045dedde3 | josharnoldjosh/personal-website | /sensor_helper.py | 764 | 3.828125 | 4 | import random
import requests
def send_temperature(temp_f):
"""
Sends a temperature as a numeric type
to the server, which from there propergates
the value to the mobile app.
temp_f : a numeric temperature in fahrenheit.
Example: send_temperature(92.7)
"""
requests.post(
... |
7bf6253f364b000a97152abc17d791595613e565 | ColeAnderson7278/BlackJack | /black_jack.py | 4,834 | 3.703125 | 4 | from random import shuffle
def getting_in():
while True:
player_money = 100
pot = 0
print('Wallet:${}'.format(player_money))
choice = input(
'This game has a $20 entry fee. Would you like to play? ')
if choice.strip().lower() == 'no':
print('Thank yo... |
37d1e58de3e3235657120f0bb0316eeb563e99a8 | LegendsIta/Python-Tips-Tricks | /number/is_odd.py | 142 | 4.25 | 4 | def is_odd(num):
return True if num % 2 != 0 else False
n = 1
print(is_odd(n))
n = 2
print(is_odd(n))
# - OUTPUT - #
#» True
#» False
|
2fb20cad7dfaba577fe164fdd9b8f63ec50df346 | JoshuaKeegan3/random-python | /school/ceaser.py | 743 | 3.53125 | 4 | encoded="PKEWHNG PKNNG PKEWHNG UWHK PKEWHNG RUNU PKEWHNG PKAM".lower()
alphabet = "a, e, h, i, k, m, n, ng, o, p, r, t, u, w, wh".split(", ")
for a in alphabet:
e=""
w=False
for i,c in enumerate(encoded):
if c == "n" or c=="w":
try:
if encoded[i+1] =="h" or encoded[i+1]=="g":
... |
ebf8e9930b149eb726fcd8d19f81550d0c1900a8 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_em_video(exercicios)/ex039.py | 2,660 | 3.984375 | 4 | '''print('#' * 100)
print(' ' * 10, 'Digite o ano em que você nasceu para saber se esta na hora de se alistar!')
print('#' * 100)
from datetime import date
atual = date.today().year
nasc = int(input('Ano de nascimento: '))
idade = atual - nasc
print('Quem nasceu em {} tem {} anos em {}'.format(nasc, idade, atual))
if i... |
65be845ad083859b32a9491b6d501364e540d224 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_em_video(exercicios)/ex031.py | 447 | 3.828125 | 4 | d = float(input('Digite a distância da sua viagem: '))
if d <=200:
print('O valor da sua passagem é R${:.2f}'.format(d * 0.50))
else:
print('O valor da sua passagem é R${:.2f}'.format(d * 0.45))
#condição simplificada a baixo:
'''distancia = float(input('Qual é a distância da sua viagem? '))
preço = distancia *... |
4b56ad45a41771cda0984030158cb32a6e9c1f72 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Minhas_coisas/teste classes.py | 518 | 4 | 4 | from tkinter import *
def bt1_click():
lb2 = Label(janela, text='Ah! Olá senhor ')
lb2.grid(row=2, column=1)
lb3 = Label(janela, text='')
lb3.grid(row=3, column=1)
lb3['text'] = ed1.get() + '!!'
janela = Tk()
lb1 = Label(janela, text="Qual o seu nome? ", bg='green')
lb1.grid(row=0, column=0)
ed1... |
0c1cb03e151ed82f535ad691fb1f28d2539406c3 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_em_video(exercicios)/aula09.py | 2,675 | 4.21875 | 4 | frase = 'Curso em Vídeo Python'
print('='*40, 'Bem vindo aos exemplos da Aula 09', '='*40)
print(' '*50, 'Manipulando texto :)', ' '*50)
print('')
print('='*51, 'Fatiamento', '='*52)
print('')
print('1>>', frase[9])#ele vai indentificar a caractere 9 ou seja a 10 pq para o python começa a contar da caractere 0
print(''... |
61725862d5c9489518a065942da115acaea4e9b7 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_POO/Aula-07-Dicionarios.py | 247 | 3.71875 | 4 | Pessoa = {'Nome': 'Hugo', 'Profissão': 'Programador', 'idade': 20}
Pessoa['Nome'] = 'Fábio'
print(Pessoa['Nome'])
class Pessoa:
pass
Hugo = Pessoa()
Hugo.nome = 'Hugo'
Hugo.emprego = 'Programador'
Hugo.idade = 27
print(Hugo.__dict__) |
5e61cd2f3f817de9cf2777ac95b030b8759c2a7e | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Minhas_coisas/Chat_boot_main.py | 5,438 | 3.65625 | 4 | '''def Chat_Boot_Goku():'''
# funções ============================================================================================================
def advinhação():
from time import sleep
from random import randint
computador = randint(0, 10)
cont = 0
n = int(input('\033[1;36mOk! vou pensar em um n... |
0bca4230d3304ed3002ca5b22d465eb5728f936b | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_em_video(exercicios)/ex036.py | 996 | 3.8125 | 4 | print('\033[1;35m-~~-\033[m' * 26)
print('\033[1;34mÓla, seja bem vindo ao nosso programa!\n ele tem como função te falar se você está apto para fazer o empréstimo,\n e enfim comprar a sua casa própria :)\033[m')
print('\033[1;35m-~~-\033[m' * 26)
casa = float(input('\033[1;36mQual é o valor da casa? R$\033[m'))
sálari... |
5cba1f6f3efaacf0c67ee0e3115e68706d827019 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_em_video(exercicios)/ex006.py | 202 | 3.78125 | 4 | print('====================DESAFIO 05====================')
n1 = int(input('Digite um valor inteiro'))
s = n1 + 1
s1 = n1 - 1
print('O seu número sucessor é {}, e o seu antecessor é {}'.format(s,s1)) |
1fe266f6b143fe6162761a05e3140930f251d012 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_Py/tratandoErros.py | 372 | 3.953125 | 4 | #Exemplo um
valor = input("Informe um número: ")
try:
soma = int(valor) + 10
resultado = soma / int(valor)
except ZeroDivisionError:
print("Ocorreu um erro de divisão por zero!")
except ValueError:
print("Opa ocorreu um erro de valor!")
finally:
print("Isso sempre é executado!")
print("\033[1;33;... |
a82bf9799f8c2376e7f4ac60adb7aa9e45b76eec | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Dicionarios/Dicionarios_03.py | 385 | 4.25 | 4 | ## Dicionários parte 3 - Ordenação por chaves; método keys() e função sorted.
# Exemplos:
#Ordenação de dicionarios
d = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
ordenada = list(d.keys())
ordenada.sort()
for key in ordenada:
print(key, '=', d[key])
print('-=' * 20)
#===============================================
#outra ... |
c7d4464b84e48c13ffedf2379bae6ba239717b48 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Curso_em_video(exercicios)/ex088.py | 1,758 | 3.984375 | 4 | '''Faça um programa que ajude um jagador da
MEGA SENA a criar palpites. O programa vai perguntar
quantos jogos serão gerados e vai sortear 6 números
entre 1 e 60 para cada jogo, cadastrando tudo em uma
lista composta.
from random import randint
from time import sleep
titulo = 'BEM VINDO AO GERADOR DA SORTE'
titulo2 ... |
4a95c1eb1ae1313b34f3cbcf46949f00652cf0d3 | antonioleitebr1968/Estudos-e-Projetos-Python | /Exercicios&cursos/Treina_web_collections/listas/operacoes_listas.py | 809 | 4.0625 | 4 | lista_simples_inteiro = [1, 2, 8, 4, 5, 14, 3, 3]
lista_simples_strings = ['Olá', 'mundo']
lista_mesclada = [1, 2.2, 'aaaa', True]
nested_list = [[1, 2], ['ola', 'mundo']]
print(lista_simples_inteiro)
print(nested_list)
#len()
print(len(lista_mesclada))
print(len(nested_list))
#append()
lista_simples_inteiro.append(... |
9dd4a8bea6d079f6bd3883fe53949bfbb1d58f1b | AndreasWJ/Plot-2d | /curve.py | 2,638 | 4.3125 | 4 | class Curve:
def __init__(self, curve_function, color, width):
self.curve_function = curve_function
self.color = color
self.width = width
def get_pointlist(self, x_interval, precision=1):
'''
The point precision works by multiplying the start and end of the interval. By ... |
6ed1e162a4ac3fcdc304d0196890f169275e7684 | RohanGTHB/ML_code | /__pycache__/elif.py | 739 | 4 | 4 | # ELSE_IF
log = False # this simply tests the presence of the variable.
if not log: # this 'not' just takes the opposite of (and/or/true/false)
print('yo')
else:
print('false retuned')
# is vs ==
l1 = [1, 2, 3, 4]
l2 = [1, 2, 3, 4]
if l1 == l2:
print('=')
elif l1 is l2:
print('is')
l1 = l2
if l1... |
f234eb95c53c24d0969fb9e2e81a131a3e945ee8 | RohanGTHB/ML_code | /__pycache__/os_1.py | 2,465 | 3.5625 | 4 | # OS MODULE
import os
# os.path.dirname(git.__file__)
# print(dir(os))
# print(os.getcwd()) # current working dir
# os.chdir('dir') - change cwd
# print(os.listdir('/users/rohan/deskop/'))
# os.makedirs('/users/rohan/desktop/python1/subdir')
# os.mkdir('/users/rohan/desktop/python1') #cant make a subdir in this
# ... |
a9d3b73e4bae3bbf0d1b2cd441f4ba3e94bbba6f | RohanGTHB/ML_code | /__pycache__/dictionary.py | 706 | 4.09375 | 4 |
# DICTIONARY
dict = {'rohan': 'smart', 'vishal': 'gent', 'chetan': 'chaman'}
print(dict['rohan'])
print(dict.get('rohan'))
# changing values
dict['rohan'] = 'angry'
print(dict)
print(dict.keys())
print(dict.items())
for key, value in dict.items(): # looping in dictionary
print(key, value)
# LOOPS
for a in... |
a93bd50b414ea060f750ebe006723dae977ddf64 | jean-ye/Solo-Project-Dduarte | /Dduarte_finalproject.py | 46,428 | 4.09375 | 4 | #Python Adventure Game
import random
import sys
import os
import time
screen_width=100
#Player Set-up
class player:
"""The class is the player
Define function to initialize the player
Includes:
self.name= inputted name string
self.race=inputted race from suggeste... |
5409717a892dae14dd8001d2b700a7c671eb1e69 | kmohan96214/vervethon | /readData.py | 801 | 3.5 | 4 | import pandas as pd
import numpy as np
def readcsv():
datacnt = pd.read_csv('countrydata.csv',sep=',')
availableData = set()
for i in range(len(datacnt)):
temp = str(datacnt.iloc[i]['Country Name'])
temp = temp.lower()
availableData.add(temp)
return availableData
def readCountr... |
8bb62085e2a1e7187aecbb3af46f4159eb1b534a | XPathfinderX/War | /turn.py | 796 | 3.84375 | 4 |
class Turn:
count = 0
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
def print_result(self):
self.__class__.count += 1
card1 = self.player1.draw_card()
card2 = self.player2.draw_card()
cards = [card1, card2]
prin... |
b528fcc23ae89ca05472a3596da7ac3c0d6d0f3c | listiani13/coursera | /Mining-Massive-Dataset/week5/basic_quiz2.py | 976 | 3.78125 | 4 |
from math import sqrt
yellow = (5, 10)
blue = (20, 5)
def get_dis(x, y):
return sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)
def check(upper_left, lower_right, y = True):
global yellow, blue
if y and get_dis(yellow, upper_left) > get_dis(blue, upper_left):
return False
elif y and get_dis(yellow, lower_right) > g... |
1fb00b42cc95e2ec22448059a58562acb952b3b2 | salizadeh10/WeatherPy | /WeatherPy.py | 5,322 | 3.671875 | 4 |
# Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
import datetime as dt
from pprint import pprint
# Import API key
from config import api_key
# Incorporated citipy to determine city based on latitude and longitude
from citipy import citipy... |
4c1922842c2bb7027d6c1f77f5d11bb4d1250a1a | keeyong/state_capital | /learn_dict.py | 906 | 4.4375 | 4 | # two different types of dictionary usage
#
# Let's use first name and last name as an example
# 1st approach is to use "first name" and "last name" as separate keys. this approach is preferred
# 2nd approach is to use first name value as key and last name as value
# ---- 1st apprach
name_1 = { 'firstname': 'keeyong'... |
3ef5ef65404c02705fc7df4e4eb080d5966138e8 | com4rang/day3 | /ex2.py | 385 | 3.71875 | 4 | from calculator import add
result=add(1,2)
print(result)
#from 외부 파일calculator에 저의된 함수 add를 불러서 사용할때
# calculator 파일의 모든 함수를 불러와 사용할 때는 from calculator import *
# from calculator import *
# num1=add(10,2)
# print(num1)
# num2=sub(10,2)
# print(num2)
# num3=mul(10,2)
# print(num3)
# num4=div(10,2)
# print(num4) |
bb2bff0df98117ad317312a18cf58b54eadb36cc | com4rang/day3 | /class2.py | 1,403 | 3.671875 | 4 | #클래스 상속하는 개념
class Cal():
def __init__(self, value):
self.value=value
def result(self):
print(self.value)
def add(self, input_value):
self.value += input_value
def sub(self, input_value):
self.value -= input_value
def mul(self, input_value):
self.v... |
ce77d2c32c5bccbac3971da25230bd80fe668d7e | stannam/530G | /preprocessing.py | 2,768 | 3.84375 | 4 | from importWords import decipher
from itertools import combinations
from editdistance import eval
import os
import sys
import pickle
"""
This is for pre-processing all the words and make a phonological neighbourhood network,
so that this costly (time-consuming) process doesn't need to done every time the user runs th... |
756effd1c0910cc32e1bc730a2c9fa810336fc10 | jwillmiller/CartiTweets | /createdb.py | 505 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 22:07:23 2019
@author: willm
create database using sqlite
"""
import sqlite3
db = "../twit_data.db"
conn = sqlite3.connect(db)
c = conn.cursor()
try:
#c.execute("drop table carti_links")
c.execute("drop table carti_links")
except:
# Nothing to drop, do... |
41a78f1c054f1623acb18dac7e0b669037830409 | AkashBabar12/Basic-Python | /p7.py | 92 | 3.65625 | 4 | languages=["a","b","c","d"]
for index, item in enumerate(languages):
print(index,item) |
f72046589b7f301b7e98a14668c6a75f5be6cea5 | Her02N0one/UniqueArt | /gui.py | 1,824 | 3.796875 | 4 | # Program to make a simple
# login screen
import tkinter as tk
import main
root = tk.Tk()
root.wm_title("Personal Abstract Art")
# setting the windows size
root.geometry("300x400")
# declaring string variable
# for storing name and password
name_var = tk.StringVar()
age_var = tk.StringVar()
fav_thing_var = tk.Strin... |
d25075e32786dfe711397de473e5be72dbd200cc | just-4-funn/tubes-medan | /mom/classes.py | 1,183 | 3.609375 | 4 | from global_func import power2, sqrt
# CLASSES
class Coordinate:
def __init__(self, x, y, z):
# default value andai x,y,z ga dimasukin
self.x = x
self.y = y
self.z = z
def __str__(self):
return f"<{self.x},{self.y},{self.z}>"
def distance_to_center... |
43cf60a74a107ad21e48823bf15f718980008298 | ckcclinton/B9DA100-CN | /bill_management_test.py | 1,038 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 19:25:38 2019
@author: clintonngan
"""
import unittest
from bill_management import read_bills, count_bills
class TestBillManagement(unittest.TestCase):
def test_read_bills(self):
bills = read_bills()
self.assertEqual(49, len(bills))
s... |
910c9eb957876aec545abf7692a33a5d0705fbf0 | Davigl/kattis-solutions | /rijeci/solution.py | 140 | 3.5 | 4 | cases = int(input())
a,b = 0, 1
while cases > 1:
temp = a
a = b
b += temp
cases -= 1
print("{} {}".format(a,b))
|
f0604e4602aead08393f7be9275896f95d6850f6 | ccb012100/projectEuler | /euler10.py | 562 | 3.6875 | 4 | def euler_10():
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
import math
def prime_test(n):
flag = True
m = int(math.sqrt(n))
if n == 2:
return True
if n % 2 == 0:
flag = False
return False
for x in range(3, m+1, 2):
if ... |
ede8301a68d39364a0c8962d6cac1e45fd5bdef6 | Marinda-Tapiwa/Python1 | /Stix.py | 4,979 | 4.21875 | 4 | import random
import time
now = time.strftime("%H")
name = input("Hello! What's your name?:")
def greeting():
if int(now)<12:
print("Good morning "+ name +"\nWelcome to a three number lotto!")
else:
print("Greetings " + name + "\nWelcome to a three number lotto!")
def random_pick():
number... |
6d8d65b568c96dd04f4ab8dcfcf26b3f19680d8b | PrithiPal/coding_challenges | /hackerank/chess.py | 945 | 3.671875 | 4 |
import time
def foo(grid,x,n) :
if x==n: ## end of search from here.
return True
## y iteration
for i in range(n) :
if i==0 :
if grid[x-1][i] or grid[x-1][i+1] :
continue
elif i==n-1 :
if grid[x-1][i-1] or grid[x-... |
e77a2e5c410431407b8bbd8d545f16bf6cc137b4 | PrithiPal/coding_challenges | /hackerank/maxSumSubarrayNonAdjacent_naive.py | 808 | 3.671875 | 4 |
def maxSum(arr,subset,ind) :
current_sum = sum(subset)
if ind >= len(arr)-1 :
return current_sum
for i in range(ind+2,len(arr)) :
subset.append(arr[i])
partial_sum = maxSum(arr,subset,i)
... |
5447efde94a7037fc6c8a95d812eb6b668521977 | PrithiPal/coding_challenges | /hackerank/naive_substr_compare.py | 849 | 3.609375 | 4 |
## ABBA LEN = 2 ; ab, bb ,ba
## 0,1,2
def countDict(arr) :
d = {}
for ch in arr :
if ch in d :
d[ch]=d[ch]+1
else:
d[ch]=1
return d
def lenSubstr(n,arr) :
count = 0
for i in range(0,len(arr)-n+1) :
s1 = arr[i:i+n]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.