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 |
|---|---|---|---|---|---|---|
fcedb2e85cb1283c77421a2f9aed8fd1b77af591 | nnicexplsz/python | /Work/4_2.py | 2,336 | 3.8125 | 4 | t = 5
vocadulary = {
"rose apple":" n.คำนาม ชมพู่ ",
"keyboard":" n.คำนาม คีย์บอร์ด",
"drink":" v.คำกริยา ดื่ม ",
"speak":" v.คำกริยา พูด",
"These":" adj.ขยายคำนาม พวกนี้",
}
while(True):
print("พจนานุกรม\n 1)เพิ่มคำศัพท์\n 2)แสดงคำศัพท์\n 3)ลบคำ... |
f46ef7a473eaa019a376c7312864168d63e06ef5 | nnicexplsz/python | /week3/week3_2.py | 896 | 3.703125 | 4 | value = int(input("กรุณากรอกจำนวนครั้งการรับค่า")) # แบบฝึกหัด 3.2
i = 1
a = 0
while(i <= value) :
number = int(input("กรอกตัวเลข :"))
i=i+1
a=a+number
print("ผลรวมที่รับค่ามาทั้งหมด = %d"%a)
print("ป้อนชื่ออาหารโปรดของคุณ หรือ exit เพื่อออกจากโปรแกรม")
foodlist[]
i = 0
while(True):
i = i +1
prin... |
b3f0da91062c2cef4b18f75077bacb5b9b555d02 | JFincher42/RandomStuff | /sairam-test.py | 493 | 3.53125 | 4 | import pygame
pygame.init()
window = pygame.display.set_mode([500,500])
x_speed = 7
y_speed = 3
b_x = 15
b_y = 15
frames = 0
while frames < 750:
frames += 1
b_x += x_speed
b_y += y_speed
if b_x >= 485:
b_x = 15
elif b_x <= 15:
b_x = 485
if b_y >= 485:
b_y = 15
e... |
e66d6267baedca2ed407055dec553fc524811e0c | abhinavgairola/PowerSimData | /powersimdata/utility/helpers.py | 3,071 | 3.59375 | 4 | import copy
import importlib
import os
import sys
class MemoryCache:
"""Wrapper around a dict object that exposes a cache interface. Users should
create a separate instance for each distinct use case.
"""
def __init__(self):
"""Constructor"""
self._cache = {}
def put(self, key, o... |
68f964fde72113fea68ff42de7cb33db2e7f4e86 | abhinavgairola/PowerSimData | /powersimdata/utility/distance.py | 2,790 | 3.703125 | 4 | from math import acos, asin, cos, degrees, radians, sin, sqrt
def haversine(point1, point2):
"""Given two lat/long pairs, return distance in miles.
:param tuple point1: first point, (lat, long) in degrees.
:param tuple point2: second point, (lat, long) in degrees.
:return: (*float*) -- distance in mi... |
c210c723687f3b80583ad336bcdbc0b9f737af0d | mytbk/xgboost-learning | /convert_data.py | 895 | 3.5625 | 4 | #!/usr/bin/env python2
import pandas
import sys
from types import *
def getDataFromCSV(csv):
table = pandas.read_csv(csv)
column_names = table.columns
working = pandas.DataFrame()
for col in column_names:
print(col)
if type(table[col][0]) is not StringType:
... |
308f36d76762dfc539ff391c11c3464963ac7e4c | mattbaumann1/contractors | /main.py | 1,173 | 3.96875 | 4 | #!/usr/bin/python3
# main.py authored by Matt Baumann for COMP 412 Loyola University
#The following video was very helpful for this assignment: https://www.youtube.com/watch?v=mlt7MrwU4hY
import csv
#Creation of list objects.
contractorList = []
lobbyistList = []
#Reading in the contractorList with contracts for ... |
f7269f85dbc1ec9a43880f49efa09b193e080aee | bopopescu/PycharmProjects | /shashi/7) Mebership & indentity operators.py | 1,117 | 4.0625 | 4 | # Membership Operators 15/05/2018
#a = '1'
#if (a === 1):
# print(a)
#if(a == '1'):
# print(a)
'''l1 = [1,2,3,4]
if 1 in l1:
print(1 in l1)
d1 = {'a': 1 , 'b': 2}
print('a' in d1)
print('aa' in d1)
print('a' not in d1)
print('aa' not in d1)'''
# Indentity operators
'''a = 1
print(a is 1)
print(a is not... |
347460f3edf3af4e5601a45b287d1a086e1a3bc3 | bopopescu/PycharmProjects | /Class_topic/7) single_inheritance_ex2.py | 1,601 | 4.53125 | 5 | # Using Super in Child class we can alter Parent class attributes like Pincode
# super is like update version of parent class in child class
'''class UserProfile(Profile): # Child Class
def __init__(self,name,email,address,pincode): # constructor of child Class
super(UserProfile, self).__init__(name,email... |
55f9eb36b8d77e7adfa28e1d27a5922dfddf1206 | bopopescu/PycharmProjects | /shashi/17) ExceptionHandling_try& _except.py | 840 | 4 | 4 | '''try:
int("sds")
print(name)
name = "aaaa"
open('dddddd')
import asdfg
print("went good...")
except (NameError, ValueError, ImportError):
print("something went Wrong")
except NameError:
print("NameError")
#except:
except ValueError:
print("exception")
except ImportError:
pr... |
2329f20248f4ab62b23828caae234b23dad10ab8 | bopopescu/PycharmProjects | /shashi/14) import_3_methods & packages .py | 552 | 3.515625 | 4 | # import 3 methods
# 1) import PackageName
'''import test
print(test.email)
test.name()'''
# 2) from PackageName import VarName ,functions ,Classes
'''from test import name,email
name()
print((email))'''
# 3) from PackageName import *
'''from test import *
name()
print(email)'''
# 4) from PackageName import VarN... |
6a6b1394a960ba09ff2c97fa71e61b78a1c45858 | bopopescu/PycharmProjects | /shashi/10) functions_1( lambda) .py | 1,902 | 4.25 | 4 | #Nested function
'''def func1():
def func2():
return "hello"
return func2
data = func1()
print(data())'''
#global function
'''a = 100
def test():
global a # ti use a value in function
a = a + 1
print(a)
#print(a)
test()'''
'''a = 100
def test():
global a # ti use a value in function... |
ee3776a9a10899adb7ca4e6979145114c979dabf | bopopescu/PycharmProjects | /Class_topic/class_assigment.py | 351 | 3.75 | 4 | '''class A:
def __init__(self,file):
self.file = open("Demo")
data = self.file.read()
print(data)
def f1(self,f):
m = input("enter a string")
self.f = open("demo")as w:
self.f = m.writeable()
def __del__(self):
print("i am here")
a = A("file2")
te... |
2001b07997daf96893b9885f14bff85c97f59d2d | danniekot/programming | /Practice/21/Python/21.py | 281 | 3.875 | 4 | def BMI(weight: float, height: float):
return weight/(height*height/10000)
def printBMI(bmi: float):
if BMI < 18.5 print('Underweight')
elif BMI < 25 print('Normal')
elif BMI < 30 print('Overweight')
else print('Obesity')
w,h=map(float,input().split())
printBMI(BMI(w,h)) |
1f6a9e033c3a3b8c5c278cb4a96d5900ef8a994e | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/optional-labs/roadtrip/roadtrip-v1.py | 1,130 | 4.15625 | 4 | city_dict = {
'Boston': {'New York', 'Albany', 'Portland'},
'New York': {'Boston', 'Albany', 'Philadelphia'},
'Albany': {'Boston', 'New York', 'Portland'},
'Portland': {'Boston', 'Albany'},
'Philadelphia': {'New York'}
}
city_dict2 = {
'Boston': {'New York': 4, 'Albany': 6, 'Portland': 3},
'New York': {'... |
0f6a5f4930f4a7ef9ce28e4fe790d79b1e77561b | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab15/lab15-number-to-phrase-v2.py | 1,819 | 3.984375 | 4 | '''
lab15-number-to-phrase-v2
Version2:
Handle numbers from 100-999
'''
print("Welcome to Number to Phrase v2.0. We'll convert your number between 0-999 to easily readable letters.")
while True:
n = int(input("Please enter an integer between 0 and 999: "))
if n not in range(0, 1000):
print("Please e... |
7c693a0fe73b2fe3cbeeddf1551bf3d2f0250ab2 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab12/lab12-guess_the_number-v3.py | 694 | 4.34375 | 4 | '''
lab12-guess_the_number-v3.py
Guess a random number between 1 and 10.
V3
Tell the user whether their guess is above ('too high!') or below ('too low!') the target value.'''
import random
x = random.randint(1, 10)
guess = int(input("Welcome to Guess the Number v3. The computer is thinking of a number between 1 and ... |
ffa71514a68193fcebd2c4939dfeaa28529d5f75 | pjz987/2019-10-28-fullstack-night | /Assignments/dj/lab10-v1.py | 390 | 4.09375 | 4 | """
Name: DJ Thomas
Lab: 11 version 1
Filename: lab10-v1.py
Date: 10-31-2019
Lab covers the following:
- input()
- float()
- for/in loop
- fstring
- range
"""
num = int(input("how many numbers?: "))
total_sum = 0
for i in range(num):
numbers = float(input('Enter number: '))
total_sum +=... |
f4da5503cbbf47772f9bcccdbfc7487c6efdc13f | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab14-gambling_pick6v2.py | 2,237 | 4.09375 | 4 | '''
lab14-pick6-v1.py
v2
The ROI (return on investment) is defined as (earnings - expenses)/expenses. Calculate your ROI, print it out along with your earnings and expenses.
'''
#1.Generate a list of 6 random numbers representing the winning tickets...so define a pick6() function here.
import random
def pick6():
ti... |
82ef1519965203526bf480fc9b989e73fb955f54 | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab17-palidrome_anagramv2.py | 312 | 4.5625 | 5 | # Python Program to Check a Given String is Palindrome or Not
string = input("Please enter enter a word : ")
str1 = ""
for i in string:
str1 = i + str1
print("Your word backwards is : ", str1)
if(string == str1):
print("This is a Palindrome String")
else:
print("This is Not a Palindrome String") |
713f27ced7d6e57dc790dc700c996d0046584b74 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/optional-labs/opt-lab-lcr-v2.py | 2,739 | 3.59375 | 4 | '''
Lab: LCR Simulator
https://github.com/PdxCodeGuild/2019-10-28-fullstack-night/blob/master/1%20Python/labs/optional-LCR.md
'''
import random
#this is the function for each player turn:
def player_roll(player_name, chips, player_L, player_R):
die_sides = ["L", "C", "R", "*", "*", "*"]
player_roll = []
if... |
ae03c569f2eb80951263f0556482c783d009e549 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/optional-labs/tic-tac-toe/tic_tac_toev2.py | 2,803 | 3.890625 | 4 | '''
Tic-Tac-Toe
'''
# import numpy
class Player:
def __init__(self, name, token):
self.name = name
self.token = token
class Game:
def __init__(self):
board = {
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
... |
2928ceeee16232bba71cac568fab3e3c19ee15bf | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab20.py | 649 | 3.640625 | 4 | def get_second_digit(num):
if num < 10:
return None
return num % 10
def validate_credit_card(cc_str):
if len(cc_str) != 16:
return False
cc = []
for i in range(len(cc_str)):
cc.append(int(cc_str[i]))
check_digit = cc.pop(-1)
cc.reverse()
for i ... |
eb0bf7381ff1ea3d9f11dec46d6e2ff775d65c7e | pjz987/2019-10-28-fullstack-night | /Assignments/dustin/lab23.py | 586 | 3.515625 | 4 | '''
By: Dustin DeShane
Filename: lab23.py
'''
songs = []
with open("songlist.csv", 'r') as song_list:
rows = song_list.read().split('\n')
headers = rows.pop(0).split(',') #set first row as headers/keys
#print(headers)
for row in rows:
row = row.split(',') #iterate through rows and split them in... |
abacfce7f2c434836cfdcbbe6f763df0dce691fe | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab09.py | 177 | 4 | 4 | import decimal
#user input
d_ft = int(input("Input distance in feet: "))
#conversion
d_meters = d_ft/0.3048
#equals
print("The distance in meters is %i meters." % d_meters)
|
c41cf49d568bee4f2e2caaf24483b0e032b247eb | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab11_v1.py | 146 | 3.640625 | 4 | operation = input("What operation would you like to do?")
num_1 = int(input("Enter first number."))
num_2 = int(input("Enter second number."))
|
8ed3fb8ef261e016ce96a2af1f955eab2003e599 | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab20-credit_card_check.py | 1,172 | 3.6875 | 4 | def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
... |
2d304bd9b8bcae2dc320a8a252ca066983467326 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab23-contact-list/lab23-contact-list-v3.py | 3,638 | 3.828125 | 4 | '''
Lab 23: Contact List
Version3
When REPL loop finishes, write the updated contact info to the CSV file to be saved. I highly recommend saving a backup contacts.csv because you likely won't write it correctly the first time.
'''
with open('cities_list.csv', 'r') as cities:
#establish the rows
rows = cities.read... |
61902e6f6ac8f23acb98798c79228bab0c09d829 | pjz987/2019-10-28-fullstack-night | /Assignments/duncan/python/lab03_grading.py | 1,030 | 4.0625 | 4 | '''
A = range(90, 100)
B = range(80, 89)
C = range(70, 79)
D = range(60, 69)
F = range(0, 59)
'''
import random
print("Welcome to the Grading Program!")
user_grade = int(input("What is your numerical score?"))
# set up +/-
if user_grade % 10 in range(1,6):
sign = "-"
elif user_grade % 10 in range(6,11):
sig... |
b3a7d72bede78555fe345a47f43661641b90e65d | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab12_v1.py | 265 | 3.984375 | 4 | import random
target = random.randint(1,10)
guess = ''
while True:
guess = input('guess the number! ')
guess = int(guess)
if guess == target:
print('that\'s correct!')
break
else:
print('that\'s incorrect!')
|
188fa1987331719b38bedc7fc2ecfa785328c1fd | harshidkoladara/Python_Projects | /PoliceComplainSystem/Template Files/mainconnection.py | 466 | 3.625 | 4 | import sqlite3
from sqlite3 import Error
def sql_connection():
try:
con = sqlite3.connect('mydatabase.db')
return con
except Error:
print(Error)
def sql_table(con):
cursorObj = con.cursor()
#cursorObj.execute('insert into data VALUES(1,0," "))')
cursorObj.ex... |
1d9b46c9cf7ecff4ea5e4ea41dc18f269dcf1ff6 | soupierbucket/Lets-Build | /Calculator_Using_Python/Calc_Using_Python.py | 4,608 | 4.125 | 4 | #Import section
from tkinter import *
#Funtion definations
def click(num):
"""
To display the number
num: input onclick parameter
"""
value = entry.get()
entry.delete(0, END)
entry.insert(0, str(value) + str(num))
return
def clear():
"""
To clear the screen
... |
3a495c4e7a920cda01b5805f0eaebc9f3fc455ae | n20002/Task | /0813.py | 2,637 | 3.734375 | 4 | import sys
from itertools import count
from random import randint
def checkfn(left, right, guess):
if left < right and guess == 'h':
return True
if left == right and (guess == 'h' or guess == 'l'):
return True
if left > right and guess == 'l':
return False... |
e128273e27389122b8d02b180980fa8562c940fb | jostaylor/Word_Search_Generator | /WordSearch.py | 7,628 | 4.125 | 4 | import random
import sys
# TODO What can I add?
# Make the program more user-friendly:
# Maybe if we get an infiniteError, allow the user to alter the words or the size of the grid and retry
# Add a file writer for the key to the word search
# Make it easier for the user to input without having to type them in all ove... |
e3131b62735d783016b26f1b6f25ca8754cb2458 | IamGianluca/algorithms | /ml/sampling/metropolis.py | 2,929 | 3.625 | 4 | import numpy as np
class MetropolisHastings(object):
"""Implementation of the Metropolis-Hastings algorithm to efficiently
sample from a desired probability distributioni for which direct sampling
is difficult.
"""
def __init__(self, target, data, iterations=1000):
"""Instantiate a *Metro... |
f008d73d640609771b8f2aaa149449a10f7706ee | aniroxxsc/Hackerrank-ProblemSolving-Python | /SuperReducedString | 632 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the superReducedString function below.
def superReducedString(s):
for i in range(0,len(s)-1):
if s[i]==s[i+1]:
s1=s[0:i]
if (i+2)<=len(s):
s2=s[i+2:]
else:
... |
fe82e7566405f33f301201bd5cce475c0147d805 | mohasinac/Learn-LeetCode-Interview | /Strings/Count and Say.py | 1,812 | 4.0625 | 4 | """
he count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nt... |
81ff46e99809f962f6642b33aa03dd274ac7a16e | mohasinac/Learn-LeetCode-Interview | /Strings/Implement strStr().py | 963 | 4.28125 | 4 | """
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empt... |
7e558fb4d31490ea5317a9b131c8e022e0504f20 | msam04/Assignment2.2 | /Python_Module2_2.py | 236 | 3.890625 | 4 |
# coding: utf-8
# In[19]:
for i in range (1, 6):
str = "*"
for j in range (1, i):
str = str + "*"
print(str)
length = len(str)
for j in range (1, len(str) + 1):
print(str[:length])
length -= 1
|
885a56023c3b3877e0d2bccf0db93f3c65351b95 | i2mint/stream2py | /stream2py/simply.py | 4,464 | 3.5625 | 4 | """
Helper Function to construct a SourceReader and StreamBuffer in one
Example of usage:
::
from stream2py.simply import mk_stream_buffer
counter = iter(range(10))
with mk_stream_buffer(
read_stream=lambda open_inst: next(counter),
open_stream=lambda: print('open'),
close_strea... |
78ae22f42201983039a2b6aba20195284063b3e4 | andrei10t/AdventOfCode | /AdventOfCode2020/day3.py | 968 | 3.546875 | 4 | def readFile(filename) -> list:
with open(filename, "r") as f:
return [line[:-1] for line in f.readlines()]
def readtest() -> list:
input = list()
with open("test.txt", "r") as f:
for line in f.readlines():
input.append(line)
return input
def part1(file):
counter = ch... |
997f0d32c5609f5e9dac7fb94b933f4e28d64809 | jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO | /exercicio11.py | 410 | 4.15625 | 4 | # 11. Altere o programa anterior para mostrar no final a soma dos números.
# Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01
num1 = int(input("Digite o primeiro número inteiro: "))
num2 = int(input("Digite o segundo número inteiro: "))
for i in range (num1 + 1, num2):
print(i)
for i in range (num2 ... |
2d0c69eabcd187406a0e982cbc343c88d88a26cb | jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO | /exercicio14.py | 601 | 3.96875 | 4 | # 14. Faça um programa que peça 10 números inteiros, calcule e mostre a
# quantidade de números pares e a quantidade de números impares.
# Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01
import math
numero = [[], []]
valor = 10
for c in range(1, 11):
valor = int(input(f"Digite o {c}º valor: "))
... |
16cbb114d0a13ac1c2a25c4be46dd7c14db6584c | Divyendra-pro/Calculator | /Calculator.py | 761 | 4.25 | 4 | #Calculator program in python
#User input for the first number
num1 = float(input("Enter the first number: "))
#User input for the operator
op=input("Choose operator: ")
#User input for the second number
num2 = float(input("Enter the second number:" ))
#Difine the operator (How t will it show the results)
if op == '... |
1f8f158a5528bff42b1eb0876794211096386475 | gruenwalds/geekbrains | /Gruenwald_4_4.py | 396 | 3.921875 | 4 | digits = [int(element) for element in input("Введите числа: ").split()]
even_number = 0
sum_numbers = 0
for counter in digits:
if counter % 2 == 0:
even_number = even_number + counter
for nums in range(1, len(digits), 2):
sum_numbers = sum_numbers + digits[nums]
sum_numbers = sum_numbers + even_... |
006703a80291ab29120be71a5a713a213d8d45bc | DeFeNdog/LeetCode | /arrays_and_strings/first-unique-character-in-a-string.py | 667 | 4.0625 | 4 | '''
## First Unique Character in a String
Given a string, find the first non-repeating character in it and return it's
index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
'''
from coll... |
b7ce6e275957e54ae4a4fd8e70f44a422396cbae | DeFeNdog/LeetCode | /linked_lists/add-two-numbers.py | 2,323 | 3.90625 | 4 | '''
## Add Two Numbers
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their nodes
contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the
... |
8a3f462060774d17383f404bf97467015cd94489 | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex053_detector_de_palindromo.py | 1,157 | 4.15625 | 4 | # Class Challenge 13
# Ler uma frase e verificar se é um Palindromo
# Palindromo: Frase que quando lida de frente para traz e de traz para frente
# Serão a mesma coisa
# Ex.: Apos a sopa; a sacada da casa; a torre da derrota; o lobo ama o bolo;
# Anotaram a data da maratona.
# Desconsiderar os espaços e acentos. Progr... |
51fba057f0a7253f1ad30a5c0d6c38171b888e77 | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex082_dividindo_valores_em_varias_listas.py | 1,188 | 4.03125 | 4 | # Class Challenge 17
# Ler vaios números
# Ter duas listas extras, só com pares e ímpares
# Mostrar as 3 listas
# Dica: Primeiro le os valores, depois monta as outras duas listas
big = list()
par = list()
impar = list()
while True:
big.append(int(input('Enter a number: ')))
resp = ' '
while resp not in '... |
9d82ae750f0a2f3d2531e9832d9e32ae142a67ea | NathanaelV/CeV-Python | /Aulas Mundo 1/aula09_manipulando_texto.py | 4,673 | 4.34375 | 4 | # Challenge 022 - 027
# Python armazena os carcteres de uma string, as letras de uma frase, separadamente
# Python conta os espaços e a contagem começa com 0
# Para exibir um caracter específico só especificar entre []
# Fatiamento
frase = 'Curso em Vídeo Python'
print('\nFATIAMENTO!\n')
print('frase[9]:', fr... |
4d7ae2dfa428ee674fdd151230a36c39c09e7055 | NathanaelV/CeV-Python | /Aulas Mundo 3/aula19_dicionarios.py | 2,623 | 4.21875 | 4 | # Challenge 90 - 95
# dados = dict()
# dados = {'nome':'Pedro', 'idade':25} nome é o identificador e Pedro é o valor
# idade é o identificador e 25 é a idade.
# Para criar um novo elemento
# dados['sexo'] = 'M'. Ele cria o elemento sexo e adiciona ao dicionario
# Para apagar
# del dados['idade']
# print(dados.valu... |
c8ac81bcd8433c0749e3afc2330ff91a325b5180 | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex068_jogo_do_par_ou_impar.py | 1,810 | 3.921875 | 4 | # Class Challenge 15
# Make a game to play 'par ou impar' (even or odd). The game will only stop if the player loses.
# Show how many times the player has won.
from random import randint
c = 0
print('Lets play Par ou Impar')
while True:
comp = randint(1, 4)
np = int(input('Enter a number: '))
rp = str(in... |
1426a37e040bc9a849200f43c5cc612fee91e36e | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex040_aquele_classico_da_media.py | 1,058 | 3.875 | 4 | # Class Challenge 12
# Calcular a média e exibir uma mensagem:
# Abaixo de 5.0 reprovado, entre 5 e 6.9 recuperação e acima de 7 aprovado
cores = {'limpo': '\033[m',
'negrito': '\033[1m',
'vermelho': '\033[1;31m',
'amarelo': '\033[1;33m',
'verde': '\033[1;32m'}
n1 = float(input('Insi... |
c6bd3a2159ebf010f5a9e17f9e1b1c8a968f88f2 | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex005_antecessor_e_sucessor.py | 386 | 4.03125 | 4 |
# Class challenge 007
# Mostrar o antecessor e o sucessor de um numero inteiro
n = int(input('\nDigite Um numero inteiro: '))
a = n - 1
s = n + 1
print('O antecessor do numero {} é {}.'.format(n, a), end=' ')
print('E o sucessor é {}'.format(s))
# Exemplo do professor
n = int(input('Digite um número: '))
print('O a... |
1bc7549e958d98847832cc25cf3ce84a242bb458 | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex027_primeiro_e_ultimo_nome_de_uma_pessoa.py | 421 | 3.9375 | 4 | # Class Challenge 09
# Ler o nome completo de uma pessoa e mostar o primeiro e o último
nome = str(input('Digite o seu nome completo: ')).strip()
a = nome.split()
print('O primeiro nome é {} e o último é {}'.format(a[0], a[0]))
# Exemplo do Professor
print('\nExemplo do Professor\n')
print('Olá, muito prazer.')
pri... |
8ca33acd165cec49c7c84b75394da1cf6b7d1f0d | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex090_dicionario_em_python.py | 930 | 3.84375 | 4 | # Class Challenge 19
# Read name and media of several students
# Show whether the student has failed or passed
student = dict()
na = str(input('Enter the student name: '))
m = float(input('Enter the student media: '))
student['name'] = na
student['media'] = m
if m >= 7:
student['Situation'] = 'Aprovado'
elif 5 <=... |
1e8dc17f6182d9c87f9c60a56e49021c5c4c7114 | NathanaelV/CeV-Python | /Modulos Curso em Video/ex107_exercitando_modulos_em_python.py | 499 | 3.828125 | 4 | # Class Challenge 22
# Criar um módulo chamado moeda.py
# Ter as funções aumentar() %; diminuir() %; dobrar() e metade()
# Fazer um programa(esse) que importa e usa esses módulos
# from ex107 import moeda
from ex107 import moeda
num = float(input('Enter a value: '))
print(f'Double of {num} is {moeda.dobrar(num)}')
p... |
ee8ebbe66eaae522f183e71a96c5b6bf218b34ad | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex031_custo_da_viagem.py | 538 | 3.84375 | 4 | # Class Challenge 10
# Calcular o preço da passagem de ônibus
# R$ 0,50 para viagens até 200 km
# R$ 0,45 para viages acima de 200 km
d = int(input('Qual a distância da sua viagem? '))
if d <= 200:
p = d * 0.5
else:
p = d * 0.45
print('O preço da sua passagem é R$ {:.2f}'.format(p))
# Exemplo do professor
... |
d76dc80b873a755892779f45844e57ce177ac511 | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex088_palpites_para_a_mega_sena.py | 1,652 | 4.0625 | 4 | # Class Challenge 18
# Ask the user how many guesses he wants.
# Draw 6 numbers for each guess in a list.
# In a interval between 1 and 60. Numbers can't be repeated
# Show numbers in ascending order.
# To use sleep(1)
from random import randint
from time import sleep
luck = list()
mega = list()
print('=' * 30)
pri... |
8ea4a1eae9758fac4e17895d3a290b4b5b7e56bf | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex024_verificando_as_primeiras_letras_de_um_texto.py | 839 | 4.0625 | 4 | # Class Challenge 09
# Ler o nome da Cidade e ver se começa com a palavra 'Santo'
cidade = input('Digite o nome da sua cidade: ')
minusculo = cidade.lower().strip().split()
# primeira = minu.strip()
# p = primeira.split()
print('Essa cidade tem a palavra santo?: {}'.format('santo ' in minusculo))
print('Santo é a pri... |
8e28da8e0eb769a6a9735bb6edf36567011b2a0a | NathanaelV/CeV-Python | /Aulas Mundo 3/aula20_funçoes_parte1.py | 1,450 | 4.1875 | 4 | # Challenge 96 - 100
# Bom para ser usado quando um comando é muito repetido.
def lin():
print('-' * 30)
def título(msg): # No lugar de msg, posso colocar qualquer coia.
print('-' * 30)
print(msg)
print('-' * 30)
print(len(msg))
título('Im Learning Python')
print('Good Bye')
lin()
def soma(... |
560596b12e9cda1ebdadfb4ab2b5c945ad0265d1 | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex103_ficha_do_jogador.py | 1,173 | 4.21875 | 4 | # Class Challenge 21
# Montar a função ficha():
# Que recebe parametros opcionais: NOME de um jogador e quantos GOLS
# O programa deve mostrar os dados, mesmo que um dos valores não tenha sido informado corretamente
# jogador <desconhecido> fez 0 gols
# Adicionar as docstrings da função
def ficha(name='<unknown>', go... |
f1f9c6ff93b2e33c013618b98735aa2c128f980f | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex051_progressao_aritimetica.py | 300 | 3.859375 | 4 | # Class Challenge 13
# Ler o primeiro termo e a razão da P.A. e mostrar os 10 primeiros números
print('{:=^40}'.format(' 10 TERMOS DE UMA PA '))
t = int(input('Digite o 1º termo: '))
r = int(input('Digete a razão da PA: '))
for a in range(t, t + 10*r, r):
print(a, end=', ')
print('\nFim!')
|
143b16bde692bfc1ace62443b270d9dd50d8185c | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex003b.py | 357 | 4.09375 | 4 | # Class Challenge 006
# Para números Inteiros
a = int(input('Digite um número: '))
b = int(input('Digete outro número: '))
c = a + b
print('A soma entre {} e {} é: {}'.format(a, b, c))
#Para números Reais
d = float(input('Digite um número: '))
e = float(input('Digite outro número: '))
f = d + e
print('A soma entre {}... |
c0f6d267dcdcd1a2dc364976bb815a9e7a524cb9 | arjngpta/miscellaneous | /experiment.py | 239 | 3.5625 | 4 | import os
i = 0
n = [1,2,3]
file_list = os.listdir(os.getcwd())
for file_name in file_list:
i = i + 1
if i in n:
print "i is in n"
else:
print "i is not in n"
print i
print n
|
090e9e030c462324d39a04eab7f05a2e44e2c8a9 | Scuba-Chris/game_of_greed | /game_of_greed.py | 3,808 | 3.53125 | 4 | import random
from collections import Counter
import re
class Game:
def __init__(self, _print=print, _input=input):
self._print = print
self._input = input
# self._roll_dice = roll_dice
self._round_num = 10
self._score = 0
self.rolled = []
self.keepers = [... |
5d86ca4b127b79be2a7edc2a93e45dfc0502ccd7 | JiJibrto/lab_rab_12 | /individual2.py | 1,358 | 4.34375 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# Реализовать класс-оболочку Number для числового типа float. Реализовать методы
# сложения и деления. Создать производный класс Real, в котором реализовать метод
# возведения в произвольную степень, и метод для вычисления логарифма числа.
import math
class Number:
... |
c1ab809f56fb6edf4827b1978bdb32bc9b7bb532 | nickolasbmm/lista2ces22 | /ex11.py | 550 | 3.78125 | 4 | #Function with argument list
def square_sequence(*arglist):
print("Squared sequence: ",end="")
for x in arglist:
print("{} ".format(x**2),end="")
print("")
print("Example function with argument list")
print("Initial sequence: 1 2 3 4 5")
square_sequence(1,2,3,4,5)
#Functio with argument dictionary
... |
b765209f2c2fc302496ec89993d73d87e2d80d56 | rbngtm1/Python | /data_structure_algorithm/array/Plus_0ne.py | 464 | 3.90625 | 4 | given_array = [1, 2, 3, 4, 5]
# length = len(given_array)-1
#print(length)
# for i in range(0, len(given_array)):
# #print(i)
# if i==length:
# given_array[i]=given_array[i]+1
# else:
# given_array[i]=given_array[i]
# print(given_array)
############################################
m... |
0036738f5c4ebd10ed148ed836ff304ead8b66f0 | rbngtm1/Python | /data_structure_algorithm/array/contains_duplicate.py | 374 | 3.96875 | 4 | array = [1,2,3,4]
my_array = []
# for i in array:
# if i not in my_array:
# my_array.append(i)
# if array == my_array:
# print('false')
# else:
# print('true')
def myfunc():
for i in range(len(array)):
if array[i] in my_array:
return True
else:
my_array.... |
c80bffe95bc94308989cec03948a4a91239d13aa | rbngtm1/Python | /data_structure_algorithm/array/remove_duplicate_string.py | 398 | 4.25 | 4 | # Remove duplicates from a string
# For example: Input: string = 'banana'
# Output: 'ban'
##########################
given_string = 'banana apple'
my_list = list()
for letters in given_string:
if letters not in my_list:
my_list.append(letters)
print(my_list)
print (''.join(my_list))
## poss... |
ee2da66a029f7bc9afad26c6025573e21bea8ae9 | gyeongchan-yun/useful-python | /threading_event_queue.py | 679 | 3.515625 | 4 | import threading
from queue import Queue
evt_q = Queue()
def func():
number = int(threading.currentThread().getName().split(":")[1])
if (number < 2):
evt = threading.Event()
evt_q.put(evt)
evt.wait()
for i in range(10):
print ("[%d] %d" % (number, i))
if (number > 2)... |
1984969edc15b4e08db867aae9241e40ad8ff8ec | AbdAyyad/opensouq | /opensouqback/stringsapp/hamming_distance.py | 546 | 3.671875 | 4 | class hamming_distance:
def __init__(self, first_string, second_string):
self.first_string = first_string
self.second_string = second_string
self.initlize_disance()
def initlize_disance(self):
self.distance = 0
for i in range(len(self.first_string)):
if self.... |
30e54e336c427637344711d8f9646d2b1fd6d43e | wendyzou02/python-test | /demolib.py | 147 | 3.953125 | 4 | def sum_even(start_num, end_num):
sum = 0
for x in range( start_num, end_num+1 ):
if x%2==0:
sum += x
return sum
|
bee174e6985d80c2a2cceb86590b5db9dbc00af6 | ingridcoda/knapsack-problem | /src/model.py | 575 | 3.578125 | 4 | class Item:
def __init__(self, size, value):
self.size = size
self.value = value
def __str__(self):
return f"{self.__dict__}"
def __repr__(self):
return self.__str__()
class Knapsack:
def __init__(self, size=0, items=None):
self.size = size
self.items ... |
d2b48f3f46963d6b8a07c766acd0475e6adb4487 | jbloom04/python-test | /functions.py | 193 | 3.546875 | 4 |
batteries=[1,3,7,5]
def light(batt1,batt2):
# if batt1 % 2 == 0 and batt2 % 2 == 0:
if batt1 in batteries and batt2 in batteries:
return True
else:
return False
|
342c9e28fead18d6fc82c40892f6743b1926564a | sofieditmer/cds-visual | /assignments/assignment3_EdgeDetection/edge_detection.py | 4,205 | 3.578125 | 4 | #!/usr/bin/env python
"""
Load image, draw ROI on the image, crop the image to only contain ROI, apply canny edge detection, draw contous around detected letters, save output.
Parameters:
image_path: str <path-to-image-dir>
ROI_coordinates: int x1 y1 x2 y2
output_path: str <filename-to-save-results>
Usage:... |
bed107a24a36afeb2176c3200aec2c525a24a55a | Silicon-beep/UNT_coursework | /info_4501/home_assignments/fraction_class/main.py | 1,432 | 4.21875 | 4 | from fractions import *
print()
#######################
print('--- setup -----------------')
try:
print(f'attempting fraction 17/0 ...')
Fraction(17, 0)
except:
print()
pass
f1, f2 = Fraction(1, 2), Fraction(6, 1)
print(f'fraction 1 : f1 = {f1}')
print(f'fraction 2 : f2 = {f2}')
####################... |
04dbc79957d16af67ab89c8aa72796517db8b5a6 | madboy/adventofcode | /2015/days/twelve.py | 734 | 3.78125 | 4 | #!/usr/bin/env python
import fileinput
import json
def count(numbers, ignore):
if type(numbers) == dict:
if ignore and "red" in numbers.values():
return 0
else:
return count(numbers.values(), ignore)
elif type(numbers) == list:
inner_sum = 0
for e in numb... |
c1f76fc8405ea15ec3d9112ff8efc51c5801fcb5 | Nduwal3/Python-Basics-III | /academy-cli/academy/student.py | 2,517 | 3.703125 | 4 | import csv
class Student:
def __init__(self):
# this.mode = mode
# this.data = data
pass
def file_read_write(self, mode, data=None):
with open ('files/students.csv', mode) as student_data:
result=[]
if mode == 'r':
stude... |
7413ffdb53524a72e59fae9138e1b143a9a2e046 | quanghona/Caro2 | /board.py | 3,919 | 3.515625 | 4 | import os
import curses
import random
class CaroBoard(object):
"""A class handle everything realted to the caro board"""
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [[' ' for x in range(self.width)] for y in range(self.height)]
self._turnCount = 0
def ConfigBoar... |
23aeff17e64ba6acfdcf8c85ae0dab9ae2ebf676 | divanescu/python_stuff | /coursera/webd/func_assn42.py | 926 | 3.765625 | 4 | # Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program
import urllib
from BeautifulSoup import *
global url
url = raw_input('Enter - ')
position = int(raw_input('Position: '))
def retrieve_url(url):
#url = raw_inpu... |
3474489ac3abf4439f4af04a6f2a69a743e168d6 | divanescu/python_stuff | /coursera/PR4E/assn46.py | 348 | 4.15625 | 4 | input = raw_input("Enter Hours: ")
hours = float(input)
input = raw_input("Enter Rate: ")
rate = float(input)
def computepay():
extra_hours = hours - 40
extra_rate = rate * 1.5
pay = (40 * rate) + (extra_hours * extra_rate)
return pay
if hours <= 40:
pay = hours * rate
print pay
elif hours >... |
a15be41097001cf7f26c42b7dbb076e8ed2bf45c | divanescu/python_stuff | /coursera/PR4E/assn33.py | 347 | 3.84375 | 4 | input = raw_input("Enter Score:")
try:
score = float(input)
except:
print "Please use 0.0 - 1.0 range !"
exit()
if (score < 0 or score > 1):
print "Please use 0.0 - 1.0 range !"
elif score >= 0.9:
print "A"
elif score >= 0.8:
print "B"
elif score >= 0.7:
print "C"
elif score >= 0.6:
prin... |
17d4df0314c967d5cb2192b274b40cf8c3abd248 | Eladfundo/task_1_18 | /Code/nnet/wbg.py | 1,412 | 3.625 | 4 | import torch
def weight_initialiser(N_prev_layer,N_current_layer,device='cpu'):
"""
Initializes the weight in the constructor class as a tensor.
The value of the weight will be w=1/sqr_root(N_prev_layer)
Where U(a,b)=
Args:
N_prev_layer: Number of element in t... |
a6dd4e5cf972068af342c8e08e10b4c7355188e6 | DivyaRavichandr/infytq-FP | /strong .py | 562 | 4.21875 | 4 | def factorial(number):
i=1
f=1
while(i<=number and number!=0):
f=f*i
i=i+1
return f
def find_strong_numbers(num_list):
list1=[]
for num in num_list:
sum1=0
temp=num
while(num):
number=num%10
f=factorial(numbe... |
fa798298cb31dce23c22393e07eaa94e0bb0a655 | DivyaRavichandr/infytq-FP | /ticketcost.py | 511 | 3.765625 | 4 | def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
ticket_amount=0
Rate_per_adult=37550
Rate_per_child=37550/3
ticket_amount=(no_of_adults*Rate_per_adult)+(no_of_children*Rate_per_child)
service_tax=0.07*ticket_amount
total_cost=ticket_amount+service... |
c60d478bce2ff6881160fa2045b2d10860d2730f | DivyaRavichandr/infytq-FP | /sumofdigits.py | 131 | 3.765625 | 4 | def sumofnum(n):
sum=0
while(n!=0):
sum=sum+int(n%10)
n=int(n/10)
return sum
n=int(input(""))
print(sumofnum(n))
|
4f7fdbff2edfa799c9db9ff345873be308face22 | anfauglit/recursion | /prntstr.py | 1,834 | 3.875 | 4 | import random
def print_str(n):
# decompose the integer n and prints its digits one by one
if n < 0:
print('-',end='')
print_str(-n)
else:
if n > 9:
print_str(int(n / 10))
print(n % 10, end='')
def digitsum(n):
# calculate the sum of all its digits
if n < 0:
return digitsum(-n)
else:
if n > 0:
... |
d9f949f598d68412fa4035e6fe8b613d006b4dc3 | AlfredKai/KaiCodingNotes | /LeetCode/Easy/Power of Three.py | 392 | 3.703125 | 4 | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
powOf3 = 3
while powOf3 <= n:
if powOf3 == n:
return True
powOf3 *= 3
return False
a = Solution()
print(a.isPowerOfThree(27))
print(a.isP... |
67b9abf27cf5751ad6b1085fe81235d4b5880d64 | AlfredKai/KaiCodingNotes | /LeetCode/Medium/328. Odd Even Linked List.py | 1,258 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
... |
d31c7945dae63c6f6aff2d57588108bcbc3e492e | AlfredKai/KaiCodingNotes | /LeetCode/Hard/1044. Longest Duplicate Substring.py | 1,255 | 3.625 | 4 | from collections import Counter
class Solution:
def longestDupSubstring(self, S: str) -> str:
def check_size(size):
hash = set()
hash.add(S[:size])
for i in range(1, len(S) - size + 1):
temp = S[i:i+size]
if temp in hash:
... |
14dfc412b8f990b71480104de064457d69f91493 | AlfredKai/KaiCodingNotes | /LeetCode/Medium/Construct Binary Tree from Preorder and Inorder Traversal.py | 1,146 | 3.8125 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder) == 0:
... |
2ecc33dd88220ed4fe133c1260a92bb34a872e5d | AlfredKai/KaiCodingNotes | /LeetCode/Contests/185/1418. Display Table of Food Orders in a Restaurant.py | 1,306 | 3.921875 | 4 | from typing import List
class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
# ["David","3","Ceviche"]
foods = set()
tableNum = set()
tableDish = {}
for order in orders:
tableN = int(order[1])
if (tableN, order... |
72db36b3000749d043e69702b38ef7c345cc99ef | mathtenote01/python | /triple_step.py | 334 | 3.765625 | 4 | def pattern_of_triple_step(N: int):
if N < 0:
return 0
elif N == 0:
return 1
else:
return (
pattern_of_triple_step(N - 1)
+ pattern_of_triple_step(N - 2)
+ pattern_of_triple_step(N - 3)
)
if __name__ == "__main__":
print(pattern_of_tr... |
ccc3586c6e51d05a034f6f02781b0e307ae3a93e | Mariliacaps/teste-python | /CAP05/EXERCICIO05-13.py | 747 | 3.75 | 4 | divida=float(input("Valor da dívida: "))
taxa=float(input("Taxa de juros mensal (Ex.: 3 para 3%):"))
pagamento=float(input("Valor a ser pago mensal: "))
mes=1
if (divida*(taxa/100)>= pagamento):
print("O juros são superiores ao pagamento mensal.")
else:
saldo = divida
juros_pago=0
while saldo>pagamento:... |
763f30a67c364954d0b3539145857295a684329f | Mariliacaps/teste-python | /CAP03/EXERCICIO3-7.py | 264 | 3.890625 | 4 | #programa que peça 2 numeros inteiros e imprima a soma dos 2 numeros na tela
numero01=int(input("Digite o primeiro numero: "))
numero02=int(input("Digite o segundo numero: "))
resultado=numero01+numero02
print(f"o resultado da soma dos numeros é: {resultado} ")
|
5703e7ab721d71cb537c3eb659ea65352c81d4d1 | Mariliacaps/teste-python | /CAP04/programa4-3.py | 281 | 4.09375 | 4 | salario=float(input("Digite o salario para o calculo do imposto: "))
base=salario
imposto=0
if base>3000:
imposto=imposto+((base-3000)*0.35)
base=3000
if base>1000:
imposto=imposto+((base-1000)*0.20)
print(f"salario: R${salario:6.2f} imposto a pagar: R${imposto:6.2f}") |
be1ae90fe39e8bfdc0b0bc64ab50ba9c62650c8e | tobetobe/python_start | /hello.py | 504 | 4 | 4 | # for index, item in enumerate(['a', 'b', 'c']):
# print(index, item)
def printHello():
""" say Hello to the console
Just print a "hello
"""
print("hello")
# printHello()
# list = ['bca', 'abc', 'ccc']
# sorted(list)
# print(list)
# list = [v*2 for v in range(1, 10)]
# print(list)
list = ['... |
580a0daea555236dcc97ca069180fc26d3cb1093 | yangtuothink/Python_AI_note | /other_add/sock(key=) demo.py | 372 | 4 | 4 | """
sort() 函数内含有 key 可以指定相关的函数来作为排序依据
比如这里指定每一项的索引为1 的元素作为排序依据
默认是以第一个作为排序依据
"""
def func(i):
return i[1]
a = [(2, 2), (3, 4), (4, 1), (1, 3)]
a.sort(key=func) # [(4, 1), (2, 2), (1, 3), (3, 4)]
# a.sort() # [(1, 3), (2, 2), (3, 4), (4, 1)]
print(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.