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 |
|---|---|---|---|---|---|---|
e4d1edac25f191fb36be749e4a6b0e103c1027d9 | erikac613/PythonCrashCourse | /8-4.py | 335 | 3.71875 | 4 | def make_shirt(shirt_size = 'large', shirt_text = "I love Python"):
"""Displays the size of a shirt and the message printed on the shirt"""
print("The shirt is a size " + shirt_size + " and bears the message " + shirt_text + ".")
make_shirt()
make_shirt(shirt_text = "Coding is Fun!")
make_shirt(shirt_siz... |
3e0a02bc09930fa93869e97e8fb8b45997f7384c | erikac613/PythonCrashCourse | /card_deck.py | 263 | 3.546875 | 4 | import itertools, random
deck = list(itertools.product(['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'], ['Hearts', 'Diamonds', 'Clubs', 'Spades']))
random.shuffle(deck)
print ("You got: ")
for i in range(5):
return [i][0], [i][1]
|
b5d546f21db9d7480efc802461ee42adfb376dc1 | erikac613/PythonCrashCourse | /10-4.py | 374 | 3.8125 | 4 | filename = 'why_program.txt'
with open(filename, 'a') as file_object:
prompt = "Why do you love programming? "
prompt += "\n(Please enter'quit' to exit.) "
while True:
reason_why = raw_input(prompt)
message = "\n" + reason_why
if reason_why == 'quit':
break
... |
de1fabcd7bcb47a114d21b7fc42aa5313aea339a | erikac613/PythonCrashCourse | /3-8.py | 367 | 3.90625 | 4 | locations = ['japan', 'scotland', 'england', 'new zealand', 'egypt']
#print(locations)
#print(sorted(locations))
#print(locations)
#print(sorted(locations, reverse = True))
#print(locations)
locations.reverse()
print(locations)
locations.reverse()
print(locations)
locations.sort()
print(locations)
loc... |
ae8899b2735de9b712b11e1e20f95afcd5008be2 | erikac613/PythonCrashCourse | /11-1.py | 483 | 4.15625 | 4 | from city_functions import city_country
print("Enter 'q' at any time to quit.")
while True:
city = raw_input("\nPlease enter the name of a city: ")
if city == 'q':
break
country = raw_input("Please enter the name of the country where that city is located: ")
if country == 'q':
... |
c99ce6589931fd25ceb804efc79cfa36000cc701 | carlosjrbk/Logica-de-Programa--o---IFPE | /lista_4/exercicio_1.py | 214 | 3.75 | 4 | t = 0
x = 1
for cont in range(1,16):
idade = int(input(f"{x} informe sua idade: "))
x += 1
if idade >= 18:
t += 1
print(f"A quantidade de pessoas com idade maior ou igual a 18 é de: {t}" )
|
6c94f305f5a475c26cd18fad516f12178edc8460 | carlosjrbk/Logica-de-Programa--o---IFPE | /lista_4/exercicio_2.py | 446 | 3.71875 | 4 | for cont in range (1,16):
nome = input("Informe seu nome: ")
valor = float(input("Informe o valor da Compra: "))
if valor < 1000:
total = valor - (valor * 0.1)
print( nome + " " "pagará " + str(total) + " por ter comprado a baixo de R$1000,00")
else:
valor > 1000
total = ... |
1be438434f7d6e0c101f381574f65d27b0a78340 | carlosjrbk/Logica-de-Programa--o---IFPE | /lista_4/exercicio_9.py | 346 | 4 | 4 | n = int(input("INSIRA O NUMERO DE TERMOS DA PA: "))
pt = int(input("INSIRA O 1° TERMO DA PA: "))
r = int(input("INSIRA A RAZÃO DA PA: "))
print("*"*40)
print("OS TERMOS DA PA SÃO")
calc = pt + ( n - 1 )*r
for i in range(pt, calc+r, r):
print(f'{i}',end='->')
soma = n * (pt + calc) // 2
print()
print(">A SOMA DOS TE... |
2c477655502b99e6eda8ad9e45fa8b67d6231d09 | carlosjrbk/Logica-de-Programa--o---IFPE | /Lista_3/exercicio_1.py | 176 | 3.875 | 4 | x = 1
valor = 0
while x <= 8:
v = int(input(" Digite o valor número %d: " % x))
valor = valor + v
x = x + 1
print("A média aritimetica é: %5.2f" % (valor//8)) |
cdd9e4d9fd2928c3105ad26faf020b1f11e73f14 | carlosjrbk/Logica-de-Programa--o---IFPE | /Lista_2/exercicio_8.py | 845 | 3.6875 | 4 | valor = int(input('SEM CONTAR OS CENTAVOS INFORME QUANTOS REAIS VOCE TEM: '))
total = valor
ced = 200
ced1 = 'Lobo guará'
totalced = 0
while True:
if total >= ced:
total -= ced
totalced += 1
else:
print(f'VOCE ESTA LEVANDO NO BOLSO {totalced} {ced1}')
if ced == 200:
... |
ed0e8417ca346dc35ec58c1843ed16a8708166d9 | carlosjrbk/Logica-de-Programa--o---IFPE | /lista_5/exercicio_2.py | 173 | 4.125 | 4 | valores = []
while True:
num = input("Digite um numero inteiro: ")
valores.append(num)
if num == " ":
valores.sort()
break
print(valores[::-1])
|
a26ca1ca0afc41454b7a3aceb0762c600fc1872a | woo1038/algorithm | /codeup/exam079.py | 82 | 3.5 | 4 | a = int(input())
b = 0
c = 0
while a > c:
b = b + 1
c = c + b
print(b)
|
859616a035c7d3d118a84f47b3314201180e3beb | fishpan1209/MortalityPrediction | /code/event_statistics.py | 5,330 | 3.609375 | 4 | import time
import os
import pandas as pd
import numpy as np
from datetime import datetime
import dateutil.parser
import utils
from utils import date_convert,date_offset
def read_csv(filepath):
'''
Read the events.csv and mortality_events.csv files. Variables returned from this function are passed as input... |
317b5674b5c26d19fba50e5b18c67494c33f001f | FRESH-TUNA/Algorithm_Exercise | /level1/goldbahe/.py | 2,185 | 3.578125 | 4 |
def 골드바흐이터레이션서비스():
while(숫자 = input != 0):
프린트(골드바흐(숫자))
def 숫자가볼드바흐면(숫자):
if 숫자 > 4 and 숫자 & 2 == 0:
골드바흐이다.
else:
골드바흐가아니다.
def 골드바흐(숫자):
if 숫자가골드바흐면(숫자):
return n을만들수있는방법중가장큰것(n)
else:
return "Goldbach's conjecture is wrong."
def n을만들수있는방법중가장큰것(숫자)
숫자A = 2
숫자B = 숫자 - 2
whi... |
3f26b432755a2ba9d2ebd09f43b7b50712399aa3 | FRESH-TUNA/Algorithm_Exercise | /level2/flat_paper.py | 587 | 3.671875 | 4 | def solution(n):
result = [0]
x = 1
insert_value = True
while x < n:
new_result = [0]
for last_data in result:
new_result = new_result + [last_data]
if insert_value is True:
new_result = new_result + [1]
else:
new_result... |
b76e63ea1bb4ee256f46be93c1fdeb16693c2b54 | RoyalRamesh/python-programming | /beginner level/vowel.py | 165 | 4.03125 | 4 | k = input("Input a letter of the alphabet: ")
if k in ('a','A','e','E','I' 'i','O','o','U','u'):
print("%s is a vowel." % k)
else:
print("%s is a consonant." % k)
|
3f2054dfef029efeb42e9f076a06958130f25896 | emrf2b/CS4500_HW3_Group10 | /cs4500_hw3_roeder.py | 4,305 | 3.703125 | 4 | """
CONTRIBUTORS: James Brown ()
Safi Khan ()
Eva Roeder (emrf2b@mail.umsl.edu)
Adam Wilson ()
PROJECT NAME:
https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly
https://stackoverflow.com/questions/11858159/... |
3e8767209a85af8982664909ec45c948c95eafb3 | alridwanluthfi00/Labpy | /Lab 4/Syntax/Latihan 1.py | 738 | 4.125 | 4 | # list bebas
a = [2, 4, 6, 8, 10]
# akses list
print(a[2]) # tampilkan elemen ke - 3
print(a[1:4]) # ambil nilai elemen ke - 2 sampai ke - 4
print(a[4]) # ambil elemen terakhir
print('==================================================')
# ubah elemen list
a[3] = 12 # ubah elemen ke 4 nilai lainnya
print(a)
a[3:5]... |
b608d778072bc2c55e4bfbf5f50da4a63a810b2b | ShigeyukiSakaki/pythontext | /p156.py | 758 | 3.75 | 4 | import math
#No.1
class Apple:
def __init__(self, c, l, b, p):
self.color = c
self.leaf = l
self.brand = b
self.price = p
#No.2
class Circle:
def __init__(self, r):
self.radius = r
def area(self):
return math.pi * self.radius**2
circle1 = Circle(10)
pri... |
69b6fa14143f0700879db4de9600c3a1e571928f | jonaylor89/ProjectEuler | /Problem14.py | 677 | 3.59375 | 4 |
from concurrent.futures import ThreadPoolExecutor
def collatz_length(num):
items = 1
while num > 1:
items += 1
if num % 2 == 0:
num = num / 2
else:
num = 3 * num + 1
return items
def collatz_max(d):
winner = 0
max_length = 1
for k, v in ... |
463300333444be42664fd4efc068d77dffa3ee33 | jonaylor89/ProjectEuler | /Problem2.py | 202 | 3.5 | 4 |
def fib(limit):
a, b = 1, 0
while a < limit:
a, b = a+b, a
yield a
if __name__ == '__main__':
even_list = (x for x in fib(4000000) if x%2 == 0)
print(sum(even_list))
|
8dcd45b9317c62db0e3c586b493604cbb833b091 | kareem171/1-16-18-warm-up | /Untitled.4.py | 188 | 4.1875 | 4 | # print even or odd in a range of numbers
for number in range (50):
if number%2==0:
print("Even number")
elif number %2==1:
print("Odd")
print(number)
|
418d38fd62dd96604db4b812e44fb7c961fd3750 | joeljoshy/Python-Set3 | /py2.py | 264 | 3.953125 | 4 | import re
#email
exp = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
def check(email):
if (re.search(exp, email)):
print("Valid")
else:
print("Invalid")
if __name__ == '__main__':
email = input("Enter your email : ")
check(email) |
ed5c7a1f1b1abd7cb63da4ab54b54ba616ecbe77 | Noura-Alquran/math-series | /math_series/series.py | 437 | 3.75 | 4 |
def fibonacci (n):
if n<=0:
return 0
elif n==1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
def lucas(m):
if m==0:
return 2
elif m == 1:
return 1
else:
return lucas(m-1) + lucas(m-2)
def sum_series(x, a=0, b=1):
if x == 0:
r... |
fd9f53e6d0a764fdccf72a3d5230fd38fa344997 | gungorefecetin/CS-BRIDGE-2020 | /Day2PM - Lecture 2.1/random_painter_karel.py | 1,104 | 3.953125 | 4 | from karel.stanfordkarel import *
"""
File: random_painter_karel.py
------------------------------
Your job is to paint random squares all over the world!
Pick two colors and choose randomly between them for each
square.
"""
def main():
"""
You should write your code to make Karel do its task in
this fun... |
6db90e6de92dc5a3ca12f22a6e94577abd42a6c1 | gungorefecetin/CS-BRIDGE-2020 | /Day3PM - Lecture 3.1/khansole_academy.py | 1,021 | 4.375 | 4 | """
File: khansole_academy.py
-------------------
This program generates random addition problems for the user to solve, and gives
them feedback on whether their answer is right or wrong. It keeps giving them
practice problems until they answer correctly 3 times in a row.
"""
# This is needed to generate random numb... |
461791388d5c39c519ab799b3761f876b9bc6dbb | gungorefecetin/CS-BRIDGE-2020 | /Day6PM - Lecture 6.1/mystery_square.py | 1,075 | 4.0625 | 4 | """
File: mystery_square.py
-------------------
This program creates a centered square that changes color randomly every second.
"""
from graphics import Canvas
# Needed for pausing for animation. Don't remove this.
import time
import random
# Size of the centered square
SQUARE_SIZE = 400
# Delay between color cha... |
8abfc5d9371ca1b5d64fc307cc2d58d9cd12575b | gungorefecetin/CS-BRIDGE-2020 | /Day3PM - Lecture 3.1/8ball_bonus.py | 664 | 4.0625 | 4 | """
File: 8ball.py
-------------------
Simulates an eight ball and gives sage answers to
yes or no questions.
"""
# This is needed to generate random numbers
import random
def main():
while True:
question = input("Ask a yes or no question: ")
# remember, this is a comment
... |
52963e18085b20a2f20020a0093b01ea26e34e0c | LucianoAlbanes/AyEDI | /TP1/Parte1/1/restrictions.py | 250 | 4.125 | 4 | ## The purpose of the following code is to have certain functions
## that python provides, but they are restricted in the course.
# Absolute Value (Aka 'abs()')
def abs(number):
if number < 0: return number*-1
else: return number
|
c730a468daba41b45753c87d0df58e7114a8c6ef | LucianoAlbanes/AyEDI | /TP1/Parte1/3/main.py | 1,565 | 3.859375 | 4 | from algo1 import *
# Ask length of inupt matrix and vector, and declare them
n = int(0)
m = int(0)
while (n < 1):
n = input_int('Ingrese la dimensión (n) de la matriz: ')
while (m < 1):
m = input_int('Ingrese la dimensión (m) de la matriz: ')
inputMatrix = Array(n, Array(m, 0.0))
n = int(0)
while... |
6735f531a626eb2dd8999e26136e950299a978d4 | LucianoAlbanes/AyEDI | /TP6/1/fibonacci.py | 1,058 | 4.25 | 4 | # Calc the n-th number of the Fibonacci sequence
def fibonacci(n):
'''
Explanation:
This function calcs and return the number at a given position of the fibonacci sequence.
Params:
n: The position of the number on the fibonacci sequence.
Return:
The number at the given position ... |
778360456c76292efd6de099cd6bf0abf1675e0f | LucianoAlbanes/AyEDI | /TP5/mystack.py | 1,095 | 3.84375 | 4 | # Stack implementation (LIFO)
# Based on Lists - sequence ADT implementation
from linkedlist import add
# Define operations
def push(stack, element):
"""
Explanation:
Add an element at the beginning of a stack (sequence ADT).
Params:
stack: The stack on which you want to add the element.... |
0ac9c93bd6a0802a830dd7415535df861efdbbbd | tuanduc123/th3 | /th45.py | 71 | 3.53125 | 4 | ds = input('Danh sách: ').split()
ds.reverse()
print(ds)
|
ef98c46c186d352f004202fa0db06d6fe1a94cb1 | ltstein/SCUTTLE | /software/python/addons/L3_tellHeading.py | 1,243 | 3.71875 | 4 | # L2_tellHeading.py
# This program checks the heading of the compass and vocalizes it through tts
# Import external libraries
import time
import numpy as np
# Import internal programs:
import L1_text2speech as tts # for talking
import L2_heading as head # for checking heading
def estimate(): # estimate the heading
... |
63bfae8fce3efe09b7727175323a0870f1ce04bc | ltstein/SCUTTLE | /software/python/basics/L1_rfid.py | 1,438 | 3.765625 | 4 | # This module allows the ability to read/write to RFID's.
# Before running the code, you need to install a modified version
# of the MFRC522-python library using the commands below.
# git clone https://github.com/ansarid/MFRC522-python
# cd MFRC522-python
# sudo python3 setup.py install
from mfrc522 import SimpleMFRC5... |
f8f30ee0eda3d8d0932bad6c0b2b45c2734a9337 | navbharti/java | /python-cookbook/wikipedia/test1.py | 1,201 | 3.5625 | 4 | '''
Created on Nov 8, 2014
@author: rajni
'''
import wikipedia
#print wikipedia.summary("pondicherry").encode("iso-8859-15", "xmlcharrefreplace")
#print wikipedia.search("Barack")
ny = wikipedia.page("pondicherry")
print ny.title
print ny.url
#print ny.content.encode("iso-8859-15", "xmlcharrefreplace")
#print ny.links... |
c828a8ab988f60b7a7c73a79ca678e5d7264415e | navbharti/java | /python-cookbook/other/ex7.py | 2,366 | 4.1875 | 4 | '''
Created on Sep 19, 2014
@author: rajni
'''
months = ('January','February','March','April','May','June',\
'July','August','September','October','November',' December')
print months
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
print cats
#fetching items from tupble and list
print cats[2]
print months[2]... |
2184302e59893b04b8e4f915a8f91a15e2a008ce | navbharti/java | /python-cookbook/postgresql/connection_test.py | 492 | 3.640625 | 4 | '''
Created on Oct 18, 2014
@author: rajni
'''
#source: http://www.tutorialspoint.com/postgresql/postgresql_python.htm
#Connecting To Database
'''Following Python code shows how to connect to an existing database.
If database does not exist, then it will be created and finally a database
object will be returned.'''
... |
5d4a9d3bf6f2b0cf8151daa24c21641c1a1b7aa7 | navbharti/java | /python-cookbook/twitter/test5.py | 756 | 3.546875 | 4 | '''
Created on Nov 10, 2014
@author: rajni
'''
import twitter
# XXX: Go to http://dev.twitter.com/apps/new to create an app and get values
# for these credentials, which you'll need to provide in place of these
# empty string values that are defined as placeholders.
# See https://dev.twitter.com/docs/auth/oauth for m... |
cdd39df47863a2441a8a5d9b4696b85d41f29ac0 | MartinRandall/CodeFirstDemo | /main.py | 3,373 | 3.578125 | 4 | import pygame
import random
# Size of board
board_width = 90
board_height = 60
screen_width = 600
screen_height = 400
class Board:
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [False] * width * height
self.x_scale = screen_width / width
... |
7357beca1c38efca4e040d1ade5fc2275e658942 | nemeth-bence/exam-trial-basics | /pirates/pirates.py | 775 | 4.25 | 4 | pirates = [
{'Name': 'Olaf', 'has_wooden_leg': False, 'gold': 12},
{'Name': 'Uwe', 'has_wooden_leg': True, 'gold': 9},
{'Name': 'Jack', 'has_wooden_leg': True, 'gold': 16},
{'Name': 'Morgan', 'has_wooden_leg': False, 'gold': 17},
{'Name': 'Hook', 'has_wooden_leg': True, 'gold': 20},
]
# Write a fun... |
90cdd451c3087dc6c929179527833d01dee7f201 | seb55381/PC2-2019-2 | /Pregunta4.py | 520 | 3.65625 | 4 | import random
N = 0
matriz = []
a = []
while True:
N = int(input("Ingrese el tamaño de la matriz, debe ser entre 2 y 5: "))
if N >= 2 and N <= 5:
break
else:
print("Ingrese un numero valido")
for i in range (0,N):
a = []
for i in range (0,N):
a.append(random.randrange(1,101))... |
18b6ea9da6e8c2299e1fc250f4cda3987e2d926f | KKGar/driving | /driving.py | 406 | 3.96875 | 4 | country = input ('請問你是哪國人: ')
age = input('你輸入年齡: ')
country = str(country)
age = float(age)
if country == '台灣':
if age >= 18:
print ('你可以考駕照')
else:
print ('你還不能考駕照')
elif country == '美國':
if age >= 16:
print ('你在美國可以考駕照')
else:
print ('你在美國還不能考駕照')
else:
print('你只能輸入台灣或美國') |
3f8236c87556006aca8e3df4f326b995fa149951 | aixixu/Python_Crash_Course | /Code/Chapter4/4_13.py | 248 | 3.8125 | 4 | simple_foods = ('pizza','ice cream','carrot cake','falafel','cannoli')
for food in simple_foods:
print(food)
#simple_foods[0]='egg tart'
simple_foods = ('pizza','egg tart','lindor','falafel','cannoli')
for food in simple_foods:
print(food) |
e8e35d68ff9c2867e5da81afb8913aa527c3c052 | aixixu/Python_Crash_Course | /Code/Chapter6/6_5.py | 351 | 3.984375 | 4 | river_country ={
'nile':'egypt',
'changjiang':'china',
'rhine':'germany',
}
for river, country in river_country.items():
print(f"The {river.title()} runs through {country.title()}.")
for river in river_country.keys():
print(f"The {river.title()}.")
for country in river_country.values():
p... |
556e1d5c25bf6ea56bf65c02bdef0aedc0a4fa94 | aixixu/Python_Crash_Course | /Code/Chapter3/3_7.py | 970 | 3.921875 | 4 | names = ['cohen','ethan','jamie']
print(f'{names[0].title()}, welcome to my dinner!')
print(f'{names[1].title()}, welcome to my dinner!')
print(f'{names[2].title()}, welcome to my dinner!')
print(f'\n{names[1].title()} cannot keep our engagement.')
names[1]='mason'
print(f'\n{names[0].title()}, welcome to my dinne... |
b0094fe867b112a49d6367b614c90c21b17ce943 | lakpa-tamang9/Calculator | /calc.py | 3,084 | 3.71875 | 4 | import tkinter as tk
# New comment below
HEIGHT = 600
WIDTH = 300
root = tk.Tk()
canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()
frame = tk.Frame(root, bg = 'gray', bd = 5)
frame.place(relx = 0.5, rely = 0.1, relwidth = 0.7, relheight = 0.1, anchor='n')
entry = tk.Entry(frame, font=('Helvetic... |
5ad0dbd8959a3daa53bc5d3c42d16ef0a4ee08ed | Gavin-Gao-Vegeta/algorithm018 | /week06/test.py | 4,840 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
import string
import math
def isPower(a, b):
if a == 1 or a == b:
return True
elif a % b == 0:
return isPower(a/b, b)
else:
return False
print(isPower(16, 2))
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a % b)
pr... |
27916944eb765e71dac30ea9acdbff33a9c88b8e | spencerhitch/codeforamerica_application | /cfa_violations.py | 2,329 | 3.640625 | 4 | """
Author: Spencer Hitchcock
Date: 24/06/2016
A brief program written in Python to summarize a simple dataset. SUMMARIZEVIOLATIONS calculates the number of violations in each category, and the earliest and latest violation date for each category given this comma-delimited data file representing building code violatio... |
b6a8f9c3301a21cb91aecdd047c6aa9c066e78c4 | arrickd/MatrixMulti | /main.py | 2,549 | 4.09375 | 4 |
def print_matrix(matrix):
for y in range(len(matrix)):
for x in range(len(matrix[y])):
print(matrix[y][x], end=" ")
print("")
def create_matrix():
matrix = []
while True:
matrix.append(input().split(","))
print("Next row ? y/n")
check = input()
... |
cd68bc26674303dc80626ed073d5596347f63f38 | vs2961/Sort_Visualizer | /selectionSort.py | 1,423 | 3.6875 | 4 | import turtle
import time
import random
t = turtle.Turtle()
turtle.hideturtle()
t.hideturtle()
t.speed(0)
turtle.tracer(0, 0)
turtle.bgcolor("black")
def drawArray(arr, count, col, colFront = "white", colBack = "white"):
t.clear()
width = turtle.window_width()
height = turtle.window_height()
t.pu()
... |
4fbe1d6eba59ef0ee7f9f62a788ad8e5f3744650 | arpanmangal/pset6_2017 | /caesar.py | 684 | 3.921875 | 4 | import sys
import cs50
def main():
if len(sys.argv) != 2:
print("Enter a command-line argument!")
exit(1)
key = int(sys.argv[1])
if key < 0:
print("Entered a non-negative integer key")
exit(0)
print("plaintext: ", end = "")
s = cs50.get_string();
print("ciph... |
fc7dd582f1d3fcff14bd071ddf53081faa20488a | mrmezan06/Python-Learning | /Real World Project-2.py | 364 | 4.25 | 4 | # Design a program to find avarage of three subject marks
x1 = int(input("Enter subject-1 marks:"))
x2 = int(input("Enter subject-2 marks:"))
x3 = int(input("Enter subject-3 marks:"))
sum = x1 + x2 + x3
avg = sum / 3
print("The average marks:", int(avg))
print("The average marks:", avg)
# Formatting the float value
pri... |
1276d32fde6b28a0cd150e64b8d0ce4546638297 | zainbinfurqan/LearnPython | /Example5/loops.py | 654 | 3.703125 | 4 |
# a = 4
# if (a in list_a):
# print(a, "is in thelist")
# print table of 2 with for loop
# for numbers in list_a:
# print(2, " ", " X ", numbers, " ", " = ", " ", 2*numbers)
# loop with rangetag
# list_b = list(range(0, 11, 1))
# print(list_b)
# a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# b = "abcdefg"
# i = 0
#... |
e8efc52684f9680bbaac503b91fdd868a6d6c5b1 | rishavhack/OOPS-Concept-and-Threads-In-Python | /Inheritance and Polymorphism/Program 2.py | 321 | 3.6875 | 4 | #Using Teacher class
from Program1 import Teacher
#Create instance
t = Teacher()
t.setid(10)
t.setname('Rishav')
t.setaddress('SGR Dental')
t.setSalary(25000)
#Reterive value from insatance and display
print 'id = ',t.getid()
print 'name = ',t.getname()
print 'address =',t.getaddress()
print 'salary =',t.getSalary()... |
f8a16b4cf56cf7740e6fd2843619fa66841ed8eb | rishavhack/OOPS-Concept-and-Threads-In-Python | /Classses and Objects/Program 10.py | 759 | 3.953125 | 4 | import sys
class Bank:
def __init__(self,name,balance=0.0):
self.name = name
self.balance = balance
def deposit(self,amount):
self.balance += amount;
return self.balance
def withdraw(self,amount):
if amount > self.balance:
print 'Balance amount is less,so no withdrawal'
else:
self.balance -= amou... |
f06f649935833e06ee15e3d3c3f78564e5b67174 | microease/Python-Cookbook-Note | /Chapter_1/1.3.py | 1,032 | 3.921875 | 4 | # 在迭代操作或者其他操作的时候,怎样只保留最后有限几个元素的历史记录?
# 保留有限历史记录正是 collections.deque 大显身手的时候。比如,下面的代码
# 在多行上面做简单的文本匹配,并返回匹配所在行的最后 N 行:
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_line... |
4c44b6c3219305a853f5e0e02163512f1fcef0df | microease/Python-Cookbook-Note | /Chapter_3/3.6.py | 273 | 3.6875 | 4 | # 你写的最新的网络认证方案代码遇到了一个难题,并且你唯一的解决办法就是使
# 用复数空间。再或者是你仅仅需要使用复数来执行一些计算操作。
a = complex(2, 4)
b = 3 - 5j
print(a)
print(b)
print(a.real)
print(a.imag)
|
9aba747577e6387948fc4d7b528f3bba39a69fc9 | microease/Python-Cookbook-Note | /Chapter_3/3.11.py | 282 | 4.09375 | 4 | # 你想从一个序列中随机抽取若干元素,或者想生成几个随机数。
import random
values = [1, 2, 3, 4, 5, 6]
res = random.choice(values)
print(res)
res = random.sample(values,3)
print(res)
res = random.shuffle(values)
print(res)
res = random.random()
print(res)
|
64f0fb0d2fdabe785bb0faa49e7ef03c01919440 | microease/Python-Cookbook-Note | /Charpter_4/4.5.py | 85 | 3.875 | 4 | # 你想反方向迭代一个序列
a = [1,2,3,4]
for x in reversed(a):
print(x)
|
9750196603066542da908cb28196c382837f4546 | microease/Python-Cookbook-Note | /Chapter_2/2.20.py | 399 | 3.703125 | 4 | # 你想在字节字符串上执行普通的文本操作 (比如移除,搜索和替换)。
data = b'hello world'
print(data[0:5])
print(data.startswith(b'hello'))
print(data.replace(b'hello', b'hello cruel'))
data = bytearray(b'hello world')
print(data[0:5])
s = b'hello world'
print(s)
print(s.decode('ascii'))
res = '{:10s} {:10d} {:10.2f}'.format('ACME', 100, 490.1).encode... |
c765b56d4d457bd428b05d59a0c882ccf7325910 | kkkansal/FSDP_2019 | /DAY 02/pangram.py | 956 | 4.21875 | 4 | """
Code Challenge
Name:
Pangram
Filename:
pangram.py
Problem Statement:
Write a Python function to check whether a string is PANGRAM or not
Take input from User and give the output as PANGRAM or NOT PANGRAM.
Hint:
Pangrams are words or sentences containing every letter of the alphabet at ... |
c6612000c95d8828eee2ef423044119eccee3463 | kkkansal/FSDP_2019 | /DAY 04/absentee.py | 364 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 04:13:50 2019
@author: kunal
"""
file=open('absentee.txt', mode = 'wt')
while True:
user_input = input("enter the value you want to insert")
file.write(user_input)
if not user_input:
break
file.close()
file=open('absentee.txt',mode='rt')
kunal=file... |
58708f641c9d77ec7a5e6327285d4df6b6bafb4c | kkkansal/FSDP_2019 | /DAY 05/print e-mail address in list.py | 340 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 23:06:10 2019
@author: kunal
"""
import re
#while True:
input1=(input("enter the e-mail address"))
# if not input1:
# break
match= re.search(r'\b[A-Z0-9+-]+@[A-Z0-9]+\.[A-Z]{1,}\b', input1,re.I)
print([match.group()])
for item in ... |
474d4d0b1f0a73ad74bd54b220d88c4e18e1e242 | kkkansal/FSDP_2019 | /DAY 03/answer/Intersection.py | 500 | 3.65625 | 4 | """
Code Challenge
Name:
Intersection
Filename:
Intersection.py
Problem Statement:
With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155]
Write a program to make a list whose elements are intersection of the above
given lists.
"""
first_list = [1,3,6,78,35,55]
second_list = [... |
cf24e6acc35ab91e205abc1cca8837cd28ca2d3a | kkkansal/FSDP_2019 | /DAY 03/answer/teen_cal.py | 1,346 | 3.875 | 4 | """
Code Challenge
Name:
Teen Calculator
Filename:
teen_cal.py
Problem Statement:
Take dictionary as input from user with keys, a b c, with some integer
values and print their sum. However, if any of the values is a teen --
in the range 13 to 19 inclusive -- then that value counts as 0, ex... |
d7b86abd0316e4c710f01619e4bca270e95bbcb1 | kkkansal/FSDP_2019 | /DAY 03/answer/mailing.py | 2,270 | 3.875 | 4 |
"""
Code Challenge
Name:
Mailing List
Filename:
mailing.py
Problem Statement:
I recently decided to move a popular community mailing list (3,000 subscribers,
60-80 postings/day) from my server to Google Groups.
I asked people to joint he Google-based list themselves,
and added many others m... |
800cf7336d707dac229f457db2ac12129505366a | kkkansal/FSDP_2019 | /DAY 03/taking input in dictionary.py | 457 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 03:57:18 2019
@author: kunal
"""
dict1={}
while True:
user_input=input("enter the values")
if not user_input:
break
user_input = user_input.split(" ")
if " ".join(user_input[:-1]) in dict1:
dict1[' '.join(user_input[:-1]... |
e32cf9c0f0f3bec5dda2c498dd1910134388328d | sfreema1/Harvard-Machine-Host | /GlobalVariables.py | 4,092 | 3.65625 | 4 | ######### Globals ######
# I guess you don't need to declare global if you import
# Maybe you just need global if you are going to want to modify these variables in the program
# A useful dictionary for converting indices into letters
ABC = {0:"A", 1:"B", 2:"C", 3:"D", 4:"E", 5:"F", 6:"G", 7:"H", 8:"I", 9:"J"}
# If o... |
847bdff898c530b627d04fbd85b45959d279d798 | sfreema1/Harvard-Machine-Host | /RectangleGenerator.py | 6,062 | 3.625 | 4 | import math
#from matplotlib import pyplot as plt
# make sure you give center and dim as type float
def make_rectangle(center, dim, resolution):
center_x = center[0] # in mm
center_y = center[1] # in mm
dim_x = dim[0] # in mm
dim_y = dim[1] # in mm
res = resolution # in microns
res_mm = res... |
5528f3822a981c88f14222da69060e68581dd6dd | matheusCalaca/estudos-python-alura | /str_metodos/forca.py | 1,494 | 4.25 | 4 | # para definir uma funcao no python voce usa a palavra "def" segue o examplo encapsulando o jogo em uma função para ser
# chamado em outro arquivo
def jogar():
print("********************************")
print("***Bem vindo ao jogo de Forca***")
print("********************************")
#variaveis
palavra_se... |
60f1674ebc94f03661576b2b15a56d2372bbf0aa | matheusCalaca/estudos-python-alura | /funcao_estrutura_codigo/forca.py | 6,046 | 3.984375 | 4 | # para definir uma funcao no python voce usa a palavra "def" segue o examplo encapsulando o jogo em uma função para ser
# chamado em outro arquivo
import random
def jogar():
imprime_mensagem_abertura()
# variaveis
palavra_secreta = carrega_palavra_secreta()
letras_acertadas = inicializa_letras_acertad... |
d25bf5a68f97f1a499bc817c0cfc3fa7d4490121 | aaron-lucas315/CS-201-Final-Project | /rope.py | 9,173 | 3.859375 | 4 | class Rope(object):
def __init__(self, data='', parent=None):
# checks if input is a string
if isinstance(data, list):
if len(data) == 0:
self.__init__()
elif len(data) == 1:
self.__init__(data[0], parent=parent)
else:
... |
7f643995e533df975143af460ef04ceab2e65691 | CCAtAlvis/ProjectEuler | /010.py | 387 | 3.625 | 4 | import time
start_time = time.time()
num = 3
counter = sum = 2
key = temp = 0
while num < 2000000:
temp = num
while counter * counter <= num:
if num % counter == 0:
num = num/counter
key = 1
break
else:
counter += 1
if key == 0 :
sum += temp
print temp
num = temp + 2
counter = 2
key = 0
p... |
adaa2cb7908e692ec44fd2f004cdf72fa1881ef5 | CCAtAlvis/ProjectEuler | /019_1.py | 808 | 3.90625 | 4 | #this program does not use make day or that kind of function although thats easer but thats not fun
#and is being built... check the easer program for answer
import time
start_time = time.time()
#making a switch in python
def switch(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 is default if x no... |
4ddb039b6b4e299b666335391b51e411a034e394 | poiuyy0420/python_study | /chapter01_02.py | 2,789 | 4.09375 | 4 | # Chapter01-2
# 객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지 등
# 클래스 상세 설명
# 클래스 변수, 인스턴스 변수
# 클래스 재 선언
class Student():
"""
Student Class
Author : Kwon
Data : 2021.01.28
"""
# 클래스 변수
student_count = 0
def __init__(self, name, number, grade, details, email=None):
# 인스턴스 변수
se... |
9636c61a43206e2e4a3162dd4486993ede22772e | jerkuebler/pyeuler | /21-30/quadprimes.py | 777 | 3.640625 | 4 | from math import sqrt
def prime(n):
if n < 2:
return False
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
return False
return True
def quad_form(num, a, b):
return num ** 2 + a * num + b
def quad_primes(range_width):
start_a = - range_width + 1
end_a = ra... |
90aabbb837f203162e77bbb07dbf1da47ed0188c | jerkuebler/pyeuler | /11-20/countsun.py | 919 | 3.953125 | 4 | import datetime
def count_sunday(startyear, endyear):
total = 0
start = datetime.date(year=startyear, month=1, day=1)
end = datetime.date(year=endyear, month=12, day=31)
def daterange(start_date, end_date):
for n in range(int((end_date-start_date).days)):
yield start_date + date... |
8c6ff37359ae97e9c4c64766fecd22d3c043122f | jerkuebler/pyeuler | /31-40/pandigitmultiple.py | 873 | 3.609375 | 4 | # Not really sure how to justify the way I'm reducing the values being iterated over.
# Fast result and gives all the 9-digit pandigitals for series where n > 1.
def pandigital_multiple():
pandigital_list = []
for list_len in range(2, 20):
max_num = "9" * (9 // list_len + 1)
min_num = ("1" * ... |
1c9f5d6aeb9514a99349c4b3da6ac7fd1a9d2704 | caueguedes/webScraping | /chapter8/7 nltkAnalysis.py | 884 | 3.84375 | 4 | from nltk import word_tokenize, sent_tokenize, pos_tag
sentences = sent_tokenize("Google is one of the best companies in the world. \
I constantly google myself to see what I'm up to.")
nouns = ['NN', 'NNS', 'NNP', 'NNPS']
for sentence in sentences:
if "google" in sentence.lower():
... |
6fe32f2de6e1939f9ca49c6d2b6d1a844bbabde6 | dev-di/python | /hellodate2.py | 377 | 3.984375 | 4 | # This is how to import in Python
from datetime import datetime, timedelta
# birth = input("What is your birth date? (yyyy-mm-dd): ")
birth = "2019-11-13"
birthday_date = datetime.strptime(birth, "%Y-%m-%d")
print("Your birthdate is: " + str(birthday_date))
print("Your day of birth was a: " + str(birthday_date.weekday... |
0e58b02c59fe57bf55e8c1c61a0442f35146876f | dev-di/python | /helloworld.py | 323 | 4.1875 | 4 | #name = input("What is your name my friend? ")
name = "Diana"
message = "Hello my friend, " + name + "!"
print(message) #comment
print(message.upper())
print(message.capitalize())
print(message.count("i"))
print(f"message = '{message}', name = '{name}'")
print("Hello {}!!".format(name))
print("Hello {0}!".format(nam... |
85cf5b61fb97ff67966ae0b55fd7f00a5b2bb481 | oddlyspaced/hackerrank-python | /easy/divide.py | 154 | 3.734375 | 4 | # https://www.hackerrank.com/challenges/python-division/problem
a = float(int(input("")))
b = float(int(input("")))
d = float(a/b)
print(int(d))
print(d)
|
d78e25319ee48c948ff6d1144d7fb112f3ca0c24 | cohenb51/School | /PL/FinalProject/functionalPython/processors.py | 2,882 | 3.890625 | 4 | #!/usr/bin/python
import sys
import functools
def lower(string):
return ''.join(map(charToLower, string)) ## strings are immutable so doesn't change original
def charToLower(c):
if ord(c) <= 90 and ord(c) >= 65: #again view it as evaluating a functional. Not store 2 seperate variables and then check. Deep down de... |
96a962066ed01f5341e414724a0d4b1af26ce700 | trungnnguyen/matlab-all | /matlab-typ/adivinaNumero.py | 302 | 3.65625 | 4 | #! -*- coding: cp1252 -*-
# Funcin
import random
A=random.randint(0,100)
n=1
print(A)
while True:
B=input("Inserte el nmero: ")
if A==B:
print("Nmero encontrado")
break
print("Siga intentando")
n=n+1
print("Nmero encontrado en ",n," intentos")
raw_input('')
|
7bc2a1e0fe346cecb5033339aa92b0a1af64a07a | acsant/CodingChallenges | /LibraryDriver.py | 261 | 3.59375 | 4 | from Library import Library
with open('data.txt') as lib_data:
lib = Library(lib_data)
while 1:
word = raw_input("Enter a word to search by: ").strip()
results = lib.search(word)
for res in results:
print res.title
|
6cf6799c4f652c47a3cb818ab1910b4c8d3d6d1c | JustinTrombley96/Python-Coding-Challenges | /drunk_python.py | 730 | 4.1875 | 4 | '''
Drunken Python
Python got drunk and the built-in functions str() and int() are acting odd:
str(4) ➞ 4
str("4") ➞ 4
int("4") ➞ "4"
int(4) ➞ "4"
You need to create two functions to substitute str() and int(). A function called int_to_str() that converts integers into strings and a function called str_to_int() tha... |
91117ae8ad046a6aed63f76d546ad6fe6b93b5ff | ScottGlenn1800/WeatherPlotting | /Libraries/WEATHER_LIBRARY.py | 787 | 3.5 | 4 | import requests,json
def RequestData(APIKEY,endpoint):
BaseURL = "http://api.openweathermap.org/data/2.5/"
print"Sending request: " + BaseURL + endpoint + "&APPID=" + APIKEY
response = requests.get(BaseURL + endpoint + "&APPID=" + APIKEY)
if response.status_code == 200:
data = json.loads(response.content.decode... |
1427540e8cd84baad7817e340368e886df87b276 | g1llz/URI-python3 | /uri2136.py | 454 | 3.734375 | 4 | lista_yes = []
lista_no = []
aux = 0
nome_maior = ""
while True:
nome = input().split()
if nome[0] == "FIM":
break
if nome[1] == "YES" and nome[0] not in lista_yes:
lista_yes.append(nome[0])
if nome[1] == "NO":
lista_no.append(nome[0])
for i in sorted(lista_yes):
print(i)
for i in sorted(lista... |
c5daa41736eb2abfe8ba85642223dfe24e7d22e5 | g1llz/URI-python3 | /uri1129.py | 575 | 3.671875 | 4 | while True:
entrada = int(input())
if entrada!=0:
for i in range(entrada):
valores = input().split()
contador = 0
posicao = 0
for i in valores:
if int(i) <=127:
contador+=1
posicao = valores.index(i)
if contador!=1:
print("*")
... |
7c2a7c641310d445f128b9aa1dd3914dad2b3cb2 | trcz/creditNB | /naivebayes.py | 4,024 | 3.796875 | 4 |
#EXAMPLE APPLICATION OF NAIVE BAYES FOR FEATURES WITH MIXED DISTRIBUTIONS
import numpy as np
import pandas as pd
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.naive_bayes import BernoulliNB
from sklearn.preprocessing import MinMaxScaler
import warnings
... |
001a5f9ea785b9523c8d62e6ccf201ff6a6f7426 | tcl326/Euler-s-Project | /Consecutive Prime Sum (50).py | 1,398 | 3.71875 | 4 | __author__ = 'student'
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equa... |
89b69d5b3a2e700b7f49bd7537ed6a56f1eaaef5 | anvandev/TMS_HW | /HW/task_1_5/task_5_7.py | 948 | 4.34375 | 4 | """ Закрепить знания по работе с циклами и условиями.
Дана целочисленная квадратная матрица. Найти в каждой строке наи-
больший элемент и поменять его местами с элементом главной диагонали. """
from random import randint
# function to print matrix in a convenient form
def print_matrix(matrix):
for element in ma... |
ad193f269225a1fa0bd24789d9fcd57edd00724d | anvandev/TMS_HW | /HW/tasks_6_9/task_9_2.py | 592 | 4.09375 | 4 | """Закрепить знания по работе с lambda функциями, генераторами списков и словарей,
декораторами.
Создать lambda функцию, которая принимает на вход неопределенное
количество именных аргументов и выводит словарь с ключами удвоенной
длины. {‘abc’: 5} -> {‘abcabc’: 5} """
cities = lambda **kwargs: {key + key: value for k... |
7c7e82c07f5df3c70fc906a62c027940ef669eea | anvandev/TMS_HW | /HW/task_1_5/task_5_1.py | 1,593 | 4.09375 | 4 | """ Закрепить знания по работе с циклами и условиями.
Написать программу, в которой вводятся два операнда Х и Y и знак операции
sign (+, –, /, *). Вычислить результат Z в зависимости от знака. Предусмотреть
реакции на возможный неверный знак операции, а также на ввод Y=0 при
делении. Организовать возможность многократн... |
2be78b4cfcf98bff824f41bfa068c69fb7f2ba9b | FabriceMesidor/Hip-Hop-Clusters | /Data-Cleaning-EDA/edahelpers.py | 1,289 | 3.703125 | 4 | import nltk
from nltk.corpus import stopwords
import string
#Stopwords
#Define stopwords
punctuation = "".join([symbol for symbol in string.punctuation if symbol not in ["'", '"']])
punctuation += '–'
punctuation += '...'
stopwords_list = stopwords.words('english')
stopwords_list += list(punctuation)
stopwords_list ... |
4ad17fdc2b5107ef3a820c5d0739bdb3afbb7811 | rishith123/cricket-game-first-try | /odd or even.py | 13,005 | 3.984375 | 4 | import random
import colorama
from colorama import init
init()
from colorama import Fore, Back, Style
game=1
check=[1,2]
runs=[0,1,2,3,4,5,6]
while(game==1):#till the player wants to play
print(Fore.BLACK + Back.BLUE + "")
name=input("enter your name : ")#take the p... |
106c85e88fcc4fbb246c8270d652cedc9de10446 | SreeNru/ReDiProject | /main.py | 580 | 4.125 | 4 | from datetime import *
import pytz
print(">>Welcome to Python program to get Current Time")
print(">>Please select your desired country")
list=["Europe/Berlin","Asia/Kolkata","America/Los_Angeles", "America/New_York","Europe/London","Hongkong","Europe/Minsk","Australia/Sydney"]
serial = 1
for item in list:
print(se... |
2fb01062b7184d9bcfb5076cf085755c9c0b5b4a | nathan755/monopoly | /game/game_objects.py | 1,717 | 3.734375 | 4 | import pygame
class Square:
"""
Base class
All squares on monopoly board will inherit from this.
"""
def __init__(self, x, y, w, h, square_id):
self.x = x
self.y = y
self.w = w
self.h = h
self.id = square_id
self.hover = False
self.is_clicked... |
27edd45628f50bdd4eef0196d8e8f3d1f16bf065 | OlehYavoriv/ITVDNtasks-py- | /task4.2.py | 130 | 4.03125 | 4 | chyslo = int(input("Enter number:"))
factorial = 1
for i in range(2, chyslo+1):
factorial *= i
print("Result:",factorial)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.