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 |
|---|---|---|---|---|---|---|
4e2ef0356ae9ea18adc30bcaf292aa3ad971c7a8 | Regenyi/python | /todo.py | 400 | 3.5 | 4 | import sys
if sys.argv == 2:
with open("todo.txt","a") as todofile:
todo = input("what is your task?")
todofile.write(todo + "\n")
todofile.close()
with open("todo.txt","r") as todofile:
for i, line in enumerate(todofile):
print('{}.{}'.format(i+1, line.strip()))
prin... |
bc67d835d21b81afaba9b1540e9caebb9af89496 | Randi90/Oving_9 | /Øving 8/Øving 8bc.py | 1,406 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 15:49:00 2021
@author: Randi
"""
class Spørsmål:
def __init__(self, spørsmål, svar, alternativ):
self.spørsmål=spørsmål
self.svar=svar
self.alternativ=alternativ
def __str__(self):
tekst=self.spør... |
a3c4170dbc8d48142cf7f8319ba45775e1956886 | Tij99/compsci-jmss-2016 | /triangleXs.py | 384 | 4.28125 | 4 | # Write a program to print out an isosceles triangle of Xs
# rewrite the program to work for an arbitrary number of rows (ie the user can
# enter the required number of rows)
def triangle(height):
for i in range(height):
spaces = height - i - 1
xs = 2 * i + 1
print("-" * spaces + "|" * xs ... |
22731da8930d9a1902e20bb480061f7aa769034a | OmarAlShalabi/CommEng | /Matplotlib.py | 836 | 3.75 | 4 | '''
==================
Rotating a 3D plot
==================
A very simple animation of a rotating 3D plot.
See wire3d_animation_demo for another simple example of animating a 3D plot.
'''
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.... |
a64c7723c900a13fb756a653e95595316f5b3722 | VitorSchweighofer/exertec | /Exercicio4/exercicio 4/exe7.py | 142 | 3.8125 | 4 | numeroLimite = int(input('Digite o limite aqui: '))
for multiplos in range (numeroLimite,-1,-1):
if multiplos % 7 == 0:
print(multiplos) |
19398fba45efe1e0e3346a166d55e4d049cee630 | VitorSchweighofer/exertec | /prova 1/prova 1/exe1.py | 510 | 3.734375 | 4 | morango = float(input('Insira a quantidade em kg dos morangos: '))
maça = float(input('Insira a quantidade em kg das maçãs: '))
if (morango<=5):
morangoP = 2.5 * morango
if (maça<=5):
maçaP = 1.8 * maça
if (morango>5):
morangoP = 2.2 * morango
if (maça>5):
maçaP= 1.5 * maça
valor = morangoP + maçaP
i... |
4b2a326a5f5573df689c8680d489ac37e7dd82da | VitorSchweighofer/exertec | /Exercicio3/Exercicio 3/exe7.py | 436 | 4.09375 | 4 | number = float(input('digite aqui o número: '))
resultado1 = number%2
resultado2 = number%3
resultado3 = number%5
if (((resultado1==0) and (resultado2==0)) and (resultado3==0)):
print('O seu número é divisivel por 2,3 e 5')
if (resultado1>0):
print('O seu número não passou no teste')
elif (resultado2>0):
pr... |
d289d24ab9aee8fe7b75a91d8282d06f9e5a5740 | VitorSchweighofer/exertec | /Exercicio4/exercicio 4/exe6.py | 531 | 4.15625 | 4 | numero1 = int(input('Digite o numero inferior aqui: '))
numero2 = int(input("Digite o numero superior aqui: "))
divisores = 0
if (numero1>numero2):
print('O suposto limite inferior está maior que o superior')
for divisor in range(numero1, numero2+1):
if (divisor == 2):
print('2')
if (divisor == 3):
prin... |
c62ece6985614df8d2fbb951a47e3985d12eb91e | stefaluc/algorithms | /googlejap/deadends.py | 2,430 | 4.0625 | 4 | #!/usr/bin/python
maze = [] # changes on each test case
visited = []
def isDeadEnd(row, col, pos):
global maze
if pos == 'left':
return maze[row+1][col] == '#' and maze[row][col-1] == '#' and maze[row-1][col] == '#'
elif pos == 'right':
return maze[row+1][col] == '#' and maze[row][col+1] ==... |
0a73c3b5eebf85900db6e67a416d28a83240b2ad | stefaluc/algorithms | /permutations.py | 322 | 3.6875 | 4 | #!/usr/bin/python
def permutations(nums):
if len(nums) == 0:
return []
if len(nums) == 1:
return [nums]
perms = []
for idx, num in enumerate(nums):
for p in permutations(nums[:idx] + nums[idx+1:]):
perms.append([num] + p)
return perms
print permutations([1,2,3]... |
96cdc50991194597fc842120f64e263de10307ce | stuqdog/PE-AOC | /aoc3b.py | 1,435 | 3.84375 | 4 | from sys import argv
script, test = argv
good_tri = 0
bad_tri = 0
x = 0
triangle_1 = []
triangle_2 = []
triangle_3 = []
limit = 0
with open(test) as f:
limit_upper = len(f.readlines()) / 3
with open(test) as f:
# Opportunity for learning. I was able to limit the number of
# iterations because I knew the... |
dc612d30d76e6e0fff4bfb09fe6b0882b7ca226f | stuqdog/PE-AOC | /pe73.py | 537 | 3.546875 | 4 | primes = [2]
fractions = 0
for x in range(3, 12001, 2):
if all(x % i != 0 for i in primes):
primes.append(x)
for x in range(1, 4000):
prime_divisors = [i for i in primes if x % i == 0]
for y in range(x * 2 + 1, x * 3):
if all(y % i != 0 for i in prime_divisors):
fractions += 1
f... |
ff3333e0f84eb4bb5e5497f953d3d6a946bba1a3 | stuqdog/PE-AOC | /pe14.py | 564 | 3.53125 | 4 | solution_chain = []
solution = 0
for x in xrange(1, 1000000):
print x
chain_length = []
test_num = x
while test_num != 1:
if test_num % 2 == 0:
test_num /= 2
chain_length.append(test_num)
else:
test_num = test_num * 3 + 1
chain_length.appe... |
654471ee952fc270d0e88e90472e03edf5a40e0f | stuqdog/PE-AOC | /aoc9b.py | 1,793 | 3.5625 | 4 | import string
raw = ""
mode = "add"
length_or_size = "length"
length, size = "", ""
solution = 0
multiplier = 1
buffer_dict = {}
dict_delete = []
# create a string of the text, so we can read it char by char.
with open("aoc9.txt") as f:
for line in f:
raw += line
for c in raw:
# this checks if the durat... |
ed83e78864f10bcf36911d09e858ca7f80d9ab9e | Transpoze/Python-Applications | /Yatzy_game/defs.py | 9,708 | 3.96875 | 4 | # coding: latin1
# Program (Yatzy™ Protocol) written by: ADDI DJIKIC (2013/2014)
# Addi 2013 KTH (Royal Institute of Technology)
# addi@kth.se
#-----------Functions------------#
import sys
import random
import os
from dice import *
from classes import *
def show_welcomescreen():
"""Welcom... |
c2b81a6a11d3fbfe51412f588c74fb7c7b88f9dd | lennonkc/311605182_wc.exe | /data/test.py | 171 | 3.59375 | 4 | import sys
import os
file = open("1.txt", "r+")
str = file.read()
print(str)
charN = len(str)
print(charN)
for i in str:
if (str == ' ' or str == '\n'):
print(i)
|
6bfbcf1ee60a618aac10f662bfbbca698f1eb8d4 | Likelion-Algorithm/AlgoStudy | /큐/프린터큐/주현.py | 1,860 | 3.71875 | 4 | class PrintQueue:
def __init__(self,docQty,docLoc,importance):
self.docQty = docQty
self.docLoc = docLoc
self.importance = importance
self.order=0
self.front=0
self.rear=len(self.importance)
def getOrder(self):
while 1 :
while self.im... |
789e73d76d11099a8af2d50c68c699ebffcf40a5 | Likelion-Algorithm/AlgoStudy | /재귀/피보나치/주현.py | 280 | 3.6875 | 4 | def fibo(n):
if(n==0):
return 0
elif (n==1):
return 1
else:
return fibo(n-1)+fibo(n-2)
n=int(input())
print(fibo(n))
'''문제만든놈이 0번째부터 시작해서 살짝 헷갈렸다. 뇌가 컴퓨터로
되어있는 놈인 것 같다.''' |
741372b06dd2c1a06c6ca71101cfb9b8bbf180b6 | Likelion-Algorithm/AlgoStudy | /큐/회전큐/주현.py | 1,854 | 3.703125 | 4 | def dequeue(queue):
queue.append(queue.pop(0))
#실제 dequeue동작은 첫 원소를 없애는 것만을 뜻하지만 편의상 꼬리에 붙이는 동작을 포함했다.
def reverseDequeue(queue):
temp = queue.pop()
queue.insert(0,temp)
#마찬가지로 실제 dequeue와는 반대방향으로 동작한다. 순환큐에서만 가능한 듯 하다.
qsize, num = map(int, input().split()) #문제에서 queue의 크기를 제시해 주는데, 필... |
f605e20c9451df9a2f4bc4cf476006b232cb7662 | Likelion-Algorithm/AlgoStudy | /티어 별 문제/실버2/베르트랑 공준/주현.py | 932 | 3.6875 | 4 | def isPrime(n):
if n>1:
for i in range(2,n):
if n%i==0:
return False
return True
else:
return False
'''
def Prime(n):
answer = 0
for i in range(n+1 , n*2+1):
if isPrime(i) == True:
answer+=1
return answer
'''
#원시적인 소수판별
def ... |
eca632aacc12949b452f80159f722e8eee861cd3 | phoenixqm/OpenCV-learn | /python-image/take_akaze.py | 671 | 3.515625 | 4 | # import the necessary packages
from __future__ import print_function
import cv2
# load the image and convert it to grayscale
image = cv2.imread("jurassic_world.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Original", image)
# initialize the AKAZE descriptor, then detect keypoints and extr... |
f8ac9454b1333d1fce5f4f43c2d3b54731b979b7 | ArthurkaX/W3SCHOOL-learning | /Python basic P1/Ex_3.py | 286 | 4.40625 | 4 | # Write a Python program to display the current date and time
import datetime
print('first variant:')
print('current date & time is:')
print(datetime.datetime.now())
now = datetime.datetime.now
print('second variant:')
print('{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
|
d5fac45dfae4e162546dd53c4a2b3bd154bcc4a3 | ArthurkaX/W3SCHOOL-learning | /Python basic P1/Ex_1.py | 514 | 4.25 | 4 | # Write a Python program to print the following string in a specific format
some_txt = 'Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are'
x = 0
for a in some_txt:
if a.isupper() == True and a ... |
bd63612ea08714f3dae8021283a09d2f5520b422 | jamesluttringer2019/lambdata | /lambdata_davidvollendroff/df_utils.py | 559 | 3.6875 | 4 | """
Utility functions for working with DataFrames
"""
import pandas
import numpy as np
TEST_DF = pandas.DataFrame([1,2,3])
class O:
"""
A square shaped block for my PyTetris game.
"""
def __init__(self):
self.type = "O"
self.color = (255, 255, 0)
mold = np.zeros([24, 10]) # fr... |
b3a349fd4d578f3a7e6aec9ae8dc87083fb0633f | virnarula/FlappyBirdAi | /game.py | 4,956 | 3.6875 | 4 | import pygame
import random
import math
# Size of Game
WINDOW_HEIGHT = 800
WINDOW_WIDTH = int(WINDOW_HEIGHT / 1.5)
# Pipes
NUM_PIPES = 3
PIPE_GAP = 75
PIPE_DISTANCE = int(WINDOW_WIDTH * 0.6)
PIPE_WIDTH = int(WINDOW_WIDTH / 6)
pipeX = []
pipeOffset = []
pipeVelocity = 1
bottomPipes = []
topPipes = []
# Size of bird
B... |
67af0b7fb383567e3dd4e87bedcfb440d7dbbb56 | aniket1004/Python | /Assignment1_8.py | 197 | 3.765625 | 4 | def Pattern(no):
if no<0:
no=-no;
i=0;
while (i<no):
print ("*",end=' '),
i=i+1;
def main():
print ("Enter number:");
num=input();
Pattern(int(num));
if __name__=="__main__":
main(); |
01f2fcab759bdcfdf121c874cdac06fef5264ebd | aniket1004/Python | /Assignment2_4.py | 290 | 4 | 4 | def SumFactor(no):
if no<0:
no=-no;
sum=0;
for i in range(1,no):
if no%i==0:
sum=sum+i;
return sum;
def main():
print ("Enter the number: ");
num=int(input());
ans=SumFactor(num);
print ("Sum of factors of number is ",ans);
if __name__=="__main__":
main(); |
10e474b6319bee3b3174c000e17afc7c49a43d33 | divakarsenthilvel/Divakar_files_ | /lists.py | 2,355 | 4 | 4 | # non mutable items
# name = "Divakar"
# another_name = name
#
# print(id(name))
# print(id(another_name))
# name = name + " priya"
# print()
# print(id(name))
# print(id(another_name))
# number = 3.1415
# another_number = number
#
# print(id(number))
# print(id(another_number))
# number = number + 1.0
# print()
# pri... |
3cb5bbf8f1cbae09611372ac56ca1503bb3ba94b | maurimaldonado89/Taller_python | /Python/tema3_2 subplot.py | 555 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 25 11:40:16 2021
@author: L01268185
"""
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 2)
plt.grid(color='red',linestyle='--',linewidth=0.2)
plt.plot(x,y)
plt.title("... |
489f0b3cbf1ecb05689b0fbf3ab71a7777a09485 | maurimaldonado89/Taller_python | /Python/tema3_7 excel.py | 385 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 25 13:38:33 2021
@author: L01268185
"""
import pandas as pd
import matplotlib.pyplot as plt
archivo='fortunas.xlsx'
info=pd.read_excel(archivo)
#Subtabla con algunas columas
valores =info[['Nombre','Fortuna',]]
ax=valores.plot.bar(x='Nombre',y='Fortu... |
50426db78b533ce033a059f1157c9f0d44123146 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_9_Classes/Dog.py | 800 | 4.21875 | 4 | class Dog(object):
"""A simple attempt to model a dog."""
def __init__(self,name,age):
"""Initialize name and age attribute"""
self.name=name
self.age=age
def sit(self):
"""Simulate a dog sitting in response to a command"""
print(self.name.title()+" is now sitting.")... |
91b3c0eace34899e1e0f2c1e40853ace87382362 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_3_Intoducing_Lists/bicyclesIntroToLists.py | 1,152 | 4.625 | 5 | #In Python, square brackets indicate a list, and individual elements in the list are separated by commas.
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
#Because this isnt the output you want your users to see, lets learn how to access the individual items in a list.
#To access an ele- ment... |
0ba59210ae47c36fd6abeab0670ead59fef062f7 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_3_Intoducing_Lists/untitled folder/3-3.py | 462 | 4.46875 | 4 | # 3-3. Your Own List: Think of your favorite mode of
# transportation, such as a motorcycle or a car, and
# make a list that stores several examples. Use your
# list to print a series of statements about these items,
# such as “I would like to own a Honda motorcycle.”
cars = ['audi' , 'bmw' , 'mercedes']
print("I wou... |
9186fd92057fe70515f32741ae8cb9d0b2ec824c | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_9_Classes/practice2/9-7.Admin.py | 1,266 | 4.03125 | 4 | class User():
"""Modelling a user"""
def __init__(self, first, last,age,gender):
self.first_name = first
self.age = age
self.last_name = last
self.gender = gender
def describe_user(self):
print("Here's some information about the user: ")
print(
"\... |
25765f81a8f389954b389a504b1ea642950b8865 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_4_Working_With_Lists/4-1.Pizzas.py | 202 | 3.78125 | 4 | pizzas = ['margherita','peri-peri','golden delight']
for pizza in pizzas:
print(pizza.title())
for pizza in pizzas:
print("I love " + pizza.title() + " pizza!")
print("I really love pizza!")
|
d88e288cffdaf538374ae33bc2f91b3410b3b143 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_9_Classes/electric_car.py | 2,219 | 4.46875 | 4 | class Car(object):
"""A simple attempt to represent a car"""
def __init__(self,make,model,year):
"""Initialize attributes to describe a car"""
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_descriptive_name(self):
"""Return a ... |
9384dd3bcac1ad6967f6f0b1d7c5b46c01702123 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_8_Functions/8-4.LargeShirts.py | 971 | 3.796875 | 4 | def make_shirt(size,printed_text):
print("So let me confirm this, You want a:\n\t"+size+" size T-shirt with\n\t"+printed_text+" written on it.")
#postional argument :
make_shirt('L','"Sorry Ladies, I am in the Nights Watch"')
#keyword argument
quote="Sorry Ladies, I'm in the Night's Watch"
make_shirt(size='Snow',pr... |
d11e007939ad611f6f34dbf43ef9949442310658 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_7_User_Input_And_While_Loop/Practice2/4.rollercoaster.py | 209 | 4.15625 | 4 | height = raw_input("How tall are you , in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enought to ride!")
else:
print("You will be able to ride when you're a little older.")
|
68b3d1a63e3df0f1f75e4fc83af3a3dd2b29f093 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_3_Intoducing_Lists/untitled folder/3-2Greetings.py | 477 | 4.25 | 4 | # 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just printing each persons name,
# print a message to them. The text of each message should be the same, but each message should be personalized
# with the persons name.
friend_list=['manan','samarth','rohan','rishi']
print ("Hello, "+frien... |
eb2f499b4d1cf367dcf6c16d5935dc1907e8739d | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_6_Dictionaries/6-3.Glossary.py | 549 | 3.921875 | 4 | glossary = {
'print':'Prints the data struture followed after the print statement.',
'range':'Creates a list of numbers starting from the first' +
'number till the last number - 1.\nYou can also add interval.',
'sort()':'This method sorts the list in alphabetical order , permanently.',
'del':'Delete... |
3389a5cd1051d2edcf6125b7adb4452d591f0726 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_9_Classes/practice2/9-6.IceCreamStand.py | 1,332 | 4.21875 | 4 | class Restaurant():
"""An attempt to model a restaurant"""
def __init__(self,restaurant_name,cuisine_type):
"""Initializing name and age attributes"""
self.name = restaurant_name
self.cuisine = cuisine_type
def describe_restaurant(self):
# Describes the restaurant name... |
40f1d80db00c4e5b45fb1b135543a9076413a600 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_2_Variables_And_Simple_Data_Types/6.apostrophe.py | 707 | 3.71875 | 4 | message="One of Python's strengths is its diverse community."
print (message)
#The apostrophe appears inside a set of double quotes,
#so the Python interpreter has no trouble reading the string correctly:
#However, if you use single quotes, Python can’t identify where the string should end:
message='One of Python's str... |
53b9fdf3ee7e05c86ff54570004d50f40db3f62c | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_8_Functions/practice2/3.pets.py | 408 | 3.71875 | 4 | def describe_pet(animal_type,pet_name):
"""Display information about a pet"""
print("I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('dog','lexus')
#Calling function multiple times is an efficeint way to work.
# Anytime you want to describe... |
9a707f3c487622e2c8caa16d2d8ca8c4d7507911 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_8_Functions/practice2/16.profile.py | 989 | 4.53125 | 5 | # Sometimes you'll want to accept an arbitary number of
# argument but you won't know ahead of time
# what kind of information will be passed to the
# function.
# Write a function that accepts as many key-value pairs as the
# calling statement provides.
# Example : Building user profiles.
# You're sure that you'll ge... |
d41dee2ed6026e6f69c9dbe2f92ab2f2a7e05b03 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_2_Variables_And_Simple_Data_Types/2-4NameCases.py | 218 | 4.09375 | 4 | # 2-4. Name Cases: Store a person’s name in a variable,
# and then print that per- son’s name in lowercase, uppercase,
# and titlecase.
name = "rishabh"
print(name.title())
print(name.upper())
print(name.lower())
|
c63d7c22a6937f8aaa1576e9f6baca9a99352a88 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_8_Functions/petsPassingArguments.py | 914 | 3.84375 | 4 | #Postional Arguments:
def describe_pet(animal_type,pet_name):
"""Display information about a pet"""
print("\nI have a "+animal_type+".")
print("\tMy "+animal_type+"'s name is "+pet_name+".")
describe_pet('Labrador','Lexus')
# See we entered the arguments in the order of the parameters.
# labrador correspon... |
58675d96e526b7454d846ed65032e236e757ae01 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_9_Classes/practice2/9-12.Privileges_Admin.py | 770 | 3.9375 | 4 | from User912 import User
class Privileges():
"""Models the privileges of an admin"""
def __init__(self, privileges):
# Initializing attributes to describe privileges
self.privileges = privileges
def show_privileges(self):
print("\nThe admin enjoys the following privileges: ")
... |
7b3a2082ef0f5fca03e39cd25891cc9ba0320bde | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_7_User_Input_And_While_Loop/Practice2/greeter.py | 270 | 4.03125 | 4 | # name = raw_input("Please enter your name. ")
# print("Hello " + name.title() + "!")
prompt = "If you tell us who you are , we can personlaize the message you see."
prompt += "\nWhat is your first name? "
name = raw_input(prompt)
print("Hello " +name.title() + "!")
|
c9349dd22148f7f878bb1be59820cc8e1b6ddcd5 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_10_File_And_Exceptions/10-6.Addition.py | 1,950 | 4.15625 | 4 | while True:
try:
first_number = raw_input("Give me two numbers and i will add them." +
"\nEnter 'quit' to quit program anytime."+
"\nFirst Number: ")
if first_number == 'quit':
break
else:
first_number = int(first_number)
second_number ... |
f2d74a5bea40e74454c884bfefb8ec99d9b9d276 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_5_If_Statements/banned_users_CheckWhetherAValueIsInAList.py | 986 | 4.125 | 4 | print "Checking whether a value is not in a list "
# Other times, its important to know if a value does not appear in a list.
# You can use the keyword not in this situation. For example, consider a
# list of users who are banned from commenting in a forum. You can check whether
# a user has been banned before allo... |
110817b78b705099ff8ae29a25d656ce2d91b8e1 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_10_File_And_Exceptions/greet_user.py | 209 | 3.5 | 4 | import json
file_name = 'username.json'
with open(file_name) as file_object:
username = json.load(file_object) # read the information stored in username.json
print("Welcome back, " + username + "!")
|
10653cc7bee25ed7a8eb94889d5c21ad344c4579 | itm-dsc-tap-2020-1/examen-1-interfaz-grafica-con-tkinter-Victoria-R | /Examen.py | 2,288 | 3.796875 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import messagebox as mBox
from tkinter import Menu
ventana = tk.Tk()
ventana.title ("EDUCACIÓN FÍSICA")
#PREGUNTA 1
label = ttk.Label (ventana, text = "1) Ecriba cual es su deporte favorito. Justifique su respuesta").grid(colum... |
9ca777ae32cc7d0e706454e7a387b76bcfa13744 | CupOfGeo/Image-Processing | /Class/IntensityTransforms/logTransform.py | 2,282 | 3.59375 | 4 | """
Joshua Stough
DIP
This example looks at an image with a very dark area, and
performs a log transform to increase contrast in the dark and
compressing the light. Then, we create an image that either
uses the log transformed intensities for the dark area, or
the original intensity for the bright.
"""
"""
This examp... |
232aadb30d4c6c294a3f3e928da4809beea039ba | LijaAlex12/oops | /inheritance1.py | 444 | 3.59375 | 4 | # superclass
# multilevel inheritance
class A:
def feature1(self):
print('feature1')
def feature2(self):
print('feature2')
# subclass
class B(A):
def feature3(self):
print('feature3')
def feature4(self):
print('feature4')
class C(B):
def feature5(self):
p... |
f70251162dc856f5892ae49ef77945845cc421b9 | JakeClauson/PythonHW | /PyHomework.py | 2,364 | 4.09375 | 4 | import os
import csv
#create variables for what im going to display/change
months = 0
gross = 0
monthlist = []
profitlist = []
changelist = []
#C:\Users\Office 1\Desktop\PythonStuff\UofA-PHX-DATA-PT-11-2019-U-C-master\03-Python\Homework\Instructions
# create a path to the file
csvpath = os.path.join('..',... |
f73c56d0da0fda218f664638f2f0603de050d14a | EFulmer/dragon_book | /chapter3/ex_3_3_5.py | 1,101 | 3.953125 | 4 | # Exercise 3.3.5:
# Write regular definitions for the following languages:
import re
import string
# a) All strings of lowercase letters that contain the five vowels in
# order.
# In other words, any number (including 0) of consonants, then a,
# then any number of consonants, then e, and so on and so forth...
con... |
762f2f99eeadc44b8b231a703b5a1c5cff960baa | TetyanaLi/hillel_python | /LEVEL_1/LESSON_5/lesson5-3v.2.py | 218 | 3.84375 | 4 | katet_a = float(input('Введите длину:'))
katet_b = float(input('Введите ширину:'))
if katet_a != katet_b:
print (katet_a * katet_b * 0.5)
elif katet_a == katet_b:
print (katet_a ** 2) |
5ccb5ca308e3cc63527b4858e25f4cd26215c34d | TetyanaLi/hillel_python | /LEVEL_1/KLASS/LESSON5/klass5-2.py | 270 | 3.59375 | 4 | some_list = []
some_text = ''
some_dict = {}
some_list.append('1')
some_list[0] = 20
some_text = '20'
some_list[0] = some_text
some_dict[some_text] = some_list
#print(some_list, some_text, some_dict,sep='/')
some_list2 = some_list
some_list2[0] = 30
print(some_dict)
|
d41a8dd0a5d9aa2cd89cfc6d11ee9c75b1c31dbb | TetyanaLi/hillel_python | /LEVEL_1/LESSON_4/lesson4-1.py | 782 | 4.21875 | 4 | #1. В первый день спортсмен пробежал `x` километров,
# а затем он каждый день увеличивал пробег на 10% от предыдущего значения.
# По данному числу `y` определите номер дня, на который пробег спортсмена составит не менее `y` километров.
#Программа получает на вход числа `x` и `y` и должна вывести одно число - номер дня.... |
5beb2bb5627236220420ff6078a2c7d299b9b140 | TetyanaLi/hillel_python | /LEVEL_1/LESSON_11/lesson 11-3.py | 1,340 | 4.46875 | 4 | #3. Написать функцию которая вернет самое длинное слово в строке:
# longest_word("What makes a good man") -> makes
#x = input('Введите действительное число с двумя знаками после десятичной точки: ')
some_list = 'What makes a good man'
def longest_word(some_list):
elements = some_list.split()
new_list = []
... |
62f565fd3e45367c0d04826da9ee1bc7400e7c95 | TetyanaLi/hillel_python | /LEVEL_1/LESSON_11/lesson 11-2.py | 381 | 3.96875 | 4 | #2. Написать функцию которая будет частично скрывать e-mail, пример:
#hide_email(somebody_email@gmail.com) -> em***@**il.com
def hide_email(email):
email = '@'.join([email.replace(email[email.find('@') - 3:], '***'),
email.replace(email[:len(email) - email.find('@') + 2], '**')])
retur... |
13be4e41d3e199bc6995e26a9a012a598f8c472c | xuzengming123/spjtest | /day3/2守护线程.py | 1,522 | 3.59375 | 4 |
import time,threading
# def foo(something,num):
# for i in range(num):
# print('CPU切换执行:',something)
# time.sleep(1)
# #创建一个线程
# t1 = threading.Thread(target=foo,args=('注册账号',10))
# #再创建一个线程
# t2 = threading.Thread(target=foo,args=('登录账号',10))
#
# #启动线程
# t1.start()
'''阻塞父线程继续执行'''
# t1.join()
# ... |
0bf902b62260bc6f9738f1210f197c4e216f7ead | mazsoltani/Python_Assignment_6 | /main.py | 5,551 | 3.625 | 4 | from pyfiglet import Figlet
f= Figlet(font="standard")
print(f.renderText( "Soltani Store."))
my_list=[]
myfile = open("database.txt","r")
data = myfile.read().lower().split("\n")
for i in range(len(data)):
product_info = data[i].split(',')
my_dic = {}
my_dic['id']= product_info[0]
my_dic['nam... |
f01fbc279e48816048409a693757f8b97567e970 | lxu213/edX-6.00-python | /ps1/ps1b.py | 290 | 3.96875 | 4 | # june 25, 2014
# ps1: counting bobs
# script prints the number of times the string 'bob occurs in s
s = 'azcbobobegghakl'
total = 0
for n in range(0,len(s)-2):
if s[n] == 'b' and s[n+1] == 'o' and s[n+2] == 'b':
total+=1
print('Number of times bob occurs is: ' + str(total)) |
af1f9c9adbde51ae220102b6f3e276ee2a7f167d | choihyuunmin/python3 | /OOP.py | 1,499 | 3.8125 | 4 | import email
class Student(object):
'''
Student Class
Author : CHOI
DATE : 2021.05.24
'''
# 클래스 변수
student_count = 0
def __init__(self, name, number, grade, details, email=None):
# 인스턴스 변수
self._name = name
self._number = number
self._grade = g... |
c8a2330bd9f0412cfd073399bb8f59d5baa03d0b | CarlosVF22/error-handling-lambda-python | /dictonary_comprehensions.py | 368 | 3.984375 | 4 | # crear un dictionario en donde las llaves sean los primeros numeros y valores los numeros elevados al cubo
import math
def run():
my_dict = {i: i**3 for i in range(1,101) if i % 3 != 0} # dict_comprehensions
print(my_dict)
my_dict_challenge = {i:math.sqrt(i) for i in range(1, 1000)}
print(my_dict_c... |
7ea24d0c3735afd6c93953437e571f95041495c4 | brentsamaha/super-enigma | /fullcode.py | 2,971 | 3.828125 | 4 |
#To start, we imported the packages we will use for the project.
import requests
from requests import get
from bs4 import BeautifulSoup
#We assign the variable html to retrieve the html data from the IMDB page that has the information we want.
html = requests.get('https://www.imdb.com/search/title/?count=100&groups=o... |
d4be6860c91ea5c24bda04fe12806f4e9669df12 | acdlee/PacmanAI | /proj1-search-python3/help/cat.py | 245 | 3.578125 | 4 | from util import Stack as s, Queue as q
st = s()
qu = q()
st.push(8)
st.push(10)
qu.push(8)
qu.push(10)
print("This is st: " + str(st))
print("This is qu: " + str(qu))
print("st.pop(): " + str(st.pop()))
print("qu.pop(): " + str(qu.pop()))
|
c2adad59e25b5e2491b1c7a022d766cf11cb82c6 | ivaylokanov/Python | /03_lists/10_square_numbers.py | 239 | 3.640625 | 4 | elements = list(map(int, input().split()))
square_elements = [item for item in elements if (item > 0) and (item ** (1 / 2) == int(item ** (1 / 2)))]
square_elements.sort(reverse=True)
print(" ".join(str(item) for item in square_elements))
|
49816d41bf27f09da40b2fe511825968f9b85d91 | ivaylokanov/Python | /03_lists/08_append_lists.py | 195 | 3.65625 | 4 | sequence = input()
tidy_sequence = sequence.split('|')
tidy_sequence.reverse()
tidy_sequence = [item.split() for item in tidy_sequence]
[print(' '.join(item), end=' ') for item in tidy_sequence]
|
4e2bec0e05a4e367a72779bd8f074a253db69b5f | ivaylokanov/Python | /07_strings_and_text/02_count_substrings.py | 251 | 3.734375 | 4 | text = input().lower()
find_substring = input().lower()
counter = 0
index = 0
while True:
if text.find(find_substring, index) == -1:
break
else:
counter += 1
index = text.find(find_substring, index) + 1
print(counter)
|
eb0686745cffe29b9cb6b7fef418eb0230a46baf | ivaylokanov/Python | /02_functions_and_debuging/04_draw_a_filled_square.py | 276 | 3.9375 | 4 | def print_external_line(n):
print('-' * 2 * n)
def print_middle_line(n):
for i in range(n-2):
print('-', end='')
print('\\/' * (n - 1), end='')
print('-')
n = int(input())
print_external_line(n)
print_middle_line(n)
print_external_line(n)
|
bf85d29ba79123c7f81054ff2e91131dcbde0892 | ivaylokanov/Python | /04_dictionaries_lambdas_functional_programming/05_mixed_phones.py | 440 | 3.671875 | 4 | import collections
input_line = input()
dict_ref = {}
while input_line != "Over":
splited_line = input_line.split(" : ")
if splited_line[1].isnumeric():
dict_ref[splited_line[0]] = splited_line[1]
else:
dict_ref[splited_line[1]] = splited_line[0]
input_line = input()
sorted_dict_ref = c... |
a994791a052a4abfb6a9a54e89d6c88d58224e4b | herzenuni/herzenuni-sem3-assignment4-191217-AnnGoga | /treemin.py | 713 | 4.15625 | 4 | def minimum_three_mpy(*args):
if len(args) < 3:
print("minimum_three_mpy : 3 arguments minimum")
return None
try:
mpy = args[0] * args[1] * args[2]
counter = 0
for i in range(len(args)):
for j in range(i + 1, len(args)):
for k in range(j + 1, len(args)):
counter += 1
new_mpy = ... |
09b25a486cac5c27830c3bcf6bb7215274d6232a | GabrielReira/Python-Exercises | /11 - Analisador de nome.py | 584 | 3.90625 | 4 | nome = str(input('Digite seu nome completo: ')).strip()
# Quantidade de letras.
print('Seu nome completo possui {} letras.' .format(len(nome) - nome.count(' ')))
# Primeiro nome e quantidade de letras.
s = nome.split()
print(f'Seu primeiro nome é: {s[0]}')
print('Seu primeiro nome possui {} letras.' .format(nome.find... |
1336ec11ba9d43672a6869fb5c5fc562fa4b8225 | GabrielReira/Python-Exercises | /53 - Progressão aritmética v.2.py | 1,147 | 3.90625 | 4 | # VERSÃO 2.
def arithmetic_prog(first_term, last_term, common_diff):
# Evitar que o programa entre em loop.
if common_diff == 0:
print('Razão inválida.')
exit(0)
# Razão positiva.
if first_term <= last_term:
# Evitar que o programa entre em loop.
if common_diff < 0:
... |
be463ae437ff7e7bd353a8e446de129b9626e27c | GabrielReira/Python-Exercises | /64 - Banco de dados.py | 2,499 | 4.03125 | 4 | def creating_file(file):
try: # Tentar abrir arquivo de texto
file_name = open(file, 'rt')
except FileNotFoundError: # Criar arquivo de texto caso não exista
file_name = open(file, 'wt+')
except:
print('Houve um erro na criação do arquivo.')
else:
f... |
6f8dfc8a2973f345d6558ae85303c9613b5a5911 | GabrielReira/Python-Exercises | /07 - Seno, cosseno e tangente.py | 250 | 3.953125 | 4 | import math
g = int(input('Digite um ângulo em graus: '))
# Precisa transformar o ângulo para radianos.
r = math.radians(g)
print(f'''O seno de {g} é {math.sin(r):.2f}.
O seu cosseno é {math.cos(r):.2f}.
E sua tangente é {math.tan(r):.2f}.''') |
6e4e764da06516d76a4a4596995109c8c222da54 | GabrielReira/Python-Exercises | /05 - Reajuste salarial.py | 207 | 3.5 | 4 | s = float(input('Digite o salário atual: R$'))
r = float(input('Digite a porcentagem de reajuste: '))
novo = s + s * (r / 100)
print(f'Com o reajuste de {r}%, o funcionário passa a receber R${novo:.2f}.') |
29ef1faff85d9298082d0e4eccad16eaabe34aa3 | GabrielReira/Python-Exercises | /12 - Adivinhe o número v.1.py | 285 | 4 | 4 | # VERSÃO 1.
from random import randint
print('\nO computador escolherá um número entre 0 e 5.')
n = randint(0,5)
u = int(input('Qual número você acha que ele escolheu? '))
print('Você acertou!') if u==n else print('Você errou.')
print(f'O número que ele escolheu foi {n}.') |
416355b3847e257021e68fc4448aff31010307e8 | GabrielReira/Python-Exercises | /26 - Analisando pesos.py | 435 | 4 | 4 | heaviest_person = 0
lightest_person = 999
total = int(input('Qual o número de pessoas? '))
for x in range(total):
weight = float(input(f'Peso da {x + 1}ª pessoa em kg: '))
if weight > heaviest_person:
heaviest_person = weight
if weight < lightest_person:
lightest_person = weight
print(f'... |
aae8f905c66d6d76f3413fe0c3c93baca99e2acb | GabrielReira/Python-Exercises | /42 - Números ordenados.py | 575 | 4.125 | 4 | all_values = []
n = int(input('Quantos valores você deseja digitar? '))
for i in range(n):
value = int(input('Digite um valor: '))
# Se for o primeiro item ou se for maior que o último valor.
if (i == 0) or (value > all_values[-1]):
all_values.append(value)
# Se estiver entre os itens do... |
eece15ae00c39e9e741fcb76b33a6bb0f577ad7b | sanadi-rohit/hanga | /binarytree.py | 1,093 | 4.09375 | 4 | #python code for the working of a tree
#gives sorted aray as output
class node:
def __init__(self,data=None,leftnode=None,rightnode=None):
self.data=data
self.leftnode=leftnode
self.rightnode=rightnode
def addnode(self,data):
if data<=self.data:
if self.leftnode==None... |
3e8a10498f15789ba5572234cff7ad4ed421b494 | augustinechang1/leetcode | /easy/longest_commin_prefix.py | 508 | 4 | 4 | # Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
a = ["flower","flow","flight"]
def longestcommonprefix(a):
shortest = min(a, key=len)
for x, y in enumerate(shortest):
for other in a:
if oth... |
b4d99ce4d371227a3af6654d20ab23724906f553 | cobrastarfunkel/ceh | /bas64/assignment4_b64.py | 5,668 | 3.515625 | 4 | #!/usr/bin/python
"""
@author: Ian Cobia
The main program that drives the encode.py and decode.py
classes. Creates the json file those two classes use to covert
to and from base64. This file also handles the hashing
of the Base64 encoded Strings.
file_name: assignment4_b64.py
Must have the encode.py and decode.py ... |
49d3ec25bb9b4f9f95b52358e907f599804bf9de | jonny21099/PianoStudioManager | /PianoProgram/Add_student.py | 974 | 3.75 | 4 | import os
from datetime import date
def Add_student(c, conn):
student_name = input("What is the student's name?\n")
lesson_day = input("On what days do you teach this student(e.g. Mon)?\n")
lesson_time = input("At what time do you teach this student?\n")
lesson_length = input("How long is each lesson?\n")
lesson... |
b5ff410dfc0a7f64f5ffff4eddfd453050d525b9 | 0x420x42Rodriguez/100-Days-of-Code | /Day 5/AddingEvenNumbers.py | 178 | 3.96875 | 4 | # Add all even numbers together between 1 and 100
accumulator = 0
for number in range(1, 101):
if number % 2 == 0:
accumulator += number
print(accumulator) |
35adb2b17002fca26b19cf9b8b7c05c7a5862f44 | 0x420x42Rodriguez/100-Days-of-Code | /Day 4/RockPaperScissors.py | 1,506 | 4.375 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
... |
d6708bbc14361fd76eff6aad3066118eccfd9a99 | Jsbarcenas/SignalsLab | /src/lab3/myStat.py | 2,750 | 3.578125 | 4 | from math import sqrt
import matplotlib.pyplot as plt
import scipy.stats as stats
import statistics as st
import scipy.stats as ss
import statistics as sta
from scipy.stats import kurtosis as k
import math
import numpy as np
# // Kurtosis
def Kurtosis(lista):
n = mean = M2 = M3 = M4 = 0
for x in lista:
... |
7d900b9d8a49c9f3b4753b7c8effd72764ddbbf6 | sweenejp/learning-and-practice | /treehouse/python-beginner/monty_python_tickets.py | 1,349 | 4.15625 | 4 | SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
def calculate_price(number_of_tickets):
# $2 service charge per transaction
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining > 0:
print("There are only {} tickets remaining!\nBuy now to secure your spot for th... |
a2aaf42be3d7c64b9a2127fa309aa14a4f4e4c22 | sweenejp/learning-and-practice | /treehouse/python-beginner/functions.py | 354 | 3.734375 | 4 | def add_two_nums(num1, num2):
#print(num1, "+", num2, "=")
val = num1 + num2
print(val)
return val
add_two_nums(1, 1)
for butts in range(10):
print(butts)
# def hello_student(name):
# return "Hello {}".format(name)
# ^same result as above
def hello_student(name):
return "Hello " + name... |
8b69c22357ef25ddca9167989f2337674fe78784 | sweenejp/learning-and-practice | /practicepythondotorg/exercise_14.py | 692 | 4.1875 | 4 | # Write a program (function!) that takes a list and returns a new list that contains all the
# elements of the first list minus all the duplicates.
#
# Extras:
#
# Write two different functions to do this - one using a loop and constructing a list,
# and another using sets. Go back and do Exercise 5 using sets, and wri... |
cb066d54e563da61e1c97f7621ac4ac43c42e3e1 | sweenejp/learning-and-practice | /treehouse/python-beginner/team.py | 1,286 | 4.21875 | 4 | # TODO Create an empty list to maintain the player names
player_names = []
# TODO Ask the user if they'd like to add players to the list.
wants_to_add = input("Would you like to add a player to the team?\nYes/no: ")
# If the user answers "Yes", let them type in a name and add it to the list.
while wants_to_add.lower... |
f0986b73b6a7e47dd6cc57f2e09dc39164bdce4c | sweenejp/learning-and-practice | /practicepythondotorg/exercise_16.py | 657 | 3.828125 | 4 | # Write a password generator in Python. Be creative with how you generate passwords - strong
# passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The
# passwords should be random, generating a new password every time the user asks for a new
# password. Include your run-time code in a ma... |
28301a007b829871cd518834994588e9f088b53b | Kinosa777/Lits-Python | /convert_n_to_m.py | 1,377 | 4.21875 | 4 | def convert_n_to_m(x, n, m):
"""Converts a number in n-based system into a number in m-based system."""
def convert_n_to_dec(x):
"""Converts a n-based number into decimal.
No int(num, base) function for number conversion is used."""
if n == 10:
return x
elif n == 1:
... |
72bd705da8baee4c8062c70de89c7c0796ea3b97 | BradleyAHiggins/PyCalc | /lexer.py | 6,375 | 3.765625 | 4 | class Token:
opDict = {'+' : "ADD", '-' : "SUB", '/' : "DIV", '*' : "MULT", '^' : "EXP"}
def __init__(self):
return self
def isInt(express):
"""isInt accepts a string, express, and tests whether express is an integer, returning True or False accordingly"""
intString = "0123456789"
... |
737e69d1e746e3157fca47f40da17f5a2ec99387 | leisurexi/python-study | /15/obcopy.py | 2,777 | 3.9375 | 4 | # author: leisurexi
# date: 2021-01-17 20:08
# Python 对象的比较和拷贝
import copy
# 浅拷贝,是指重新分配一块内存,创建一个新的对象,里面的元素是原对象中子对象的引用。因此,如果原对象中的元素不可变,那倒无所谓;但如果元素可变,浅拷贝通常会带来一些副作用
def shallow_copy():
l1 = [1, 2, 3]
l2 = list(l1)
l3 = l1[:]
print('=======================浅拷贝=======================')
print(l1 == l2)
... |
e8c48f782657d7761349fa5ecf6fcef3e0b589fc | leisurexi/python-study | /22/practice.py | 593 | 3.53125 | 4 | # author: leisurexi
# date: 2021/1/24
# file name: practice.py
# 计算0到给定元素的平方和(改为多进程版本)
import time
def cpu_bound(number):
print(sum(i * i for i in range(number)))
def calculate_sums(numbers):
for number in numbers:
cpu_bound(number)
def main():
start_time = time.perf_counter()
numbers = [... |
7298c7eca57f058c10682bcdfffb19a25c863293 | leisurexi/python-study | /03/listtuple.py | 1,697 | 4.125 | 4 | # author: leisurexi
# date: 2021-01-11 23:25
# 列表和元组示例,列表和元素都是一个可以放置任意数据类型的有序集合
# 列表是动态的,长度大小不固定,可以随意地添加、删除或者改变元素
lists = [1, 2, 3, "hello"]
lists[2] = 20
lists.append(5)
print(f'列表添加和修改元素后: {lists}')
lists.remove(1)
print(f'列表删除元素后: {lists}')
# -1 代表最后一个元素,-2 代表倒数第二个元素以此类推
print(f'列表负数索引: {lists[-1]}')
# 切片包前不包后
prin... |
235fdaa0a8994a442342fd0521db8ffaebbdbd10 | tohkev/Module-5-Hwk | /loopy_loops.py | 671 | 4.125 | 4 | if __name__ == '__main__':
pokemon = ('pikachu', 'charmander', 'bulbasaur')
print(pokemon[1])
starter1 = pokemon[0]
starter2 = pokemon[1]
starter3 = pokemon[2]
print(starter1, starter2, starter3)
name_tuple = tuple('Kevin')
print(name_tuple)
is_there_i = 'i' in name_tuple
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.