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 |
|---|---|---|---|---|---|---|
9648970ff9274423ca3d14d5da847b3597b4b0ed | 98chaithanya/program | /Untitled3.py | 3,701 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
def average(lst):
return sum(lst)/len(lst)
lst=[15,9,14,10,30,27]
average=average(lst)
print("average of list=",round(average,1))
# In[11]:
x=5
y=10
print("before swapping")
print("value of x:",x ,"value of y:",y)
x,y=y,x
print("after swappnig")
print("value of ... |
22d6f9943861b21b3fe3168e22c0f309464995b1 | gentoomaniac/Minecraft | /py-minecraft/engine/player.py | 1,754 | 3.828125 | 4 | import json
class Player(object):
""" This class defines a player including the state, position etc. """
def __init__(self):
# player position in the gameworld
self.position = (0, 0, 0)
# player name
self.name = "Player"
# player life
self.life = 100
... |
50e6dc86d6a2dcec1df9cac643815c3e9c3a7f06 | ArnoBali/python-onsite | /week_01/03_basics_variables/08_trip_cost.py | 402 | 4.46875 | 4 | '''
Receive the following arguments from the user:
- miles to drive
- MPG of the car
- Price per gallon of fuel
Display the cost of the trip in the console.
'''
miles = int(input("please input miles to drive:" ))
mpg = int(input("please input MPG of the car:" ))
p_gallon = int(input("please input Price ... |
3805dac79b3e1ca32aa8ff65819968ae759b8a36 | ArnoBali/python-onsite | /week_03/01_files/00_long_words.py | 352 | 3.8125 | 4 | '''
Write a program that reads in the file words.txt and prints only the
words with more than 20 characters (not counting whitespace).
Source: http://greenteapress.com/thinkpython2/html/thinkpython2010.html
'''
with open('words.txt','r') as fin:
words = fin.readlines()
print(words)
for word in words:
if len... |
1bdcfa5db635cbba8f5f54f3d651187ee1865810 | ArnoBali/python-onsite | /week_02/07_conditionals_loops/Exercise_05.py | 532 | 4.375 | 4 | '''
Take two numbers from the user, an upper and lower bound. Using a loop, calculate the sum
of numbers from the lower bound to the upper bound. Also, calculate the average of numbers.
Print the results to the console.
For example, if a user enters 1 and 100, the output should be:
The sum is: 5050
The average ... |
a3108aa1bb32563d4f06c16fc3dcb65135a579c4 | ArnoBali/python-onsite | /week_03/01_files/04_rename_doc.py | 986 | 4.09375 | 4 | '''
Write a function called sed that takes as arguments a pattern string,
a replacement string, and two filenames; it should read the first file
and write the contents into the second file (creating it if necessary).
If the pattern string appears anywhere in the file, it should be
replaced with the replacement string.
... |
d2dd93a12035f03644a19898b5e8356a16320a02 | ArnoBali/python-onsite | /week_02/07_conditionals_loops/Exercise_01.py | 382 | 4.5625 | 5 | '''
Write a program that gets a number between 1 and 1,000,000,000
from the user and determines whether it is odd or even using an if statement.
Print the result.
NOTE: We will be using the input() function. This is demonstrated below.
'''
input_ = int(input("Please input a number between 1 - 1,000,000,000: "))
if ... |
7433581892828c7364bb64e252ef03869d3e5887 | TheTathe/Tickets | /model.py | 3,681 | 3.6875 | 4 |
class Machine():
"""
Maszyna - automat. Obecnie masz tam 500 * 20g (10000gr = 100zł).
"""
def __init__(self):
print("ELO TO JA TWOJA MASZYNA")
self.moneyInMachine = {
'20gr': 500,
'50gr': 0,
'1zl': 0,
'2zl': 0,
'5zl': 0,
... |
690d9f99a2ec2fbd896cce76ffb23e7385071634 | matt23177/Simple-Python-Game | /game.py | 709 | 3.828125 | 4 | import random
def start():
print('Hello! The objective of the game is to collect money')
a = input("Do you want to play?")
if a.lower() in ('y', 'yes'): #If user inputs one of the following, game starts with 0 money.
Game(0)
def Game(money):
number = random.randint(1,51) #generate a random number
pic... |
82e6174ca9db4ae76f287b66ced3abc582c21dcd | Abreu-Ricardo/EstruturaPython | /ead1.py | 1,102 | 3.6875 | 4 | # Programador: Ricardo Abreu de Oliveira
# Professor: Eloi Araujo
#Criando a estrutura de um nó
class Noh(object):
def __init__(self):
self.info = None
self.pai = None
self.esq = None
self.dire = None
#Função para achar a distância da raiz
def posicao(r, l_erd):
j = 0
while l_erd[j] != r:
j = j+1
re... |
60ccf89fecb723e2d04e886a7573e4f756879097 | EdilsonJunior-2/PAA-2020-2 | /Respostas/Lista2/2_2_a.py | 367 | 3.78125 | 4 | n = int(input("Diga quantos elementos você quer inserir: "))
array = input()
lista = list(map(int,array.split(' ')))
if (len(lista) == 1):
print('Intervalo = 0')
elif (lista[0] > lista[-1]):
intervalo = str(lista[0] - lista[-1])
print('Intervalo = ' + intervalo)
else:
intervalo = str(lista[-1] - lista[... |
7b98d652c32a060c3aee3ef4a321f97f8b65927c | GeginV/Algorithms-and-data-structures- | /linear search.py | 361 | 3.75 | 4 | def find(array, element):
for i, a in enumerate(array):
if a == element:
return i
return False
array = list(map(int,input().split()))
element = int(input())
print(find(array, element))
def count(array, element):
count = 0
for a in array:
if a == element:
... |
930aa1338bd9bcab9c005cb62111e8d6b7820016 | udichibarsagadey/pychemistry | /ML/panda_ML.py | 409 | 4.15625 | 4 | """
how to write csv file in panda
1) Pandas head()
2) Pandas tail()
3) Pandas write csv ‘dtype’
4) Pandas write csv ‘true_values‘
5) Pandas write csv ‘false_values’
# pandas fillna
"""
import pandas as pd
ab = pd.read_csv('Fortune_10.csv')
print(ab)
print(ab.head())
print(ab.tail(7))
ab = pd.read_csv('student_resu... |
df0735725158fedbe4aad8ba5516821f08a11892 | Jpub/LearningPython | /code/sumtree2.py | 2,674 | 3.84375 | 4 | trace = lambda x: None # or print
visit = lambda x: print(x, end=', ')
# breadth-first by items: add to end
def sumtree(L): # Breadth-first, explicit queue
tot = 0
items = list(L) # Start with copy of top level
while items:
... |
671c47bd99d23bf39039939139e2dea3db2ab81c | Jpub/LearningPython | /code/timerdeco.py | 803 | 3.515625 | 4 | """
File timerdeco.py (3.X + 2.X)
Call timer decorator for both functions and methods.
"""
import time
def timer(label='', trace=True): # On decorator args: retain args
def onDecorator(func): # On @: retain decorated func
def onCall(*args, **kargs): # On calls: call o... |
fe543b79f42a5cfac5ce3f32d8a97c929e92cd3e | Jpub/LearningPython | /code/lunch.py | 1,206 | 3.8125 | 4 | class Lunch:
def __init__(self): # Make/embed Customer, Employee
self.cust = Customer()
self.empl = Employee()
def order(self, foodName): # Start Customer order simulation
self.cust.placeOrder(foodName, self.empl)
def result(self): ... |
2f297fe02ccbd6125f62cbc5c6023123e992c21f | Jpub/LearningPython | /code/mins.py | 440 | 3.84375 | 4 | def min1(*args):
res = args[0]
for arg in args[1:]:
if arg < res:
res = arg
return res
def min2(first, *rest):
for arg in rest:
if arg < first:
first = arg
return first
def min3(*args):
tmp = list(args) # Or, in Python 2.4+: return sorted(args... |
53e869d8c3d495bc5c1bce9c60a33f654ad86e87 | seilcho7/week_1-python | /degree-conversion.py | 106 | 3.828125 | 4 | celsius = input("Temperature in C? ")
fahrenheit = float(celsius) * 1.8 + 32
print(str(fahrenheit) + " F") |
93634ae8844b72229529f1c44a33cfe948413323 | seilcho7/week_1-python | /for.py | 292 | 3.875 | 4 | # for q in range(3, 6):
# print(q)
#(start#, stop before#, interval)
for q in range(1, 10, 2):
if q == 5:
print("spam")
else:
print(q)
print("\nPrint odd numbers")
#print odd numbers
count = 0
for x in range(10):
if x % 2 == 0:
continue
print(x) |
aa19f6fd39f1e8f1dcf3b648e9be186c97bd1cc9 | seilcho7/week_1-python | /madlib.py | 248 | 4.0625 | 4 | print("Please fill in the blanks below: ")
print("___(name)___'s favorite subject in school is ___(subject)___")
name = input("What is name? ")
subject = input("What is subjec? ")
print("%s's favorite subject in school is %s." % (name, subject)) |
2e35cc10c983f421dbb7c30b0e2684b5a0906efa | seilcho7/week_1-python | /dictionary.py | 1,724 | 3.578125 | 4 | # meal = {
# "drink": "Creatures Comforts Athena",
# "appetizer": "Charcuterie",
# "dinner": "Grindhouses burger",
# "dessert": "Cupcakes"
# }
# house = {
# 'kitchen': 'Fancy Refrigerator',
# 'bathrooms': 3,
# 'bedrooms': 4,
# 'living_room': 'giant'
# }
# user = {
# 'first_name': '... |
d946a30e785309b401e0e85efb429979c4fe1150 | chandrakant100/Assignments_Python | /Practical/assignment4/product.py | 548 | 3.96875 | 4 | import math
count = input("Enter total numbers want to multiply(max = 4):")
if count.isnumeric() == 0:
print("It is a string!!!")
exit()
count = int(count)
countNum = 1
def multiply(num1 = 1, num2 = 1, num3 = 1, num4 = 1):
return num1*num2*num3*num4
if count > 4:
print("Maximux intput is 4")
ex... |
18a97252b8585ab6b59260fac96e3f2db9a1192f | chandrakant100/Assignments_Python | /Practical/assignment3/sine_series.py | 762 | 3.765625 | 4 | #wap to print sine series
n = input('Enter the range:')
if n.isnumeric() == 0:
print('Please enter a numeric value!!!')
exit()
else:
n = int(n)
x = input('Please enter a value for x:')
if x.isnumeric() == 0:
print('Please enter a numeric value!!!')
exit()
else:
x = int(x)
x = (3.14/... |
053cb5267b320925f281d903706a2bef5c8a0b89 | chandrakant100/Assignments_Python | /Practical/assignment4/multiply.py | 494 | 3.84375 | 4 | '''
to find the product of max 4 numbers by one function
file name : Multiply.py
date : 07/10/2020
'''
def product(n1 = 1, n2 = 1, n3 = 1, n4 = 1):
return n1 * n2 * n3 * n4
# multipling 2 numbers
print("{0} * {1} = {2} ".format(5, 10, product(5, 10)))
# multipling 3 numbers
... |
9639eef2aa3f2812c8376ec08b415c050428a5c4 | chandrakant100/Assignments_Python | /Practical/assignment3/pattern.py | 343 | 3.921875 | 4 | import math
num = input("Enter a number:")
if num.isnumeric() == 0:
print("Its is string")
exit()
num = int(num)
for i in range(num):
for j in range(num,i,-1):
print(" ",end = '')
for k in range(1,i+2):
if k % 2 == 0:
print("1",end = ' ')
else:
print("0"... |
c3eafe4b5b245cf0ad6e77460780af570a92560c | chandrakant100/Assignments_Python | /Practical/assignment4/factorial.py | 246 | 4.28125 | 4 | # To find factorial of a number using recursion
def rec_fact(num):
if num <= 1:
return 1
return num * rec_fact(num - 1)
num = int(input("Enter a number: "))
print("Factorial of {0} is {1}".format(num, rec_fact(num)))
|
d61ad114fac2c739b6230fee6acddf0008a1c094 | dmshelton/dmshelton | /learningPython/practicePython-ex6.py | 443 | 4.03125 | 4 | # BSD 3-Clause License
# Copyright (c) 2017, Darren Shelton
# All rights reserved.
def main():
print("Provide a word, and I will check to see if it is a palindrome: \n")
word = input("What is your word?")
backwards_word = word[::-1]
if str.lower(word) == str.lower(backwards_word):
print("The... |
39dd8df560136489ac4e3519807b2b295338ba86 | yuqiaoyan/fb_code | /sentiment/my_tokenizers.py | 2,043 | 3.5 | 4 | import re
import nltk.corpus
#exception = "\xe2\x80\x99\x93"
#word_pattern = re.compile(r"[a-zA-Z'-%s]+|[?!]"%exception)
word_pattern = re.compile(r"[a-zA-Z'-]+|[^\w\s]+")
def tokenize_sentence_emote(sentence, unique_stop_words=[]):
'''REQUIRES: string sentence to tokenized
OPTIONAL: unique_stop_words, to define yo... |
1bc3b9ed20421942dbb4fa426416a62280a0b27b | nattesharan/Datastructures-and-Algo | /BigO/bigO.py | 2,358 | 3.953125 | 4 | # Algorithm: A procedure a formula for solving a problem..
'''Why should we compare algorithms ??
Imaging two guys are asked to do a task like sum of n numbers... Both the guys may have different approaches
to do this. How would we say which one is the best ??
Say the two solutions are below how would we co... |
30c496b61fba0e0b46bf2dcb648db46812d21529 | ericjiang97/grad-inteview-practice | /Sorting/TimSort.py | 3,046 | 4.15625 | 4 | class TimSort:
def __init__(self, array, run_size=32):
self.array = array
self.run_size = run_size
def insertionSort(self, array, left_index, right_index):
""" performs insertion sort on a given array
:param array: the array to sort
:param left_index: the lower bound of ... |
349d17c98133a3970fe6f20f369a802ab59d8c3b | govindarajanv/python | /programming-practice-solutions/exercises-set-1/exercise-01-solution.py | 968 | 4.21875 | 4 | #1 printing "Hello World"
print ("Hello World")
#Displaying Python's list of keywords
import keyword
print ("List of key words are ..")
print (keyword.kwlist)
#2 Single and multi line comments
# This is the single line comment
''' This is multiline
comment, can be
used for a paragraph '''
#3 Multi line state... |
4f5ad33e6485de134980f5523cb21c41b51bfb99 | govindarajanv/python | /gui-applications/if-else.py | 338 | 4.15625 | 4 | #
number = 23
# input() is used to get input from the user
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.') # New block starts here
elif guess < number:
print('No, it is a little higher than that') # Another block
else:
print('No, it is a little l... |
05dd4f332bfcde3226a0ed1939be9228322bf2d2 | govindarajanv/python | /classes/decorator_for_custom_datatype.py | 651 | 4.09375 | 4 | class Student:
def __init__(self):
self.__name = ""
# here sname is taken as a reference and all setter and getter property will be based on this name
@property
def sname(self):
print ("getter is called")
return self.__name
@sname.setter
def sname(self,name):
p... |
6658ab77e9521efd122e1348c1860401d6b7abda | govindarajanv/python | /regex/regex-special-sequences.py | 1,679 | 4.34375 | 4 | import re
pattern = r"(.+) \1"
print ("pattern is",pattern)
match = re.match(pattern, "word word")
if match:
print ("Match 1")
match = re.match(pattern, "?! ?!")
if match:
print ("Match 2")
match = re.match(pattern, "abc cde")
if match:
print ("Match 3")
match = re.match(pattern, "abc ab")
if match:
... |
170ffd1a881e4043e7e9be7d70841c5652443d9d | govindarajanv/python | /regex/regex.py | 1,061 | 4.125 | 4 | import re
# Methods like match, search, finall and sub
pattern = r"spam"
print ("\nFinding \'spam\' in \'eggspamsausagespam\'\n")
print ("Usage of match - exact match as it looks at the beginning of the string")
if re.match(pattern, "eggspamsausagespam"):
print("Match")
else:
print("No match")
print ("\nUsag... |
8638bd18648d6ed7aceaffd6c842e42a0cad680b | govindarajanv/python | /functional-programming/loops/fibonacci.py | 539 | 4.1875 | 4 | """
0,1,1,2,3,5,8,13...n
"""
def factorial(n):
first_value = 0
second_value = 1
for i in range(1,n,1):
if i == 1:
print ("{} ".format(first_value))
elif i==2:
print ("{} ".format(second_value))
else:
sum = first_value + second_value
pri... |
04db43932905662ea741f34a135cd9097941e469 | govindarajanv/python | /regex/regex-character-classes.py | 1,794 | 4.6875 | 5 | import re
#Character classes provide a way to match only one of a specific set of characters.
#A character class is created by putting the characters it matches inside square brackets
pattern = r"[aeiou]"
if re.search(pattern, "grey"):
print("Match 1")
if re.search(pattern, "qwertyuiop"):
print("Match 2")
if... |
d217be148c6b0497e221f015e3be3b986b20582e | govindarajanv/python | /functional-programming/stack/stack.py | 413 | 3.984375 | 4 | stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print ("Intial stack is {}".format(stack))
print("Popping the first element")
print ("after pop,{} is removed, contents are {}".format(stack.pop(),stack))
print ("after pop,{} is removed, contents are {}".format(stack.pop(),stack))
print ("after pop,{} is re... |
5c2081b7eb58da37d4afdba914b95449fae253ac | Aaron-Dzaboff/Classic-Iris-Dataset-Analysis | /Project3_Code.py | 19,295 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 12:08:45 2020
@author: aaron
"""
# import needed libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Importing the data set
from sklearn import datasets
# 1.) import some data to play with
iris = datasets.load_iris()
X = ... |
30f0e6de3013c0e071b83bf9c116bf81da3848f9 | jlinear/remote_control_admin | /admin.py | 5,384 | 3.59375 | 4 | import socket
import threading
from time import sleep
from time import time
from queue import Queue
NUM_OF_THREADS = 2
JOB_NUM = [1, 2]
queue = Queue()
all_connections = []
all_address = []
# vars used to print correct prompt after a new connection
# new connections are printed and move cursor to a new line
# global ... |
10e85d68d0c5c121457de9a464b8cc8a22bf62db | Achraf19-okh/python-problems | /ex7.py | 469 | 4.15625 | 4 | print("please typpe correct informations")
user_height = float(input("please enter your height in meters"))
user_weight = float(input("please enter your weight in kg"))
BMI = user_weight/(user_height*user_height)
print("your body mass index is" , round(BMI,2))
if(BMI <= 18.5):
print("you are under weight")
elif(BMI... |
4f60f9d5114af31414e1d4e4c1c024722251390c | Achraf19-okh/python-problems | /jeu.py | 408 | 3.609375 | 4 | import random
print('ce jeu consiste à deviner un nombre entre 0 et 1000.\npour abandonner taper 1001')
n = random.randrange(0,1001)
c = 1
x = int(input('essai 1:'))
while x!=n and x!=1001 :
if x < n :
print('trop petit')
else :
print('trop grand')
c = c+1
x= int(input('essai' + str(c) + ':'))
if x == n :
... |
114750f010cf199646fd8865995fe1963a169b9d | mirajp/Statistical-Learning | /Mini Project #2 - Linear Regression/Linear Regression.py | 6,268 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.linear_model import Ridge, Lasso
from sklearn.preprocessing import scale
from operator import itemgetter
def linear_regression(X_train, Y_train) :
# Compute number of observations & features... |
3c1ed9201286aaf6e888c7832debe778f02c3d82 | ChallengerCY/Python-OperatorDemo | /PythonOperator/OperatorDemo5.py | 477 | 4.0625 | 4 | #表达式
#1、由值表达式
print(8)
#2、字符串表达式
print("hello")
#3、计算表达式 (值和运算符)
print(25+7)
#4、赋值表达式和变量表达式
a=67
print(a)
# is 运算符
#==用来判断俩个对象是否相等,is判定是否是同一个对象
#避免将is运算符用于比较类似数值和字符串这类不可变值,使用is运算符的结果是不可预测的
x=y=[1,2,3]
z=[1,2,3]
print(x==y)
print(x==z)
print(x is y)
print(x is z) |
69727f67b8301a856559c4d49b5141871e7d61d2 | adityaraaz01/opencv | /14 simple_thresholding_techniques.py | 952 | 3.796875 | 4 | '''
Date: 02-06-2020. Aditya Raj.
Level = Beginners.
Objective = Simple Thresholding Techniques.
'''
import numpy as np
import cv2
img = cv2.imread('gradient.png', 0)
_,th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)# Pixel value > Threshold will assign to 255 and Pixel value < Threshold will assign t... |
e5e26adc9ce9c5c85bd2b8afdb2bc556746f8d20 | azhar-azad/Python-Practice | /07. list_comprehension.py | 770 | 4.125 | 4 | # Author: Azad
# Date: 4/2/18
# Desc: Let’s say I give you a list saved in a variable:
# a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
# Write one line of Python that takes this list a and makes a new list
# that has only the even elements of this list in it.
# ------------------------------------... |
bcd76925689d3e401ce55f7efe88aa323b02c0d0 | azhar-azad/Python-Practice | /10. list_overlap_comprehensions.py | 995 | 4.3125 | 4 | # Author: Azad
# Date: 4/5/18
# Desc: Take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that
# contains only the elements that are common between the li... |
f2ce7880b7f4ac54fc10fa7dd22767b853855477 | AltChance/pwp-capstones | /TomeRater/TomeRater.py | 5,766 | 3.8125 | 4 | class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
def get_email(self):
return self.email
def change_email(self, address):
self.email = address
print(self.name + '\'s email has been updated!')
def __... |
b7018a4c6469992806f1c09e5b8eda3ead5cbcd2 | maverick27031989/Hacker-Rank-Practice | /PrintFunction.py | 163 | 4 | 4 | a = int(input("Enter a Number :: "))
for i in range(0, a):
print(i + 1, sep=' ', end='', flush=True) # that keeps the output in a straight line
|
134d74d8764c6c71d3da93914b055c6a651b8a27 | GordonWei/python-ftp | /getfile.py | 593 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
#author GordonWei
#date 07/31/2020
#comment connect ftp and get file
from ftplib import FTP
filterName = input('Pls Enter The FileName:' )
filterName = filterName + '*.*'
ftp = FTP()
ftp.connect(<ip>,<port>)
ftp.login(<loginuser>, <userpasswd>)
def get_File(filt... |
d032e1c2bed0a0a98e58e0216ebc57954397c115 | RP5018540/seleniumgit | /SampleProject/control statements.py | 3,991 | 4.09375 | 4 |
#emp_ID=1
#emp_name='John'
#empl_email_id='john1@gmail.com'
#emp_phone_no=9874563211
#emp_salary=20000
#emp_gender='Male'
#emp_city='chennai'
#print(emp_ID)
#print("emp_Id")
# student_Id=int(input("Enter the student ID: "))
# student_Name=str(input("Enter the student name: "))
# Mark_1=int(input("Enter t... |
56cc96bbd13e65bae0a9f225abb8b4fa790fb3f0 | RP5018540/seleniumgit | /SampleProject/Datatype input.py | 691 | 3.984375 | 4 |
#emp_ID=1
#emp_name='John'
#empl_email_id='john1@gmail.com'
#emp_phone_no=9874563211
#emp_salary=20000
#emp_gender='Male'
#emp_city='chennai'
#print(emp_ID)
#print("emp_Id")
# student_Id=int(input("Enter the student ID: "))
# student_Name=str(input("Enter the student name: "))
# Mark_1=int(input("Enter t... |
3bf3286001b6e1a112de0be3c34df480e307220e | ryuzu001/dailyprogrammer | /369.py | 1,227 | 3.984375 | 4 | # https://redd.it/a0lhxx
def hexcolor(colors):
col = colors.split(", ")
if not len(col) == 3:
print("Input error")
exit()
if not col[0].isdigit() or not col[1].isdigit() or not col[2].isdigit():
print("Number error")
exit()
a = int(col[0])
b = int(col[1])
... |
c4ee624c29d26122b4f97f3d0afd98a2e79f8418 | ddobos/lesson05 | /Food.py | 1,011 | 3.828125 | 4 | class Food:
def __init__(self, name):
self.name = name
def message(self):
print('Food is a life')
def energy(self):
raise NotImplementedError
def __str__(self):
return self.name
class Junk(Food):
def __init__(self, name, energy):
super().__init__(name)
... |
73d62048dff9063285a3b6542b0d9c718e22bccf | DT-S/tictactoe | /tictactoe_game.py | 4,033 | 4.3125 | 4 | # 12-04-2021
# V1.0
# Simple Code for Tic Tac Toe
# Fabrice Lezzi
# Programming Week: 1
#
# --------- Imported Library's ---------- #
import random
# --------- Global Variables ----------- #
# Stores the game board data
board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
# Stores the active player token
current_activ... |
860519c4322c29d72ba419f5f1da188c0ad84911 | lmilewicz/SNAKE_AI | /snake_game.py | 11,874 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import curses
from random import randint
import numpy as np
class SnakeGame:
def __init__(self, board_width=20, board_height=20, gui=False, binary=False):
self.snake = []
self.food = []
self.score = 0
self.binary = binary
self.win = None
sel... |
7b1eb732d0daf86f2a14ec7f21dcd04c0efec6e2 | k07713/cydf_ai | /a_star.py | 1,246 | 3.671875 | 4 | from queue import PriorityQueue
import copy
que = PriorityQueue()
fisrt = [[1,2,6], [0,4,3], [0,7,5]]
last = [[1,2,3], [0,0,4], [7,6,5]]
def f(start, goal, level):
return h(start,goal) + level
def h(start,goal):
temp = 0
for i in range(0,3):
for j in range(0,3):
if start[i][j] != goal... |
6c2bd53ca6944995ac4c162a12336c08d90f1e6a | Jarunee-Meesabtong/MAK-NEEB | /game2.py | 3,308 | 3.5 | 4 | import pygame
from constants import *
from board import *
from c1 import *
import traceback
class Game2:
def __init__(self, win):
self._init()
self.win = win
def _init(self):
self.selected = None
self.board = Board()
self.turn = RED
self.valid_moves = {}
... |
e4bca7544f2b86d4acdb49a1b2eb69755a30a480 | Fmancino/advent-of-code-2020 | /18/main.py | 2,149 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
def parse_in(std_in):
return [s.strip() for s in std_in]
def plus(a, b):
return a + b
def times(a, b):
return a * b
OPER_DICT = {'+': plus, '*': times}
def add_parens(text):
_open = 1
for idx, l in enumerate(text):
if l == '(':
_open += 1
... |
84cdb963f4a64e89e5076aeda69e8646b7fdedec | yrus98/successor_alien | /succ_alien.py | 1,671 | 3.796875 | 4 |
def create_dict_B_to_digit(B):
dict_B_to_digit = dict()
value = 0
for char in B:
if char in dict_B_to_digit:
raise Exception("Input Error: Duplicate characters in character set B !")
dict_B_to_digit[char] = value
value += 1
return dict_B_to_digit
def encode_to_alien_string(num, leading_zeros, B):
succ =... |
86ab95cb7e273e9867152b0c7219ffca93ad4fe7 | drowsell/RGB-to-HLS-Converter | /RGB-HLS.py | 998 | 3.671875 | 4 | def rgb_to_hls(r,g,b):
# Convert the RGB values to the range 0-1, this can be done by dividing the value by 255 for 8-bit colour depth
r = r/255
g = g/255
b = b/255
#Find the minimum and maximum values of R, G and B.
minimum = min([r,g,b])
maximum = max([r,g,b])
l = (maximum + minimum)/2
... |
1f3f615c62d6de6511019a6183513b7a9ec278da | athyrson-h/pygame | /main.py | 2,303 | 3.984375 | 4 | import turtle
class shape(turtle.Turtle):
def __init__(self, goto):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("black")
self.penup()
self.goto(goto, 0)
self.shapesize(5, 0.5)
#forma dos play
class player(shape):
def __init__(self, goto):
shape.__init__(self, goto)
... |
900685d187fce72a3edb34daef753d90395b2a8b | ARBUCHELI/100-DAYS-OF-CODE-THE-COMPLETE-PYTHON-PRO-BOOTCAMP-FOR-2021 | /Guess the Number/guess_the_number.py | 1,951 | 4.4375 | 4 | #Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Trac... |
7411d9b91601f354235447e51ee07269e5605500 | davxdan/DataAndNetworkSecurity | /HW2/working code for Modulus.py | 4,401 | 4.53125 | 5 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 00:43:25 2018
@author: Alex Salamah
Section 404
Ansswer for Exercise 1 part 3
This code asks the user select an action encrypt or decrypt then it prompts
the user to input the message. Code can handle / process any input i.e.
it can handle Alpha, numbers, alphanumer... |
09a4e5070ef9566e2efbd87e109b5eb25a9834a3 | gkayling/cloaked-octo-hipster | /ProjectEuler/p5.py | 331 | 3.890625 | 4 | import datetime
def isDivisible(num, low, high):
for i in range(high, low, -1):
if num % i != 0:
return False
return True
high = 20
num = high
start = datetime.datetime.now()
while not isDivisible(num, 1, high):
num += high
print num
end = datetime.datetime.now()
diff = end-start
print 'Duration: ' +... |
27226d0aa9deec3e84e2cfa51f2217c1b0e2a339 | gkayling/cloaked-octo-hipster | /ProjectEuler/p3.py | 299 | 3.546875 | 4 | import math
number = 600851475143
def isPrime(num):
for i in range(2, int(math.floor(math.sqrt(num)))):
if num % i == 0:
return False
return True
bigprime = 1
for i in range(1,int(math.floor(math.sqrt(number)))):
if number % i == 0 and isPrime(i):
bigprime = i
print bigprime
|
8fbde6ce1ebbf37efcff736d213040edadac5e2e | harshavardan25000-main/geekforgeeks | /Arrays/arrayRot_reverseBlock.py | 317 | 3.859375 | 4 | arr=[1,2,3,4,5,6,7,8,9]
d=2
l=len(arr)
def reverse(arr,start,end):
while start<end:
arr[start],arr[end]=arr[end],arr[start]
start,end=start+1,end-1
def rotation(arr,d,l):
if d==0:
return
reverse(arr,0,d-1)
reverse(arr,d,l-1)
reverse(arr,0,l-1)
rotation(arr,d,l)
print(arr) |
d8980a4378ebdbc774684badeb36f76eca8a5039 | ntelfer/pythonDataStructuresPractice | /binaryTree/Node.py | 704 | 3.921875 | 4 | class Node:
def __init__(self, val="", lNode=None, rNode=None):
self.value = val
self.leftNode = lNode
self.rightNode = rNode
def insert(self, val):
if val > self.value:
if self.rightNode is None:
self.rightNode = Node(val)
else:
... |
2a29710b1ce51119772ee86b796193f1eec0658a | tzyl/ctci-python | /chapter9/9.1.py | 726 | 4.28125 | 4 | def stair_permutations(n):
"""Returns the number of different ways a child can hop up a staircase
with n steps by hopping 1,2 or 3 steps at a time."""
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
return (stair_permutations(n - 1) +
stair_permutations(n - 2)... |
0252b4e076baf81508570df3000d168c0c7c7b98 | tzyl/ctci-python | /chapter9/9.9.py | 1,366 | 4.09375 | 4 | def arrange_eight_queens():
"""Gets all the different ways of arranging eight queens on an 8x8 chess
board such that no two queens share the same column, row or diagonal.
"""
solutions = []
fill_row(0, solutions, [], [], [], [])
return solutions
def fill_row(i, solutions, current, col... |
e4a101fc075ad62f0cd5e2196446330d3abdcc0d | tzyl/ctci-python | /chapter5/5.7.py | 1,265 | 3.859375 | 4 | def find_missing_integer(A):
"""O(n) solution using more complex method."""
n = len(A)
bit_length = 0
m = n
while m:
m >>= 1
bit_length += 1
ans = 0
for i in xrange(bit_length):
zeroes = [x for x in A if not x & 1 << i]
ones = [x for x in A if x & 1... |
9c050650a4b64905b6a089fb46eaf27b0a588139 | tzyl/ctci-python | /chapter1/1.5.py | 528 | 3.78125 | 4 | def basic_string_compression(s):
if not s:
return s
saved = 0
compressed = []
count = 0
start = s[0]
for i, c in enumerate(s):
if c == start:
count += 1
if i == len(s) - 1 or c != start:
compressed.append(start + str(count))
... |
4e51ccfe4bbdf4401dd6c2741d3f2d8ca63ef3c2 | tzyl/ctci-python | /chapter9/9.2.py | 1,672 | 4.125 | 4 | def number_of_paths(X, Y):
"""Returns the number of paths to move from (0, 0) to (X, Y) in an X by Y
grid if can only move right or down."""
if X == 0 or Y == 0:
return 1
return number_of_paths(X - 1, Y) + number_of_paths(X, Y - 1)
def number_of_paths2(X, Y):
"""Solution using mat... |
87ab1523b2dd3d3ea98954e30f8da13137a57ab1 | tzyl/ctci-python | /chapter11/11.1.py | 641 | 4 | 4 | # You are given two sorted arrays, A and B, where A has a large enough buffer
# at the end to hold B. Write a method to merge B into A in sorted order.
def merge(A, B):
# Work from the end and move elements into their correct place. O(n)
i, j = len(A) - 1, len(B) - 1
while A[i] is None:
i ... |
9f8201a7a55fd59dc02cdd24fbd64ee8cd10ebfc | tzyl/ctci-python | /chapter5/5.5.py | 736 | 4.28125 | 4 | def to_convert(A, B):
"""Clears the least significant bit rather than continuously shifting."""
different = 0
C = A ^ B
while C:
different += 1
C = C & C - 1
return different
def to_convert2(A, B):
"""Using XOR."""
different = 0
C = A ^ B
while C:
... |
8d869c4037eb3c9887025bafa726c5c65794b216 | tzyl/ctci-python | /chapter11/11.3.py | 2,346 | 3.59375 | 4 | # Given a sorted array of n integers that has been rotated an unknown
# number of times, write code to find an element in the array. You may
# assume that the array was originally sorted in increasing order.
# If all elemnts are not distinct we need to do extra searches.
def find_element(A, x):
stack = []
... |
4c00ccc04640dbdd9bff817f6f895641ece4c971 | CaptainMidnight/Sudoku-Solver-6 | /MAINMENU.py | 11,825 | 3.6875 | 4 | # from tkinter import Tk
from sudoku_utils import is_puzzle_valid , only_digits
import tkinter as tk
from tkinter.font import Font
import pprint
import time
from tkinter import messagebox
from sudoku_solvers import CP_with_MRV ,Basic_Backtracker
from puzzle_extractor import load_random_puzzle
# TODO - Add buttons for... |
a46a5c7ceee93d069d73575d3db5bbbee3eef66b | sleeptodeath/summer_project | /src/bullet.py | 14,693 | 3.6875 | 4 | # coding=utf-8
"""
子弹类的集合
玩家子弹:
Bullet
Bullet1
Bullet2
敌机子弹:
EnemyBullet1
EnemyBullet2
EnemyBullet3
"""
import pygame
from pygame.locals import *
from source import *
class BulletFactory(object):
"""子弹工产,用来生产子弹"""
def __init__(self):
pass
def make_bul... |
e7fb44ca81b0b01a866e87db7b22f59d48736a91 | iammaverick13/python-semester-ini | /function.py | 260 | 3.984375 | 4 | def additional(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
a = int(input('insert a number : ')
b = int(input('insert the second number : ')
print(additional(a, b))
|
c61471d83d375ead22f96a6d47b4b9f835b994f2 | MariaPetrova1993/testingMaria | /ДЗ1.задание1вар15.py | 478 | 4.0625 | 4 | a = int(input("Введите целое число:\n"))
b = int(input("Введите целое число:\n"))
c = int(input("Введите целое число:\n"))
d = int(input("Введите целое число:\n"))
if a%2 ==0:
print(str(a)+" - четное число")
if b%2 ==0:
print(str(b)+" - четное число")
if c%2 ==0:
print(str(c)+" - четное число")
if... |
418ca21f79c29e86a00a47a8177186ccaefdef97 | MariaPetrova1993/testingMaria | /ДЗ 2. Рекурсия.py | 569 | 3.953125 | 4 | a = int(input('Введите сторону прямоугольника a:\n'))
b = int(input('Введите сторону прямоугольника b:\n'))
A = []
def rec(a, b):
if a > b:
return rec(a - b, b) + rec(b, b)
elif a < b:
return rec(a, b - a) + rec(a, a)
elif a == b:
A.append(a)
return 1
A.sort(re... |
e46c3484f1214958d5f7c4574cb5be85b7336c0c | CharlesA750/practicals_cp1404 | /P5_Email.py | 579 | 4.28125 | 4 | email_dict = {}
def main():
email = input("What is your email address?\n>>> ")
while email != "":
nameget = get_name(email)
name_check = input("Is your name " + nameget + "? (y/n) ").lower()
if name_check == "y":
email_dict[email] = nameget
else:
real_name... |
2e925cbed4eaeb10f9f822f1b7600823bf8f0603 | carlosmertens/Python-Introduction | /default_argument.py | 2,221 | 4.59375 | 5 | """ DEFAULT ARGUMENTS """
print("\n==================== Example 1 ====================\n")
def box(width, height, symbol="*"):
"""print a box made up of asterisks, or some other character.
symbol="*" is a default in case there is not input
width: width of box in characters, must be at least 2
height... |
cf64717471c00ba262457cb47ef6b8fe1e23aa1c | pawansingh10/PracticeDemo | /CodeVita/FibRange.py | 282 | 4.0625 | 4 | def fibRange(first,second,n):
a=first
b=second
if n==1:
return a
elif n==2:
return b
else:
for i in range(3,n+1):
c=a+b
a=b
b=c
return b
first,second=0,1
n=12
print(fibRange(first,second,n)) |
e4232c807b730f7419e3b750122c765543747fc8 | pawansingh10/PracticeDemo | /CodeVita/Fibonacci.py | 1,724 | 4.125 | 4 | import math
"""USING RECURSION TIME COMPLEXITY EXPONENTIAL COMPLEXITY SPACE O(N)"""
def fib(n):
if n==0 :
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
"""USING DYNAMIC PROGRAMMING AVOID REPAETED WORK"""
def fibo(n):
fib_list=[0,1]
while len(fib_list)<n+1 :
... |
8add667460dc63ca62569c5170dab5e16ec78e35 | pawansingh10/PracticeDemo | /InterviewQ/pattern2.py | 384 | 3.75 | 4 | """
11112
32222
43333
54444
65555
76666
"""
n=6
'''
for i in range(1,n+1):
for j in range(1,n):
print(i,end="")
if
print()
for i in range(1,n+1,2):
print(i,i,i,i,i+1)
i+=1
print(i+1,i,i,i,i)
'''
k=n
for i in range(n):
for j in range(k):
print("",end="")
while j<... |
943f22a4987efd8ec189b12fe5994efbe69cd3cb | pawansingh10/PracticeDemo | /InterviewQ/fibinacci.py | 263 | 4.03125 | 4 | def fib(n):
f_list=[0,1]
if n==1:
return f_list[0]
elif n==2:
return f_list[1]
else:
for i in range(2,n):
f_list.append(f_list[i-2]+f_list[i-1])
return f_list
n=int(input("Enter the term:"))
print(*fib(n)) |
6f3884fc9e1db278a64a49710e4c6a936ade197a | pawansingh10/PracticeDemo | /HackWithInfy/Palindrome.py | 289 | 3.890625 | 4 |
def checkPalindrome(s):
s1=s[::-1]
if s==s1:
return "Palindrome!"
else:
return "Not Palindrome!"
def reverseString(s):
r=""
for i in range(len(s)-1,-1,-1):
r+=s[i]
return r
s="102001"
print(checkPalindrome(s))
print(reverseString(s)) |
680c9979e7e3ba578be70bbc89a825ccf18bbc4b | pawansingh10/PracticeDemo | /InterviewQ/reverseNum.py | 217 | 4.0625 | 4 | def reverse(n):
temp=n
reverse=0
while n>0:
rem=n%10
reverse=(reverse*10)+rem
n=n//10
return f'Reverse of {temp} is {reverse}'
n=int(input("Enter a num:"))
print(reverse(n)) |
76377cbdb563e421631ac545505c7cb311394d83 | NeahGarza/myDictionaries | /CountDictionary.py | 1,113 | 3.8125 | 4 | #Neah Garza
#MIS 4322
#Dictionary Exercise 1
def update_input(data):
data = data.replace('"', '')
data = data.replace('.', '')
#data = data.replace("'", "")
data = data.replace("‘", "")
#data = data.replace("’", "")
data = data.replace("-", " ")
data = data.repla... |
5e03b7a9787d2b6e3be87a7b18d9e1198c1b0ae9 | Boringdreams/CodeWars | /python/7kyu/Driving Licence/driver.py | 1,647 | 3.828125 | 4 | from datetime import datetime
def driver(data):
print(data)
first = data[2].upper() # The first five characters of the surname (padded with 9s if less than 5 characters)
while len(first)<5:
first = first + '9'
if len(first) > 5:
first = first[0:5]
print(first)
formatD... |
62ce698cea9b770dd6f641a27aec07034898d2e8 | usmanwardag/Python-Tutorial | /strings.py | 1,619 | 4.28125 | 4 | import sys
'''
Demonstrates string functions
'''
def stringMethods():
s = 'Hello, how are you doing?'
print s.strip() #Removes whitespaces
print s.lower()
print s.upper() #Changes case
print s.isalpha()
print s.isdigit()
print s.isspace() #If all characters belong to a class
print s.startswith('H'... |
6b68339e7fff555ed838c1350cf5def7945af08a | jgmanzanas/Prueba | /Prueba.py | 889 | 3.953125 | 4 | if __name__ == '__main__':
in_data = input("Write an integer: ")
try:
number = int(in_data) + 1 #Check Type
except ValueError:
ValueError("Data introduced is not a integer")
new_data = list(map(str, in_data))
original_len = len(new_data)
pos = original_len % 3
# Care with m... |
827d17365bc37db0f1c5c07cb1ffff695e9e52e3 | yuanwen000/yuanwen | /ooo.py | 95 | 3.953125 | 4 |
age = int (raw_input("please enter your name"))
if age >= 18:
print "ad"
else:
print "cc" |
8cc2fe68933531b73992062cd880978d27ee0511 | Micky143/LPU_Python | /Fuctions.py | 263 | 4.03125 | 4 | def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
n = input('enter your number :' )
for x in range(2, int(n)):
if is_prime(x):
print(x, 'is prime')
else:
print(x, 'not')
|
d9c4bbd50b8473f6dc1ad17b3e0fa4ec8ce5c424 | Micky143/LPU_Python | /Functions2.py | 725 | 4.3125 | 4 |
greeting ="hello World.!"
print(greeting)
print(greeting.find('lo')) #output :- 3
print(greeting.replace('llo', 'y')) #output :- hey World.!
print(greeting.startswith('hell')) #output :- True
print(greeting.isalpha()) #output :- False
greeting = "Micky Mehra..!"
print(greeting.lower(... |
673e41fef49a913b1f2cac9416bea4f11aade5b8 | Micky143/LPU_Python | /return fun.py | 142 | 3.6875 | 4 | def cube(M):
return M ** 3
print(cube(3))
''' return the addition of the No. '''
def add(M,K):
return M+K
print(add(5,5))
|
8cca35f0664b800db6cc47bde2ecf148e2b03b39 | minami14/Algorithm | /python/Euclid.py | 335 | 3.734375 | 4 | import math
import random
def Euclid(a, b):
x = a
y = b
if a < b:
x = b
y = a
while 1:
if x % y == 0:
return y
else:
x, y = y, x % y
a = random.randint(1, 100)
b = random.randint(1, 100)
GCD = Euclid(a, b)
print(a, b)
print(GCD)
print(math.gcd... |
25e3966054a470e3b18aa18704f460e6c14d4e84 | AmandaHenrique/Academia2019 | /Python-301/palavras.py | 172 | 3.84375 | 4 | name = 'Aula 01'
print(name[1:4]) #Mostra letra de 1 a 4#
print(len(name))
print(name.find('1'))
print(name.replace('A', 'h'))
print(name.upper())
print('0' in name) |
be955571ea17a553f7d942ec4f637a065313140f | OtmiVi/python | /function.py | 165 | 3.703125 | 4 | def hello():
print('Hello')
def func(a):
print(a)
a += 3
print(a)
a = 5
print(a)
a += 3
print(a)
hello()
hello()
x = 7
func(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.