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 |
|---|---|---|---|---|---|---|
57f2fb242f163be8132cfee38788e977b11c9bd4 | Daniellso000/exerciciospython | /desempenhotimes.py | 1,237 | 3.71875 | 4 | pontos = 0
gols = 0
contras = 0
partidas = 0
class Time():
def mediagols(gols, partidas):
x = gols / partidas
return x
def mediapontos(pontos, partidas):
y = pontos / partidas
return y
def calculargols(gols, contras):
z = gols - contras
return z... |
55885f48b318943495a44ff4454b5c21ca1f3f45 | sirajmuneer123/anand_python_problems | /3_chapter/extcount.py | 533 | 4.125 | 4 | #Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.
import os
import sys
cwd=os.getcwd()
def count(cwd):
list1=os.listdir(cwd)
newlist=[]
frequ... |
1f10e09ec50ed8ae452fc8129b4d637eff66b636 | sirajmuneer123/anand_python_problems | /2_chapter/cumulative_sum.py | 383 | 3.90625 | 4 | #Problem 8: Cumulative sum of a list [a, b, c, ...] is defined as [a, a+b, a+b+c, ...]. Write a function cumulative_sum to compute cumulative sum of a list. Does your implementation work for a list of strings?
def cumulative_sum(num):
sum=[]
temp=0
i=0
while i!=len(num):
temp=temp+num[i]
sum.append(temp)
i=i+... |
a360a18d93371e46214a28eb71275171a5a3a93c | sirajmuneer123/anand_python_problems | /3_chapter/regular_ex.py | 409 | 4.21875 | 4 | '''
Problem 9: Write a regular expression to validate a phone number.
'''
import re
def reg_exp(str1):
match=re.search(r'phone:\d\d\d\d\d\d\d|mobile:\d\d\d\d\d\d\d\d\d\d',str1)
if match:
print 'found'
s= re.findall(r'phone:\d\d\d\d\d\d\d|mobile:\d\d\d\d\d\d\d\d\d\d',str1)
for i in s:
print i
else:
print ... |
9fdf38d1a2c8bf2460625ff16b4ebc6692936cfc | sirajmuneer123/anand_python_problems | /2_chapter/factorial.py | 412 | 4.1875 | 4 | #Problem 5: Write a function factorial to compute factorial of a number. Can you use the product function defined in the previous example to compute factorial?
array=[]
def factorial(number):
while number!=0:
array.append(number)
number=number-1
return array
def product(num):
mul=1
a=len(num)
while a!=0:
m... |
d94770c1a7390f6496875a68025424d33fa93755 | sirajmuneer123/anand_python_problems | /6_chapter/p2.py | 414 | 3.953125 | 4 | """
Problem 2: Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.
"""
def flatten_dict(d,result=None,prefix=''):
if result == None:
result = {}
for key in d:
if isinstance(d[key],dict):
flatten_dict(d[key],result,prefix + str(key) + '.')
else:
result[prefix+... |
95bf6f759355c2b8e6413d38a9792210c1cb815e | sirajmuneer123/anand_python_problems | /2_chapter/sumstr.py | 244 | 3.734375 | 4 | #Problem 3: What happens when the above sum function is called with a list of strings? Can you make your sum function work for a list of strings as well.
def sum(x):
s=''
for i in x:
s=s+i
return s
print sum(['siraj','muneer','kk'])
|
38171858be0fc89461f6e38bb85d7585c18525c1 | LTTTDH/dataScienceHelpers | /NaNer.py | 477 | 4.125 | 4 | # This function was created to deal with numerical columns that contain some unexpected string values.
# NaNer converts all string values into np.nans
def NaNer(x):
"""Takes a value and converts it into a float.
If ValueError: returns np.nan
Originally designed to use with pandas DataFrames.
... |
75bbbb5489251c222770f09a7db5f86cf82e03d6 | A-Prathamesh1/SDN_Learning- | /SDN_to_set_up_an_arbitrary_path_between_two_hosts.py | 1,936 | 3.796875 | 4 | """
SDN to set up an arbitrary path between any two host
how use LLDP packets to discover hosts attached to switches.
Compute the k-shortest paths between those two nodes. to find
How many (simple) paths can you find between the two nodes
"""
# Non-Shortest Path Packet Routing, We don't usually do this but we need to... |
86e799994e384d8348b7cfd5bb72806a50eb1001 | sagarkamthane/selenium-python | /seleniumproject/practice/list.py | 670 | 3.796875 | 4 |
l = ['a', 1, 'b', 'cd', 's s k', 2.3]
print("lst", l)
print("index", l[2])
print("slicing",l[3:])
print(l[:3])
print(l[:3] + l[3:])
l.append(3)
print("append", l)
l.insert(2,3)
print("insert", l)
l.extend([7, "eight", [9, "nine", 9.0]])
print("extend", l)
print(l + [10, 11])
l[5:] = []
print(l)
print(['s'] * 3)
... |
03fbd4b416d36eea2aa98b0c7daead2e5192fa8f | sagarkamthane/selenium-python | /seleniumproject/pythonProject2/trycatch.py | 302 | 3.546875 | 4 |
try:
with open('txtt.txt', 'r') as readerror:
readerror.read()
except: #catch
print("error in try")
try:
with open('txtt.txt', 'r') as readerror:
readerror.read()
except Exception as e: #prints error reason
print(e)
finally:
print("it is executed every time") |
c5601ebd19fda93e75d4ec897958428b71d95e87 | sagarkamthane/selenium-python | /seleniumproject/Velocity/for loop.py | 243 | 3.765625 | 4 | for a in range(4) :
for b in range(2) :
print("Hi", end= "")
print("sagar", end="")
print("kamthane", end="") #prints in same line
print("ok")
for i in range(4):
for j in range(3):
print("*", end="")
print("")
|
b6a42b25d12a76a9192c557ecdb947662c07b2f5 | sagarkamthane/selenium-python | /seleniumproject/pythonProject2/new.py | 1,186 | 3.796875 | 4 | a=3
print(a)
hi = "hi"
print(hi)
a, b, c = 5, 10, "sagar"
print(a, b, c)
print("{} {} {}".format("Im", a, "years old"))
#list
values = [1, 2, 3, "four", 5, 6.1 ]
print(values[0:5])
values.insert(5, "six")
values.append(7)
values[1] = "two "
values.remove(6.1)
del values[5]
print(values)
#tuple
val = (1, 2,... |
051c485cf68844613d64f75d57de227f614be24e | SetOffAtDawn/python | /day1/var.py | 571 | 4.3125 | 4 | """"
变量
目的:用来存储数据
定义变量:
name = "huchao"
变量定义的规则:
字母、数字、下划线
第一个字符不能是数字
关键字不能作为变量名
不合适的变量名:
a1
a 不知道变量代表的意思
姓名 = 'huchao'
xingming = "huchao"
推荐写法:
girl_of_friend = "huchao"
"""""
print("hello world")
name = "huchao"
print("my name is ",name)
name = "huchao"
name2 = name
print("my name is ",name,name2)... |
21dc472d1a81eef46ac8de9b5e3370a94044cbea | SetOffAtDawn/python | /day2/字典.py | 1,294 | 4.03125 | 4 | #字典是无序的
info = {
'1':'book',
'2':'bike',
'3':'computer',
}
#字典的特性:key 唯一,字典是无序的
print(info)
#字典的增、删、改、查
#增
info['4'] = 'bag'
#删
del info
del info['2']
info.pop('2')
info.popitem()#随机删,最好就不要用了
#改
info['1']='desk'
#查
info['3']#可以将其打印出来 print(info['3']),只有在确认字典中有这个才用这种方法,否则没有的话就会出错
print(info.get('4... |
beaa93c691fb74169c9c06f29c2a72eea9f5d91b | deriksadiki/python-prac | /divisors.py | 239 | 3.90625 | 4 | def divisors(integer):
x = []
i = 2
while i < integer:
if integer % i == 0:
x.append(i)
i += 1
if len(x) == 0:
print(str(integer) + " is a prime")
else:
print(x)
divisors(13)
|
6dd0b1d7aaf12a7a2ebdfb94e0bf9ab0608f5627 | deriksadiki/python-prac | /cellnumbers.py | 398 | 3.65625 | 4 | def create_phone_number(n):
text = "("
for i in range(0,10):
if i <=2:
text += str(n[i])
if i == 2:
text += ") "
elif i > 2 and i <=5:
text += str(n[i])
if i == 5:
text += "-"
elif i > 5 :
text +=... |
cc8d797537d95fc05f0dcf77b5651fe31440271f | gokarna14/Chat | /useful_functions/strings.py | 1,901 | 3.890625 | 4 | def a_to_z_present(string):
for character in string:
if character.isalpha():
return True
return False
def digit_present(string):
for character in string:
if character.isdigit():
return True
return False
def special_character_present(string):
... |
c0f21f89665a5e12ec10f2dbbf24bdd0048dcacd | Vinothjoywlaker/pytestrepo | /Extracotr.py | 1,143 | 4.09375 | 4 |
class Extractor():
"""This class is used to extract information from the string or documents or webpages"""
def __init__(self):
pass
def phoneNumberExtractor(self,data):
"""
This function handled phone number extraction using various methods in the given data
:param data : type: string
:return set
"""
... |
04c60353f0f9e39b7d47819a01447d220d1934d2 | Vinothjoywlaker/pytestrepo | /class_testing.py | 710 | 4.03125 | 4 | #This script is for testing python class
class Base:
def __init__(self, name, age):
self.name = name
self.age = age
self.num = 20
def print_info(self):
print("This is from Base class".title())
print(f"student is {self.name} and his age is {self.age}")
class Child(Base):
def __init__(self,name,age,gender... |
2b674e250beff24935bd16cfc23d406bb88b95c3 | ShlhSio/Bartmoss | /Listes : Insérer.py | 362 | 3.75 | 4 | def collec(collection1, collection2, position):
if position < 0 or position > len(collection1):
return None
else:
for n in range(len(collection2)):
n = collection2[n]
collection1.insert(position-1, n)
return collection1
c1 = ['A', 'E', 'janvier', 7, 5]
c2 = ["Mars", ... |
0301d99596412496d5295f58eddb93d2bc1ef0be | ShlhSio/Bartmoss | /Boucles : Moyenne.py | 246 | 4.0625 | 4 | nbr_notes = input("Combien de notes avez-vous eu ?")
note = 0
notes = 0
while note < int(nbr_notes):
notes = notes + int(input("Donnez moi l'une de vos notes. >"))
note = note + 1
moyenne = notes / int(nbr_notes)
print(moyenne)
|
6e3ae062eb33ecfb41d0503791bc13aca5243bab | katsuunhi/python_demos | /温小胖作业/homework_python2.7.py | 1,437 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import Tkinter as tk
import tkMessageBox
window = tk.Tk()
window.title('triangle')
window.geometry('500x300')
l1 = tk.Label(window, text='first edge:',font=('Arial', 12),width=20, height=2)
t1 = tk.Entry(window,show = None)
l2 = tk.Label(window, text='second edge:',font=('Arial', 12),width=2... |
fcbba8657b7426a6f8caf229a1f094f51819a2bf | simonmichnowicz/swc | /bob.py | 136 | 3.515625 | 4 | file = open("sample.txt")
while True:
line = file.readline()
print "Line is ",line
if not line:
break
file.close()
print "BYTE"
|
9323e5586a6d173d996b3857b2a8d20b9c253810 | GaoFangshu/solve-games | /homework/HW1.py | 3,482 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Python 3.5.2
Game:
One to N
Rule:
There are N+1 slots (from 0 to N), and a piece is in slot 0. Each player can move the piece 1 to K slots ahead,
the player who reaches the slot N is winner.
"""
class OneToN:
def __init__(self, init_position=0, n_position=10, max_mov... |
fa58c2a04c98fbcc2b630b0ae376782a0db06fdc | antiface/actval | /tables.py | 1,794 | 3.875 | 4 | def generateAnnuityTable(assumptions, sex):
""" Generates a table of single life annuity values for each age
"""
mortality = (assumptions.maleMortality if sex[0].lower == "m"
else assumptions.femaleMortality)
interest = assumptions.interest
table = [0.0 for i in range(0, 120)]
for age in reversed(range(0,... |
04daa85dffc8866da7792c8620cb4748fbce7dff | Lokitosi/Python-UD | /Repaso para el parcial.py | 250 | 3.90625 | 4 | print (" X |", end=" ")
for i in range(1,11):
print ("%2d" % (i),end=" "),
print ("\n", "-"*35)
for i in range(1,11):
print ("%2d |" % (i),end= " "),
for j in range(1,11):
print ("%2d" % (i*j),end=" ")
print(" ")
|
c8a5689a00c96a4ce9cf4a42f29e61995d64c255 | Lokitosi/Python-UD | /PROYECTO notas.py | 2,160 | 3.96875 | 4 | import sys
# interfaz
print ("bienvenido a el sistema de notas" + "\n" + "los pasos a seguir son")
print ("1:ingresar notas" + "\n" + "2:Ver notas y sus estadisticas" + "\n" + "3:corregir nota")
print ("4:eliminar o añadir nota")
# Modos
# agregar notas
activate = 0
modo = int(input())
calificaciones = [... |
b00119c6d7ce4424b6e0053c8020173be45a0495 | TusharPatil31/Health-Tracker | /HealthTracker.py | 3,012 | 4.03125 | 4 | # This function is to calculate BMI
def bmi(Weight, Height):
bmi = Weight / ((Height/100)**2)
if bmi <= 18.4:
print(f"Your BMI: {format(bmi,'.1f')}. Try to put on some weight !")
elif bmi >= 25.0:
print(f"Your BMI: {format(bmi,'.1f')}. Try to loss weight !")
else:
print(f... |
ee9d018f5a7fd7e23e66f972c0ab3aa8f8d19e27 | PingryPython-2017/black_team_palindrome | /palindrome.py | 823 | 4.28125 | 4 | def is_palindrome(word):
''' Takes in an str, checks to see if palindrome, returns bool '''
# Makes sure that the word/phrase is only lowercase
word = word.lower()
# Terminating cases are if there is no characters or one character in the word
if len(word) == 0:
return True
if len(word) == 1:
return Tru... |
03ce252aff035661ceb8b2fd449ad8d93c7ee481 | dkrotx/daily-interview | /character-map.py | 481 | 3.546875 | 4 | def has_character_map(str1, str2):
if len(str1) != len(str2):
return False
charmap = dict()
for c1, c2 in zip(str1, str2):
if c1 in charmap:
if charmap[c1] != c2:
return False
else:
charmap[c1] = c2
return True
print(has_character_map('a... |
65360622dd035b3b6d4b1ade579793e61d578584 | VongRichard/Algorithms | /Lab6/Lab6_Q14.py | 3,451 | 4.125 | 4 | """Finally, you hit the big time. Now you have to write a
function huffman_tree(frequencies) that takes a dictionary mapping characters
to their frequencies and return a Huffman Coding tree represented using the Node
and Leaf classes given in the previous examples (or extensions of those
classes - see below). You ar... |
970c04ca2f06298520a63732aaac0899329ec9a9 | VongRichard/Algorithms | /Assignment quiz 2/Ass2Q1.py | 1,498 | 4.03125 | 4 | def longest_common_substring(s1, s2):
"""that takes two strings as parameters and returns
the longest common substring, using the algorithm
given in the notes"""
return lcs(s1, s2, cache=None)
def lcs(s1, s2, cache=None):
#Initialise variables
s1_len, s2_len = len(s1), len(s2)
... |
cd958a62776f20cdf29c9b7eb7ebd1d201e581f2 | VongRichard/Algorithms | /Lab9/Lab9_Q2.py | 669 | 4 | 4 | class Vec:
"""A simple vector in 2D. Also used as a position vector for points"""
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vec(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vec(self.x - other... |
75fdab72bc52df4116f583cea94b1f2066d27273 | VongRichard/Algorithms | /Lab10/Lab10Q3.py | 1,352 | 4.09375 | 4 | # Do not alter the next two lines
from collections import namedtuple
Node = namedtuple("Node", ["value", "left", "right"])
# Rewrite the following function to avoid slicing
def search_tree(nums, is_sorted=False, left=None, right=None):
"""Return a balanced binary search tree with the given nums
at the leave... |
4ceb6ef0c2d97778843ed635aa81bc0938edc79a | VongRichard/Algorithms | /Assignment quiz 2/Ass2Q2.py | 2,222 | 3.5 | 4 | def longest_common_substring(s1, s2):
"""Bruh"""
#Initilise rows and cols
n_rows = len(s1)
n_cols = len(s2)
#Making the table (row * col) to store dp values
grid = [["" for x in range(n_cols + 1)] for x in range(n_rows + 1)]
#Calculates the values that should go into rows
for... |
f26d5693862f924812f54127eb92d900345ca784 | AnantGup/Python-Project | /Pong/main.py | 325 | 3.5 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong by Anant")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
# Paddle 1
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.shape("while")
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle 2
# Game Loops
while True:
wn.upd... |
b674ece676899ef60de95c7463023ff5376c16ab | ikhanter/Rock_Paper_Scissors--Hyperskill | /Rock-Paper-Scissors/task/game.py | 1,854 | 3.984375 | 4 | import random
import sys
default_option = ['paper', 'scissors', 'rock']
print('Enter your name: ', end='')
username = input()
print(f'Hello, {username}')
option_input = input()
if option_input == '':
options = default_option
else:
options = [s for s in option_input.split(',')]
print('Okay, let\'s start')
with... |
18b80ac6e7d4bdae93fce7613de883e7ee2f4402 | fgsrfug/CS-325 | /hw3/knapsack.py | 3,918 | 4.34375 | 4 | #!/usr/bin/python3
############################################
# Jesus Narvaez
# CS 325 Homework 3
# knapsack.py
# February 3rd, 2020
# This file determines the largest value that
# can be placed into a knapsack of weight W.
# There is a recursive solution and a dynamic
# solution. Both are timed and compared.
#######... |
be832202e22425289126c594a6c5649cff49d533 | dan76296/stopwatch | /stopwatch.py | 1,495 | 4.25 | 4 | import time
class StopWatch:
def __init__(self):
''' Initialises a StopWatch object'''
self.start_time = None
self.end_time = None
def __repr__(self):
'''Represents the object in a readable format'''
return 'Time Elapsed: %r' % ':'.join((self.convertSeconds(self.resul... |
210a20f8472f96158334d9159efabc3e3f94cf07 | 1769778682/python06 | /work/work01.py | 785 | 3.875 | 4 | # print(True and 0)
# print(False or 4)
# print(True or False)
# print(2 and 1)
#
# print(4 or 0)
# print(3 and 4)
# print(False or True)
# print(True and 1)
#
# print(4 or False)
# print(True and 4)
# print(3 or True)
# print(True and 1)
#
# print(0 or True)
# print(True or 4)
# print(0 and True)
# print(3 and 1)
#
# ... |
d1aedeb9bf478767b463d66961a97446d49dd40c | 1769778682/python06 | /class1/c07函数参数和返回值.py | 588 | 3.859375 | 4 | # 定义函数的形式
def demo1():
"""无参数,无返回值"""
print('函数demo1')
def demo2():
"""无参数,有返回值"""
result = 100
return result
def demo3(num):
"""有参数,无返回值"""
print(num)
def demo4(num):
"""有参数,有返回值"""
print(num)
result = 100
return result
# 结论:如果需要从外部给函数内部传递数据,那么就需要定义函数添加参数
# 如果需要获取函数内部... |
4c6ccfd2c6ee728ddf61c418ecd90334b90a54d1 | phanirajkiran/cs107e.github.io | /assignments/assign4/starter/libs/get_bytes.py | 521 | 3.53125 | 4 | #! /usr/bin/env python
from __future__ import print_function
import binascii, sys
# This program takes an decimal integer string as its first argument and outs
# the 32-bit little endian representation of the integer.
full_hex = "{0:0{1}x}".format(int(sys.argv[1]), 8)
hex_string = "".join([full_hex[i-2:i] for i in ra... |
bc747c14c57f1d8b8aaccc03984bccfe584b57d5 | GitFiras/CodingNomads-Python | /09_exceptions/09_03_else.py | 505 | 3.90625 | 4 | '''
Write a script that demonstrates a try/except/else.
'''
while True:
try:
input_ = int(input("Please provide a number higher than 1: "))
calc_ = input_ + 100
if input_ < int(1):
print("This number is too low. Please provide a higher number.")
print(input_)
ex... |
aa08a6475f125520389646b0551301a54dafcf89 | GitFiras/CodingNomads-Python | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 992 | 4.4375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
# sort numbers
numbers_ = [ 1, 5, 4, 67, 88, 99, 3, 2, 12]
num... |
be616a73c1e05410a1461277824f37d45e8a3d24 | GitFiras/CodingNomads-Python | /13_aggregate_functions/13_03_my_enumerate.py | 693 | 4.3125 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate():
index = 0
value_list = ['apple', 'banana', 'pineapple', 'orange', 'grape'] # list
for value in value_list: ... |
64c9d551092b05a7d1fc1b4919403731cb2aa07d | GitFiras/CodingNomads-Python | /04_conditionals_loops/04_01_divisible.py | 473 | 4.40625 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
num = int(input('Please provide a number between 1 and 1,000,000,000: '))
if num % 3 == 0: # if output is 0, the numb... |
48550e1cb00bf023ec1394a0d0c8116fa0c8c456 | GitFiras/CodingNomads-Python | /06_functions/06_01_tasks.py | 2,146 | 4.25 | 4 | '''
Write a script that completes the following tasks.
'''
# define a function that determines whether the number is divisible by 4 or 7 and returns a boolean
print("Assignment 1 - Method 1:")
def div_by_4_or_7(x):
if x % 4 == 0:
print(f"{x} is divisible by 4: ",True) # boolean True if func... |
3ad789eadbc061a3dafa8af235e28282e659ad63 | GitFiras/CodingNomads-Python | /09_exceptions/09_05_check_for_ints.py | 669 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
while True:
try:
user_input = input("Please provide ... |
c43746c218b0df727e187614f7859b0146575356 | GitFiras/CodingNomads-Python | /03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 506 | 4.3125 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list_ = []
# Iteration from dict to list with tuples
for i i... |
eaff47a1ee62690db5a71d1f235dc8635c238202 | GitFiras/CodingNomads-Python | /15_generators/15_03_floor.py | 311 | 3.875 | 4 | '''
Adapt your Generator expression from the previous Exercise
(remove the print() statement), then run a floor division by 1111 on it.
What numbers do you get?
'''
my_list = range(1,100000)
generator = (num for num in my_list if num % 1111 == 0)
floor_gen = [num // 1111 for num in generator]
print(floor_gen) |
20acb5c9c5b63cfb04b70a82a815027e856fb517 | GitFiras/CodingNomads-Python | /Inheritance - Course Example Code.py | 1,361 | 4.46875 | 4 | class Ingredient:
"""Models an Ingredient."""
def __init__(self, name, amount):
self.name = name
self.amount = amount
def expire(self):
"""Expires the ingredient item."""
print(f"whoops, these {self.name} went bad...")
self.name = "expired " + self.name
def __str__(self):
return f"You h... |
98faf534a9a12528e3d95bad178048cdbbdb0013 | Keshav7aug/Python | /Linked_List/Pascal_Triangle.py | 352 | 3.9375 | 4 | def nth_row_pascal(n):
if(n==0):
return [1]
else:
A=[1]
B=nth_row_pascal(n-1)
for a in range(len(B)-1):
A.append(B[a]+B[a+1])
A.append(1)
return A
def print_space(n):
for i in range(n):
print(' ',end=' ')
a=int(input(... |
2f58121a0e19243ff43b0635ba5ac443adbf0ee5 | Keshav7aug/Python | /Recursion/Return_Subsets.py | 570 | 3.671875 | 4 | def all_Subsets(ls):
Ans=[]
if(len(ls)<=1):
Ans=[ls]
else:
for i in range(len(ls)):
if [ls[i]] not in Ans:
Ans.append([ls[i]])
j=i+1
if j<len(ls):
sme=all_Subsets(ls[j:])
for k in sme:
... |
14d99a0e85a8334af6689f1ea5f29669b15c3e6d | jordanemedlock/People | /lib/powertypes.py | 1,606 | 3.625 | 4 |
"""
Symbol class which should replicate/encapsulation the string type
So at the moment this only contains a string and checks equality
normally, so theres nothing added by this class, but I would like to
have this represent a "fuzzy" string, where you can have many representations
and it can encorporate typos and ya... |
1a78c0c29bc4c6a3ead3c4d464789d1a0af0efe7 | teamdaemons/100daysofcode | /Day18/main.py | 807 | 3.953125 | 4 | from turtle import Turtle, Screen
import random
tim = Turtle()
screen = Screen()
tim.shape("turtle")
tim.color("red")
def square():
# Draw a square
for _ in range(4):
tim.forward(100)
tim.right(90)
# square()
def dotted_line():
# tim.right(90)
for _ in range(50):
tim.forwa... |
aca7ab41804e618a5476e3e43dc964fcf2be900c | teamdaemons/100daysofcode | /Day27/tkinter_exercise.py | 710 | 4.0625 | 4 | from tkinter import *
window = Tk()
window.title("My first tkinter App")
window.minsize(width=500, height=300)
my_label = Label(text="I am a Label", font=("Arial", 24, "bold"))
my_label.pack()
my_label.grid(column=0,row=0)
def button_clicked():
my_label["text"] = "Button got Clicked"
my_label.config(text=i... |
1592a2f312a4f5687a6006dd90aacf63b86393cb | teamdaemons/100daysofcode | /Day8/functions.py | 273 | 3.625 | 4 | # Review:
# Create a function called greet().
# Write 3 print statements inside the function.
# Call the greet() function and run your code.
def greet(name,location):
print(f"My name is {name}")
print(f"I am from {location}")
greet(location="california",name="Mark") |
068f54bf2923d7ff3f3141744be4029bc337d598 | teamdaemons/100daysofcode | /Day4/whopaysbill.py | 494 | 3.9375 | 4 | import random
test_seed = int(input("Enter the seed number"))
random.seed(test_seed)
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#print(names)
#print(names[0])
... |
68e082e49104d10e87ca3417de722cf2f34e7cc6 | 13163203690/scraping | /selenium1.py | 2,302 | 3.75 | 4 | '''
from selenium import webdriver
# chromedriver的绝对路径
driver_path = r'F:\Anaconda3\Scripts\chromedriver.exe'
# 初始化一个driver,并且指定chromedriver的路径
driver = webdriver.Chrome(executable_path=driver_path)
# 请求网页
driver.get("https://www.baidu.com/")
# 通过page_source获取网页源代码
print(driver.page_source)
# hide browser window
'''
#... |
35e7dac35147e8deb769f8d27b71fdd61eda0863 | kalvatn/projecteuler | /lib/util.py | 1,957 | 3.625 | 4 | #!/usr/bin/env python
from collections import deque
def string_rotations(s):
rotations = []
dq = deque(s)
for i in range(len(s)):
dq.rotate(1)
rotations.append(''.join([c for c in dq ]))
return rotations
def read_file(filename):
return [ line.strip() for line in open(filename) ]
... |
8e1fa8a122db070741ada6d89087ae85389e4743 | gbbDonkiKong/UdemyAI_Template | /Chapter2_Python/enumAndZip.py | 189 | 3.84375 | 4 | list_a = [10, 20, 30]
list_b = ["Jan", "Peter", "Max"]
for value_a, value_b in zip(list_a, list_b):
print(value_a, value_b)
for i in range(len(list_a)):
print(i, ": ", list_a[i]) |
9e6838fa28c9f6655ea4a87ccfa511a6c3bc5615 | NeoFantom/PAT | /PAT Tests/20200725(Spring)/review/7-1PrimeDay.py | 1,034 | 3.9375 | 4 | import math as m
isPrime = []
primes = []
def primeTableUnder(n):
n = int(n)
global isPrime
isPrime = [True] * n
root = m.sqrt(n)
i = 2
while i <= root:
if isPrime[i]:
primes.append(i)
k = i + i
for k in range(i * 2, n, i):
... |
dd3a1fb2e5d36a0799733dfdc23fe01b274e29c5 | youralien/SoftwareDesign | /hw6/PlayingWithFireDemo.py | 28,115 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 7 20:44:17 2014
@author: jenwei,ryanlouie,julianmorris
Wall Collision Code Adapted from:
http://programarcadegames.com/python_examples/f.php?file=move_with_walls_example.py
"""
# --- Menu Opening Screen
"""Used code from the website below for the menu of this game.
ht... |
2d3d52bb87089c545a92cf9d1ce668cddd4a7ca4 | peterjhyoon/rsa-math | /math_functions.py | 1,073 | 3.875 | 4 | #Fundamental Math Functions
def is_prime(n):
assert type(n) == int
if n < 2:
return True
else:
for i in range(2, n):
if n % i == 0: #n has a factor
return False
return True
def divisor(n):
lst = []
for i in range(1, n + 1):
if n % i == 0:... |
333def98a0d89131255c05cdda32b5bc2decb1be | DanielaBeltranSaavedra1/TrackIt | /Sistema/LogicaNegocio/Resultados.py | 6,254 | 3.53125 | 4 |
from tkinter import Frame
from tkinter import Label
from tkinter import Button
import tkinter
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Pronostico import prediccion
"""
Description: This method creates the results interface in which t... |
1e8bcc3ebb084185cfc7a460234e3df36ea8e2a2 | DanielaBeltranSaavedra1/TrackIt | /Sistema/Pruebas/Pruebas.py | 4,744 | 3.5 | 4 | import pandas as pd
#PRUEBAS DE PREDICCION
#Error Percentage
#Description: This function give to result the percentage of error for the predict value
def errorPercentage(realValue,predictValue):
difference=abs(realValue-predictValue)
percentage=(100*difference)/realValue
return percentage
#Get Reak Value
... |
d4e7052ab81756075baabff5061f6ae0d3d6efc3 | shobhadhingra/Akademize-grofers-python | /12_maximum_of_4_number.py | 394 | 4 | 4 | a= int(input("Enter a: "))
b= int(input("Enter b: "))
c= int(input("Enter c: "))
d= int(input("Enter d: "))
if a > b and a > c and a>d:
print(f"Max = {a}")
elseif:
print(f"Max ={c}")
else:
print(f"Max ={d}")
else:
if b > a and b > c and b > d:
print(f"Max = {b}")
... |
d69b75c26b2b5e5dfaa52255c6afbf367019f344 | shobhadhingra/Akademize-grofers-python | /31_print_first_n_odd.py | 71 | 3.578125 | 4 | n = int(input("Value of N:-"))
for i in range(1,n*2+1,2):
print(i) |
821ccb85e64dd5ca0a685f6829280590e487552d | shobhadhingra/Akademize-grofers-python | /19_else_if_adder.py | 194 | 4.21875 | 4 | age= int(input("Enter age:-"))
if age <5:
print("Infant")
elif age <13:
Print("child")
elif age <20:
Print("teen")
elif age <60:
Print("Adult")
else:
print("Senior Citizen") |
d75e1dfa32d326c57d0241ed8b9ddf06dbd79fe1 | shobhadhingra/Akademize-grofers-python | /34_printing_lines.py | 150 | 3.796875 | 4 | def print_line(n):
for i in range(n):
print("_", end="")
print()
def main():
for i in range(5):
print_line(i+1)
main()
|
f39fadba2f9d57dd9c9f59c827619f891d579fa4 | SnehaMercyS/python-30-days-internship-tasks | /Day 7 task.py | 1,734 | 4.125 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #1) create a python module with list and import the module in anoother .py file and change the value in list
>>> list=[1,2,3,4,5,6]
>>> import m... |
57f431a34996a079438dd3035d7d076450b76d06 | ratkinson0405/python_list | /hostslist.py | 717 | 3.640625 | 4 | import argparse
import json
argParser = argparse.ArgumentParser(description='Parse the exported JSON host list and produce a .CSV file.')
argParser.add_argument('-if', '--inputfile', help='Input JSON File', required=True)
args = argParser.parse_args()
with open(args.inputfile, 'r') as inputfile:
host_list_dict ... |
0e09feaa86a5775797bb547188b4108994be8cd9 | Allen-Cee/Python | /25 Programs/0001 Coupon.py | 401 | 3.5625 | 4 | #使用 Python 生成 200 个激活码(或者优惠券)
#方案1 使用string和random模块
#方案2 使用uuid模块生成唯一标识符
import string
import random
#Coupon length
length=int(input())
char=string.ascii_uppercase+string.digits
def GenerateCoupon(length):
c=''
for i in range(length):
c+=random.choice(char);
return c
for i in range(200):
print(GenerateCoupo... |
965913ee67ca78b59a40c203d1a47a9713bc30d0 | abhishekmulik/linear-data-structures | /Queue_using_linkedList.py | 1,427 | 4 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Queue:
def __init__(self):
self.head=None
self.front=None
self.rear=None
def isEmpty(self):
if self.head==None:
return True
return False
def enqueue(sel... |
f325f06db10a19d3203c0a5572ba2f0e81b50a6f | Comeonboy/estrutura-de-dados | /bubble_sort.py | 850 | 3.734375 | 4 | import unittest
#O(n²) para tempo de execução e O(1) para memória, no pior caso
def bubble_sort(seq):
n = len(seq) - 1
flag = 0
for i in range(n):
for j in range(n):
if seq[j]>seq[j+1]:
seq[j+1], seq[j] = seq[j], seq[j+1]
if flag == 0:
break;
... |
9a3ec2a372b541407f78b7b4c146325fe296d937 | KY0915/LEETCode | /heapSort.py | 691 | 3.9375 | 4 | #How to create a heap and heapSort . for min, change largest to smallest and make smallest the smallest of l and r.
def heapify(arr,n,i):
largest=i
l=2*i+1
r=2*i+2
if l< n and arr[l]> arr[i]:
largest=l
if r < n and arr[r] > arr[largest]:
... |
148d9c22adfd0d3e83d987f153a343df0b4e20b2 | clopez5313/Python | /1. Become a Python Developer/2. Python Essential Training/Built-in Functions/zipFunction.py | 159 | 3.984375 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = (1,2,3,4,5)
y = (6,7,8,9,10)
z = zip(x,y)
for a,b in z:
print("{} - {}".format(a,b))
|
95184a0c6b8f63b19e30bd8cc518b5bc7851ab37 | clopez5313/Python | /1. Become a Python Developer/7. Python Data Structures - Dictionaries/dictionaryChallenge2.py | 695 | 3.8125 | 4 | #getting a dictionary from a text file
#Getting a dictionary from a CSV file
import csv
with open('treeorderssubset.csv', mode='r') as infile:
reader = csv.reader(infile)
#1st Video - creating a dictionary - walk them through this. And introduce the idea of a Case Study
treeOrders ={}
for row in reader... |
ff5ab0479685f05bb48735e125e5525a132fb763 | clopez5313/Python | /1. Become a Python Developer/5. Python Data Structures - Stacks, Queues, and Deques/Queues/queueChallenge.py | 1,623 | 3.671875 | 4 | import random
class PrintQueue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
if(len(self.items) > 0):
return self.items.pop()
return None
def peek(self):
if (len(self.items) > 0):
... |
81af9ef448d9228b34e6c8017b034ccd6405d9ea | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Arrays/2dArrays.py | 1,025 | 4.125 | 4 | import os
# Create a 2D array and print some of their elements.
studentGrades = [[72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60]]
print(studentGrades[1])
print(studentGrades[0])
print(studentGrades[2])
print(studentGrades[3][4])
# Traverse the array.
for st... |
ba5b7564b61ea7d0bacdfcb2ac19024a39f163ae | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Stacks and Queues/sortingQueues.py | 730 | 4.15625 | 4 | import queue
# Create the object and add some elements to it.
myQueue = queue.Queue()
myQueue.put(14)
myQueue.put(27)
myQueue.put(11)
myQueue.put(4)
myQueue.put(1)
# Sort with Bubble Sort algorithm.
size = myQueue.qsize()
for i in range(size):
# Remove the element.
item = myQueue.get()
#Remove the next... |
c7dc710dd1aa33d463ffeb1868aafec97048e767 | clopez5313/Python | /2. Advance Your Skills in Python/3. Effective Serialization with Python/Python-specific Serialization Formats/pickleExample.py | 892 | 3.734375 | 4 | """Basic pickle exmaple"""
import pickle
from moves import move1, move2, move3, move4
# print(move1)
data = pickle.dumps(move1) # serialize. data is of type "bytes:
# print(data)
# print(type(data))
move1d = pickle.loads(data) # de-serialize
# print(f'de-serialized data = {move1d}')
# serialize to file
with open('... |
25438e596f02cac2323bac935732509169469f97 | clopez5313/Python | /1. Become a Python Developer/11. 8 Things You Must Know in Python/min() and max() Methods/challenge4.py | 1,746 | 3.9375 | 4 | import string
DICTIONARY = 'dictionary.txt'
letter_scores = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4,
'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3,
'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8,
... |
5562c7691035233a625d4c60ccbfd368f35c69a2 | clopez5313/Python | /3. Advance Your Skills as a Python Data Expert/2. NumPy Data Science Essential Training/Create NumPy Arrays/intrinsicCreation.py | 1,167 | 3.78125 | 4 | import numpy as np
import os
# Clear function for the console.
clear = lambda: os.system("cls")
# Calling arange() by itself will cause a runtime error.
# arange(7)
# An array of integers between 0 and 6.
print(np.arange(7))
# An array of integers between 10 and 22.
np.arange(10, 23)
# Subtract 10 from the range ... |
98e6a613b1d2b09ed3013deee6e2e4177a432693 | clopez5313/Python | /3. Advance Your Skills as a Python Data Expert/1. Building a Recommendation System with Python Machine Learning & AI/Simple Approaches to Recommendation Systems/popularityBased.py | 990 | 3.671875 | 4 | import pandas as pd
import numpy as np
import os
frame = pd.read_csv('rating_final.csv')
cuisine = pd.read_csv('chefmozcuisine.csv')
# Clear function for the console.
clear = lambda: os.system("cls")
# Returns a table with user reviews to different restaurants.
print(frame.head())
clear()
# Returns a table with re... |
6630232ad4666101339e5c59a4e951e80594a6cf | wwwerka/Zadania-Python | /Zestaw 7/frac7.py | 5,869 | 3.53125 | 4 | from math import gcd
from functools import total_ordering
class frac:
def __init__(self, x=0, y=1):
if y == 0:
raise ZeroDivisionError("Mianownik musi być różny od 0")
self.x = x
self.y = y
# Chce żeby obsługiwał floaty bez zmieniania w testach z 1 na 1.0
... |
85c5bb06d2688e66eb3192257e37bc532fe7f851 | Vipamp/pythondemo | /com/heqingsong/Basic/OperationalCharacter/Demo2.py | 1,480 | 4.0625 | 4 | # -*- coding: utf-8 -*-
'''
@Author:HeQingsong
@Date:2018/9/24 17:20
@File Name:Demo2.py
@Python Version: 3.6 by Anaconda
@Description:比较运算符
'''
'''
比较运算符:
== 等于 比较对象是否相等 (a == b) 返回 False。
!= 不等于 比较两个对象是否不相等 (a != b) 返回 True。
> 大于... |
ead8ebc089b757ecd403a157356018c0224d35ba | Vipamp/pythondemo | /com/heqingsong/Tools/MatplotlibDemo/Demo04.py | 558 | 3.75 | 4 | # -*- coding: utf-8 -*-
'''
@Author:HeQingsong
@Date:2018/10/9 11:23
@File Name:Demo04.py
@Python Version: 3.6 by Anaconda
@Description:设置图线类型
'''
import matplotlib.pyplot as plt
# 设置图的名称
plt.title("hello ")
# 1、画散点图
x = [1, 2, 3, 4, 5]
y = [3, 4, 6, 7, 8]
plt.plot(x, y, '-')
plt.p... |
a3004a7d41bd11158e6a17b9821253e53480c444 | Vipamp/pythondemo | /com/heqingsong/Basic/MyTest/Demo02.py | 305 | 3.5 | 4 | # -*- coding: utf-8 -*-
'''
@Author:HeQingsong
@Date:2018/9/24 17:08
@File Name:Demo02.py
@Python Version: 3.6 by Anaconda
@Description:递归方式求阶乘
'''
def res(n):
if n == 0:
return 1
else:
return n * res(n - 1)
print(res(3))
|
ae764a5a64f7b916476b77e991216be13725813d | Vipamp/pythondemo | /com/heqingsong/Basic/MyTest/Demo04.py | 450 | 3.75 | 4 | # -*- coding: utf-8 -*-
'''
@Author:HeQingsong
@Date:2018/9/24 17:11
@File Name:Demo04.py
@Python Version: 3.6 by Anaconda
@Description:列表推导式作数据筛选
'''
list = [1, 3, 63, 4, 6, 72, 354, 8, 64]
# 筛选出大于10 的数据
list2 = [x for x in list if x > 10]
print("出大于10 的数据:", list2)
# 筛选出可以被4整除的数据
list3... |
924129476fb6394b98270e275fa24c03258d1f1f | beepscore/argparse | /arg_reader.py | 1,440 | 4.0625 | 4 | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text
import argparse
from arg... |
2526c1e1b8e175fba32edf1666d2711a931b8629 | VeryKumar/race_for_eva | /Litterally my first game.py | 2,722 | 3.8125 | 4 | import pygame
import time
pygame.init()
game_width= 800
game_height= 600
black = (0,0,0)
white = (255,255,255)
green = (161,185,81)
blue = (161,185,253)
brown = (62,26,1)
car_width = 32
gameDisplay = pygame.display.set_mode((game_width,game_height))
pygame.display.set_caption ('Chimera Ants: Racing ... |
72d926636f2c160c437a590690b0fd54301fe9a4 | C8364/ferdi.github.io | /pwd_reminder.py | 265 | 4 | 4 | user = "Ferdi"
password = "W_c1E@2a"
attempt = input("write your first name to get password : ").lower().title()
if attempt == user :
print("Hello {}! Your password is : {}".format(attempt, password))
else :
print("Hello {}! See you later.".format(attempt))
|
e5992fd33a8207f2a4c318e4bb2c94c932ad2ed8 | TracyOgutu/Password-Locker | /run2.py | 6,619 | 3.875 | 4 | #!/usr/bin/env python3.6
import random
from user import User
from credential import Credential
def create_user(usern, userpass):
new_user = User(usern, userpass)
return new_user
def save_users(user):
user.save_user()
def del_user(user):
user.delete_user()
def login(user, passw):
login = Use... |
ec94e882ff4f039bad9c0785c6d615c445cb706b | shyboynccu/checkio | /old_library/prime_palindrome.py | 1,877 | 4.28125 | 4 | #!/usr/local/bin/python3
# An integer is said to be a palindrome if it is equal to its reverse in a string form. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N. You must find the smallest integer M >= N such that M is a prime number and M is a palindrome.
# Input: An integer... |
9570c0d0bad6cf9492fd40177fae1c5d6a8eb03d | DeveloperRachit/PythonDevelopment | /Python_Modules/test.py | 650 | 3.96875 | 4 | from sys import argv
print(len(argv))
print(argv)
for x in argv:
print(x)
a,b,c=10, 20,30
print(a,b,c)
print(a,b,c,sep=',')
print("hello",end='')
print("student",end='')
print("python" ,end='')
print(10,20,30,40, sep=':',end='...')
print(10,20,30,40, sep='-')
print("the value is %a" %a)
print("a value is %i and b... |
63476e0cde925165cc8fc5ca0fba4b556a23591e | DeveloperRachit/PythonDevelopment | /filesys.py | 329 | 3.5 | 4 | obj=open("abcd.txt","w")
obj.write("Welcome to the world of Python")
obj.close()
obj1=open("abcd.txt","r")
s=obj1.read()
print (s)
obj1.close()
obj2=open("abcd.txt","r")
s1=obj2.read(20)
print (s1)
obj2.close()
objA = open("data.txt", "w")
print (objA.name)
print (objA.mode)
print (objA.... |
329c90745d34d2cfc3c5e7e5a918ee3e4d0c4c3d | emilnorman/euler | /problem010.py | 689 | 3.703125 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
def sundaram(limit):
# All primes except 2
# Generate base table
all = range(1, (limit - 2) / 2, 1)
# Remove numbers
for j in xrange(1, limit):
... |
b11df8ac4815beda9256b0050a085b34933c8e9e | emilnorman/euler | /problem044.py | 395 | 3.640625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import math
def isPenta(number):
num = (math.sqrt(1+24*number) + 1.0) / 6.0
return (num == int(num))
notDone = True
j = 1
while(notDone):
j += 1
p1 = int(j*(3*j-1)/2)
for k in range(1, j):
p2 = int(k*(3*k-1)/2)
if isPenta(p1-p2) and isP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.