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 |
|---|---|---|---|---|---|---|
118b18a4dd6a0aa5691499849adb54b709adca77 | itaicaspi/AI | /HW2/amazons/min_distance.py | 4,261 | 3.765625 | 4 | import amazons_board
from time import clock
def timed(f):
'''decorator for printing the timing of functions
usage:
@timed
def some_funcion(args...):'''
def wrap(*x, **d):
start = clock()
res = f(*x, **d)
print(f.__name__, ':', clock() - start)
return res
return ... |
a3901eb63e3a2184fcd76eb7fd8f3e1c025e9185 | eclam/study_review | /online_assessments/hackerrank/regex/matching-one-or-more-repititions.py | 221 | 3.78125 | 4 | # Source: https://www.hackerrank.com/challenges/matching-one-or-more-repititions/problem
import re
# Source:
Regex_Pattern = r'^\d+[A-Z]+[a-z]+$'
# Given Code:
print(str(bool(re.search(Regex_Pattern, input()))).lower())
|
7bc85cb70b9618792bb1bdb21012f07bd788514c | eclam/study_review | /online_assessments/leetcode/python/uniqueNumOfOccurences.py | 1,060 | 3.546875 | 4 | # Source: https://leetcode.com/problems/unique-number-of-occurrences/
from typing import List
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
myDict = {}
for i in arr:
if myDict.get(str(i)):
myDict[str(i)] += 1
else:
myDict... |
295e224afbf70eb6128a0bc5783f8b96849d699d | eclam/study_review | /online_assessments/hackerrank/regex/alternative-matching.py | 232 | 3.765625 | 4 | # Source: https://www.hackerrank.com/challenges/alternative-matching/problem
import re
# Solution:
Regex_Pattern = r'^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)[a-zA-Z]+$'
# Given Code:
print(str(bool(re.search(Regex_Pattern, input()))).lower())
|
15fefd3350dcc2b623d1a211e559daee5f6eec6d | eclam/study_review | /online_assessments/leetcode/python/reverseString.py | 828 | 3.703125 | 4 | # Source: https://leetcode.com/problems/reverse-string/
from typing import List
class Solution:
def unoptimalSoln_reverseString(self, s: List[str]) -> None:
s_prime = s[::-1]
for idx, val in enumerate(s_prime):
s[idx] = val
def reverseString(self, s: List[str]) -> None: # Made this ... |
0e30ae9206721354903be154338ed8fdbcdf1af4 | weissxu/python_test | /weiss/methos_test.py | 251 | 3.734375 | 4 | from functools import reduce
def power(x):
return x * x
f = power
r = map(f, range(5))
for k in r:
print(k)
print('===============')
def fn(x, y):
return x * 10 + y
reduce_num = reduce(fn, range(5))
print('reduce: ', reduce_num)
|
90b6e8bb555449c804981247b95f1f4e0994203d | weissxu/python_test | /weiss/sqllite_test.py | 811 | 3.578125 | 4 | import sqlite3
try:
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute('create table user(id int primary key,name varchar(64))')
cursor.execute('insert into user values(1,"siwei")')
print(cursor.rowcount)
cursor.execute('insert into user values(?,?)', (2, 'mike'))
except B... |
a6142846998f42277f231d8af2130c7b6cd80368 | weissxu/python_test | /weiss/jsontet.py | 699 | 3.75 | 4 | class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return 'student name: %s, score: %s' % (self.name, self.score)
__repr__ = __str__
def printscore(self):
print(self.score)
def __call__(self, *args, **kwa... |
8c3d94a63e05c32af5b53829a14902bd494a583b | tigerjoy/SwayamPython | /cw_2021_06_12/nprime.py | 367 | 3.78125 | 4 | def is_prime(number):
fact_count = 2
for i in range(2,number):
if(number%i==0):
fact_count+=1
# condition = true, ret = true
# condition = false, ret = false
return(fact_count==2)
def nprime(count):
num=2
while(True):
if(is_prime(num)):
print(num,end=",")
count=count-1
num=n... |
d8d8b40759b3774786500074dffc142360943b93 | tigerjoy/SwayamPython | /cw_2021_06_19/hcf_q16.py | 252 | 3.921875 | 4 | def hcf(divisor,dividend):
if dividend%divisor==0:
return(divisor)
else:
return (hcf(dividend%divisor,divisor))
num1=int(input("Enter a number:"))
num2=int(input("Enter a number:"))
print("HCF of", num1 ,"and",num2 ,"is",hcf(num1,num2)) |
465b774801fab916d105055df2974fce9324360c | tigerjoy/SwayamPython | /old_programs/cw_2020_08_01/multipy_5_q4.py | 50 | 3.609375 | 4 | i=1
while(i<=10):
print("5 x",i,"=",i*5)
i=i+1 |
a86289aad3e4934769c3d47b84c367b6789e0610 | tigerjoy/SwayamPython | /old_programs/cw_2020_08_08/range_q3.py | 257 | 4.03125 | 4 | lb=int(input("enter lower bound: "))
ub=int(input("enter upper bound: "))
print("Numbers are in ascending order:")
for i in range(lb,ub+1):
print(i,end=",")
print("\nNumbers are in desending order:")
for i in range(ub,lb-1,-1):
print(i,end=",")
|
aec85ea6f687ec7516c577d5ddd58ed90f72e18f | tigerjoy/SwayamPython | /old_programs/cw_17_06_20/year.py | 471 | 4.15625 | 4 | year=int(input("enter year :"))
if year%100==0:
print("it is a centennial year")
if year%400==0:
print("it is a leap year")
else:
print("it is not a leap year")
elif year%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
# Alternative
# if (year % 100 == 0) and (year % 400 == 0):... |
571a5322ed3b18be4a319ffa3a14a9541b6f08d3 | tigerjoy/SwayamPython | /old_programs/cw_2021_01_16/dictionary_exercise.py | 639 | 4.1875 | 4 | dict_users={}
for i in range(1,11):
# Enter username of user 1:
username=input("Enter username of user {}:".format(i))
password=input("Enter password of user {}:".format(i))
dict_users[username]=password
print("Enter log in details:")
username=input("Enter username of user :")
password=input("Enter password o... |
42f1f36beba414210ebd044deeef30d576f3bf37 | tigerjoy/SwayamPython | /old_programs/cw_08_07_20/quadratic.py | 233 | 3.875 | 4 | a=float(input("enter the value of a: "))
b=float(input("enter the value of b: "))
c=float(input("enter the value of c: "))
discriminant=b**2-(4*a*c)
if discriminant>=0:
print("Roots are real")
else:
print("Roots are imaginary") |
40f740939d2a1c486e2d189bfdc1094faa59fa37 | tigerjoy/SwayamPython | /old_programs/hw_2020_08_08/range_sq_q5.py | 113 | 3.734375 | 4 | lb=int(input("enter lower bound: "))
ub=int(input("enter upper bound: "))
for i in range(lb,ub+1):
print(i*i)
|
1448f5e1bf322f266cb52fc4c3aaa34cd50096d3 | tigerjoy/SwayamPython | /cw_2021_05_08/map1_with_map.py | 159 | 3.890625 | 4 | def square(num):
return num ** 2
nums = [1,2,3,4,5]
squared = list(map(square, nums))
print("Original List:", nums)
print("Transformed List:", squared)
|
119d817dbd33ac3ef5d06e8956d80acb32fc7f94 | tigerjoy/SwayamPython | /old_programs/cw_2021_02_06/string_exercise/q7.py | 104 | 3.9375 | 4 | word=input("Enter a word: ")
new_word=word[1:]+word[0]+"ay"
print("Twisted pig latin word is",new_word)
|
c0210eb01ae2d0bc684b02c165b3da9ece3d8f27 | tigerjoy/SwayamPython | /cw_2021_05_13/passing_of_params_3.py | 264 | 3.71875 | 4 | def func3(arr):
print("Inside function")
print("Value received in arr:", arr)
arr.pop()
arr.append(6)
print("Value of arr after changes:", arr)
arr = [1,2]
print("Before calling func2(), arr=", arr)
func3(arr)
print("After calling func2(), arr=", arr)
|
6058ec01c170a5d4a5896820cdb09f09a36b14e8 | tigerjoy/SwayamPython | /old_programs/cw_08_07_20/grade.py | 277 | 4.03125 | 4 | marks = float(input("Enter average marks of the student: "))
if (marks>=90):
print("Grade : A")
elif (marks>=80):
print("Grade : B")
elif (marks>=70):
print("Grade : C")
elif (marks>=60):
print("Grade : D")
elif (marks>=50):
print("Grade : E")
else:
print("Fail")
|
3cbb7df3a6fed8cfabefe75ecd3cdc31e38ff55e | tigerjoy/SwayamPython | /cw_2021_05_13/filter1_with_filter.py | 283 | 3.796875 | 4 | def iseven(num):
return(num%2==0)
def isodd(num):
return(num%2==1)
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 19]
even = list(filter(iseven, nums))
odd = list(filter(isodd, nums))
print("Original List:", nums)
print("Filtered Even List:", even)
print("Filtered Odd List:", odd)
|
3b51f2f0f0267366f5c1b246267ca3c10105cf9b | tigerjoy/SwayamPython | /old_programs/cw_2021_01_16/list_exercise.py | 623 | 4.15625 | 4 | list1 = []
list2 = []
size1 = int(input("Enter the size of list 1: "))
print("Enter elements in list 1")
for i in range(size1):
item = int(input("Enter element {}: ".format(i + 1)))
list1.append(item)
size2 = int(input("Enter the size of list 2: "))
print("Enter elements in list 2")
for i in range(size2):
ite... |
04252c8b0c9637d2b8440ae6049e59fdd488d06c | tigerjoy/SwayamPython | /cw_2021_05_13/passing_of_params_4.py | 272 | 3.515625 | 4 | def func4(arr):
print("Inside function")
print("Value received in arr:", arr)
new_list = [5,6]
arr = new_list
print("Value of arr after changes:", arr)
arr = [1,2]
print("Before calling func2(), arr=", arr)
func4(arr)
print("After calling func2(), arr=", arr)
|
e75b96c49baded7f0a3ef9f6a9de37b8bc048389 | tigerjoy/SwayamPython | /cw_2021_05_29/reverse_q8.py | 283 | 3.890625 | 4 | import math
def reverse(n):
if(0<=n<=9):
return(n)
else:
x = math.floor(math.log10(n))
return((n%10)*(10**x)+reverse(n//10))
a=int(input("Enter the number:"))
# The reverse of 1769 is 9671
print("The reverse of ",a,"is",reverse(a)) |
edb846aa3c266cbf254b1d41fbac8f00ec70f825 | tigerjoy/SwayamPython | /cw_2021_07_13/dec2oct.py | 193 | 3.984375 | 4 | def dec2oct(num):
if(num==0):
return("0")
else:
return(dec2oct(num//8)+str(num%8))
num=int(input("Enter a number:"))
# (8)10 = (10)8
print("(", num ,")10 = (",dec2oct(num),")8") |
09f3a586358f6e9725d9cb93d62a05625ce7ed1f | tigerjoy/SwayamPython | /cw_2021_05_13/filter1_with_lambda.py | 237 | 3.96875 | 4 | nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 19]
even = list(filter(lambda num:num%2==0, nums))
odd = list(filter(lambda num:num%2==1, nums))
print("Original List:", nums)
print("Filtered Even List:", even)
print("Filtered Odd List:", odd)
|
12d9d1eb684dad8946f5c66c30eb5faec45c3f72 | tigerjoy/SwayamPython | /old_programs/cw_2020_10_22/list_q15.py | 264 | 4.34375 | 4 | size=int(input("Enter size of a list:"))
arr=[]
for i in range(0,size):
item=int(input("Enter element {}:".format(i+1)))
arr.append(item)
largest=arr[0]
for i in range(1,size):
if(arr[i]>largest):
largest=arr[i]
print("Largest element is:",largest) |
36b38fa452daf1bdf0a3ea0ec9ee795acb05c3e3 | tigerjoy/SwayamPython | /cw_2021_05_13/passing_of_params_2.py | 250 | 3.765625 | 4 | def func2(arr):
print("Inside function")
print("Value received in arr:", arr)
arr[0] += 2
print("Value of arr after changes:", arr)
arr = [1,2]
print("Before calling func2(), arr=", arr)
func2(arr)
print("After calling func2(), arr=", arr)
|
2cc2a7b4d5e441bdd774cdd94d14d54257b2c91e | tigerjoy/SwayamPython | /old_programs/cw_2020_10_22/list_q16.py | 269 | 4.25 | 4 | size=int(input("Enter size of a list:"))
arr=[]
for i in range(0,size):
item=int(input("Enter element {}:".format(i+1)))
arr.append(item)
smallest=arr[0]
for i in range(1,size):
if(arr[i]<smallest):
smallest=arr[i]
print("smallest element is:",smallest) |
cb7ec04d9e47007ae26eb6a0dbeddf298c13ce90 | tigerjoy/SwayamPython | /cw_2021_06_19/sum_factor_q11.py | 253 | 4.1875 | 4 | def sum_of_factor(num,f=1):
if f>num//2:
return(num)
elif(num%f==0):
return (f+sum_of_factor(num,f+1))
else:
return (sum_of_factor(num,f+1))
num=int(input("Enter a number:"))
print("Sum of factors of", num ,"is",sum_of_factor(num)) |
b9ee20a7dc0189b8f203c1eeaa8c21c8450e1b47 | pranaysathu/pythonTraining | /exceptions.py | 570 | 3.828125 | 4 | class ValueTooSmall(Exception):
pass
num=1; scores={}; score=[]
while num !=-1 :
try:
num = int(input("Enter Number:"))
if 1 == num:
10/0
elif 2 == num:
scores["sa"]
elif 3 == num:
print(sachine)
elif 4 == num:
import KeyboardInterrupt
elif 5 == num:
print(score[1])
elif -2 == num:
r... |
2bfc5e5f0621189e58a1ada49db23445a6ae8025 | pranaysathu/pythonTraining | /swap.py | 74 | 3.578125 | 4 | list = [10,20]
def swap(l):
l[0],l[1]=l[1],l[0]
swap(list)
print(list) |
c76e0f17f031ce92daa8fab6a119f50bae3aef62 | phzsantos/Playing_with_Python | /03-MoedasFalsas/MoedasFalsas.py | 1,901 | 4 | 4 | # ------------------------------------ NOTAS ------------------------------------
print('Enunciado: \nVocê tem 5 moedas, uma delas é falsa, e a falsa tem o peso menor que as outras. Desenvolva uma regra para fazer o minimo numero de pesagens e descobrir a falsa (tem como resolver com 2 pesagens)')
print('\nNOTA! \nEs... |
4f410d916db3037ff710098ee28663c3558c958b | xingzhicn/MyLeetCode | /hard/正则表达式匹配.py | 979 | 3.8125 | 4 | class Solution:
"""
示例 4:
输入:s = "aab" p = "c*a*b"
输出:true
解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
示例 5:
输入:s = "mississippi" p = "mis*is*p*."
输出:false
"""
def isMatch(self, s: str, p: str) -> bool:
# dp = [False]*len(s)
i = 0
j = 0
... |
b041ec2bc5e3b76d1091c38091ae7d4558ea72f3 | xingzhicn/MyLeetCode | /medium/2. 两数相加.py | 1,741 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 ->... |
87dc9b2852a2c2f61af3b1a461844884f33aa264 | Norcinu/CricketScraper | /player.py | 663 | 3.515625 | 4 | class Player(object):
name = ""
country = ""
average = 0.00
matches = 0
def __init__(self):
self.name = "Cricket Player"
self.country = "None"
self.average = 0.00
self.matches = 0
def print_info(self):
print "Name: {}, Country {}, Played {}, Average {}."... |
d65345905b668ebf18c1c8ddec85f04f856304b6 | bac2qh/Machine_Learning | /Assignment_3/read_files.py | 440 | 3.53125 | 4 | import os
import pandas as pd
def read(file_name):
path = 'data/'+ file_name
ext = os.path.splitext(path)[-1].lower()
# for csv files
if ext == ".csv":
df = pd.read_csv(path)
# for xls files
elif ext == ".xls":
df = pd.read_excel(path)
elif ext == ".xlsx":
df = pd.re... |
d9f334bd9360012b9fd6479a8e2549a08f60b2d9 | anican/CIBL | /cibl.py | 5,280 | 3.796875 | 4 | ## CIBL Interpreter in Python
## process: program -> PARSER -> abstract syntax tree -> EVAL -> result
#### import modules
from __future__ import division
import math
import operator as op
#### Types
Symbol = str
List = list
Number = (float, int)
#### Parsing : parser, tokenizer, reading from tokens
def parse(pro... |
11e1186d3726740d52adb68d2df197c4466c2efa | larissapaiva/Exerc_Python1 | /ex024.py | 205 | 3.828125 | 4 | # AULA 9 - Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome “SANTO”.
nome = str(input('Digite o nome da sua cidade: ')).strip().upper()
print(nome[:6] == 'SANTO')
|
63ad1a8fcf66d6b12d8ca22f9113db7f9ebe75e4 | larissapaiva/Exerc_Python1 | /ex017.py | 437 | 4.0625 | 4 | # AULA 8 - Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo,
# calcule e mostre o comprimento da hipotenusa.
# h = (co ** 2 + ca ** 2)**(1/2) // uma forma de ser feito
from math import hypot
co = float(input('Digite o valor do cateto oposto: '))
ca = float(input(... |
df0c6c8d99745babe6c2aa86b12ee313005e0789 | larissapaiva/Exerc_Python1 | /ex033.py | 453 | 4.03125 | 4 | # AULA 10 - Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))
menor = n1
maior = n3
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
m... |
be5c68dffa964c0eea09aa1cfe92cb9c8efd2e5d | KocUniversity/comp100-2021f-ps0-alpersahin21 | /main.py | 182 | 3.515625 | 4 | import numpy as np
x = int(input("Enter number x: "))
y = int(input("Enter number y: "))
z = x**y
print("x**y =",z)
logx = np.log2(x)
print("log(x) = ",logx)
print("80417")
|
2dcc0526888b1627b1e6d73928a592cb27f46580 | init-fun/ds_fromScratch | /doubly_linkedlist.py | 5,429 | 3.875 | 4 | class Node:
def __init__(self, data, prev=None, next=None):
self.prev = prev
self.data = data
self.next = next
class doublyLinkedList:
def __init__(self):
self.start = None
def __str__(self):
if self.start is None:
return f"List is empty"
res = ... |
d23cef82db35b66743a2fdba88755547b5a0c7dd | matthew-thomas-acosta/Dynasty-Dashboard | /DynastyDashboard/Data/json_writer.py | 2,486 | 3.59375 | 4 | from sqlite3 import Error
import os
import sqlite3
path = '/db'
def connect(db_path):
db_conn = None
if not os.path.exists(db_path):
os.makedirs(db_path)
db_path = db_path + '/Dynasty.db'
try:
db_conn = sqlite3.connect(db_path)
except Error as error:
print(error)
... |
3704b5048a83ccb80b2b1602f3756ba8ee5b57ef | AlexGerwer/DS-Unit-3-Sprint-1-Software-Engineering | /acme_report.py | 7,360 | 3.796875 | 4 | """
Acme Products
"""
import random
import unittest
class Product(object):
"""
class of all products
"""
def __init__(self, name, price=10, weight=20, flamability=0.5):
self.name = name
# self.default defined as 0 when self.name is in product_names
self.default = 0
# ... |
e14d2d7de4b93ed78fcd63de63c6b26a73141c11 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_7/greedy_change.py | 531 | 3.90625 | 4 |
face = [1, 2, 5, 10, 20, 50, 100]
amount = int(input('Input the desired amount: '))
amount_left = amount
banknote = []
while amount_left:
money = face.pop()
if amount_left >= money:
banknote.append((money,amount_left//money))
amount_left %= money
nb_of_note = sum(note[1] for note in banknote)... |
c188cb9a70020a72c16c7c3595abb7e54ee55ca5 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_1/my_answer/intervals.py | 1,299 | 4.0625 | 4 | # written by Yuchen Yan Vinceny for comp9021 lab 1
'''
Prompts the user for a strictly positive integer, nb_of_elements,
generates a list of nb_of_elements random integers between 0 and 19, prints out the list,
computes the number of elements strictly less 5, 10, 15 and 20, and prints those out
'''
from random import... |
d0c9761e584e92bcf685db646085b53e15a77c04 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /quizzes/quiz_1/code_and_marks/quiz_1.py | 2,353 | 3.8125 | 4 | # Written by *** and Eric Martin for COMP9021
'''
Generates a list L of random nonnegative integers smaller than the length of L,
whose value is input by the user, and outputs two lists:
- a list M consisting of L's middle element, followed by L's first element,
followed by L's last element, followed by L's second ... |
9851cd093e9f06e686e9ce26a3508902b9358074 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_5/my_answer/cal.py | 2,308 | 4.09375 | 4 | #This is written by Yuchen Yan
'''
My calendar generator, tart the first day of week by monday
'''
import calendar
print('I will display a calendar, either for a year or for a month in a year.')
print('The earliest year should be 1753.')
print('For the month, input at least the first three letters of the month’s n... |
741c8a69d3e1782d6cd3f6f5ef4167ada0936601 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_2/my_answer/perfect.py | 667 | 3.84375 | 4 | # Written by Vincent Yuchen YAN for comp9021 lab2
'''
This program is aim to input a number n and find the
perfect number from 1 to n.
Implement a naive solution, of quadratic complexity,
so that can deal with small
values of N only.
'''
if __name__ =='__main__':
try :
N = int(input('Input an int... |
8c8c861daf4fb6f0c70eb776d8563907dda10f35 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_1/my_answer/celsius_to_fahrenheit.py | 435 | 4.1875 | 4 | # Written by Yuchen Yan for comp9021 lab 1 question1
'''
Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees,
with the former ranging from 0 to 100 in steps of 10.
'''
min_temperature = 0
max_temperature = 100
step = 10
print('Celsius\tFahrenheit')
for celsius in range(min_temperature,... |
26c5f944249dae521fee3f7a7a08dced6783f083 | xckou/SI507-HW04-xckou | /magic_eight.py | 963 | 3.90625 | 4 | import random
def question():
answer = input("What is your question?")
if answer[-1] != "?":
print("I’m sorry, I can only answer questions.")
else:
randomanswer()
while answer !="quit":
answer = input("What is your question?")
if answer == "quit":
return
elif answer[-1] != "?":
print("I’m sorry, I... |
84c13428e3ef48e19fdfbf7f6c35d069584aad33 | vpiyush/SandBox | /python-samples/L1/ifelif.py | 231 | 3.84375 | 4 | i = int(input("enter a number:"))
n = 12
if i == 10:
print("i is 10")
elif i == 12 and n == 12:
print("i is 12")
elif i == 13:
print("i is 13")
else:
print("i is not matching to any condition")
print(type("s"))
|
aabc20bf3f88230a7feb7873388b666d55d78897 | vpiyush/SandBox | /python-samples/Indetataion.py | 128 | 4 | 4 | a = [1,2,3,4,5]
for i in a:
print(i)
if(i==3):
print("3 found")
print("another statement inside if ")
|
20e61a14ba04a69c1095840c5b33ff936f6a8d3b | vpiyush/SandBox | /python-samples/rangeOp.py | 330 | 4.15625 | 4 |
# sequnce of numbers 0 to 8
for temp in range(9):
print(temp)
# sequnce of numbers 0 to 8
# range (start, stop)
for temp in range(5, 9):
print(temp)
# sequnce of numbers 0 to 8
# range (start, stop, step)
for temp in range(1, 9, 2):
print(temp)
#typecasting to list
oddlist = list(range(1, 19, 2))
print... |
fe1964b193c780885b6ec707855a7ad028b853eb | vpiyush/SandBox | /python-samples/L3/boolOp.py | 169 | 4.21875 | 4 | x = True
y = False
if x or y:
print("either x or y is true")
if x and y:
print("Both x and y is true")
else:
print("either x or y is false")
print(not x)
|
0bdd19a602af82c611e31bd421a0bc8aca10ecce | harshita26/Hotel-management-system | /hotel.py | 6,158 | 4.21875 | 4 | # using function
def intro(name,rest_total,laun_total,game_total,rent,address,checkin,checkout,room):
print('''\n\n**********WELCOME TO HOTEL************ \n\n
1.Enter Customer Data
2.Calculate Room Rent
3.Calculate Restaurant Bill
4.Calculate Laundry Bill
5.Calculate Game Bill
6.Show Total Cost
7.EXIT
'''... |
4564b05674cd522ec2e5da66254c09cdeb22b2fd | TheSmileyDroid/Deepy | /dialog.py | 2,614 | 3.515625 | 4 | import pygame
WIDTH = 320
HEIGHT = 224
LOCATION = (12, 176)
LIMIT = 296
def drawText(surface, text, color, rect, font, aa=False, bkg=None):
rect = pygame.Rect(rect)
y = rect.top
lineSpacing = -2
# get the height of the font
fontHeight = font.size("Tg")[1]
while text:
i = 1
... |
fbb68d13dac17cda4e7f2f495d91430f1377058c | kethllen/ASA | /trab02/dbCategorias.py | 2,237 | 3.640625 | 4 | import psycopg2
from psycopg2 import Error
with open('/home/lariteixeira/ASA/password.txt') as f:
password = f.read().strip()
class Categorias:
schema = "schema.sql"
connection = psycopg2.connect(user = "postgres",
password = password,
ho... |
27a48c5d309c06a6730df859139245bec6106a37 | sureshanandcse/Python | /listex.py | 693 | 4.34375 | 4 | # Creating a List with the use of multiple values
l= ["Sairam", "Engineering", "College"]
print("\nList containing multiple values: ")
print(l[0])
print(l[2])
s=l[1]
print("s= ",s)
print("s[2] =" ,s[2])
print(len(l))
"""
list = [ 'abcd', 786 , 2.23, 'john', 70.26 ]
list[0]='suresh' # list is mutab... |
995a812fcfa31f6ba0ca9b8cf48bba04e6ff1a66 | codekyz/learn-algorithm | /algorithm_with_python/Doit/old/2_8.py | 733 | 4.1875 | 4 | # reverse sort of mutable sequence element
from typing import Any, MutableSequence
def reverse_array(a: MutableSequence) -> None:
n = len(a)
for i in range(n//2):
a[i], a[n-i-1] = a[n-i-1], a[i]
if __name__ == '__main__':
print('reverse sort of array element')
nx = int(input('enter number of ... |
098691ffe2c7ed3c0c167e639451faa34f091860 | codekyz/learn-algorithm | /algorithm_with_python/08_Divideandconquer.py | 490 | 3.828125 | 4 | # Binary Search - Recursive
def location (S, low, high):
if (low > high):
return 0
else:
mid = (low + high) // 2
if (x == S[mid]):
return mid
elif (x < S[mid]):
return location(S, low, mid - 1)
else:
print(low, mid, high)
r... |
c6b1796b76ecf25bf0078f56fc07be3afe8c8721 | codekyz/learn-algorithm | /algorithm_with_python/Doit/old/1_7.py | 774 | 3.609375 | 4 | # 가로, 세로 길이가 정수 이고 넒이가 area인 직사각형의 변의 길이 나열하기
# 약수 구하기
area = int(input('넓이 : '))
for i in range(1, area+1):
if i * i > area: break # i가 가장 긴 변의 길이가 되고 사각형의 최대 넓이를 초과하므로 강제 종료
if area % i: continue # 넓이가 i로 나누어 떨어지지 않으면(나머지가 있으면) 출력하지 않고 건너뜀
print(i,' X ',area // i)
# 10~99 사이의 난수 n개 생성하되 20이 나오면 중단
# e... |
0bc6907db2836ea17153e10d68f408d6a2759300 | codekyz/learn-algorithm | /algorithm_with_python/Doit/old/1_1.py | 438 | 4.09375 | 4 | # input : 정수 3개
# Find Maximum Value
# a = int(input())
# b = int(input())
# c = int(input())
# input() enter 입력전까지 문자열을 받고 enter를 제외한 string return
def max3(a, b, c):
max = a
if b > max: max = b
if c > max: max = c
return max
# sequential structure
# select Structure
print(f'max3(3,2,1)= {max3(3,2,1... |
3b963eb9fab0d9077d566d1e77f61a0e171189a4 | Eshan-shukla/Game | /game.py | 3,960 | 3.75 | 4 | import pygame
from pygame.locals import *
import time
import random
class Apple:
def __init__(self, parent_screen):
self.parent_screen = parent_screen
self.image = pygame.image.load("resource/apple.jpg")
self.x = 40*10
self.y = 40*10
def draw(self):
self.parent_screen.b... |
d1ff5430830089780370fe8fb3b0d5463db3a24e | ShapeshiftR9/proj-test1 | /TweetSearch.py | 912 | 3.546875 | 4 | # Twitter search to Excel
# '''Search for thousands of tweets and accounts
#Perform bulk searches on multiple terms
# Retrieve 50+ columns per tweet & account
#mRemove duplicate tweets automatically'''
# You just need to call Twitter api which you need to read about
# from twitter developers website and then use a x... |
125c4341943e9781fc9ee60b35e6beb13717c4aa | peggybarley/Ch.03_Input_Output | /3.0_Jedi_Training.py | 1,568 | 4.375 | 4 | # Sign your name: Peggy Barley
# 1.) Write a program that asks someone for their name and then prints their name to the screen?
print()
name = str(input("What is your name?"))
print("Hello,", name,"!")
print()
# 2. Write a a program where a user enters a base and height and you print the area of a triangle.
print(... |
7ee6a48e8387a0d45ea82cf44b3e7b679dfcc503 | kongxilong/python | /mine/chaptr3/readfile.py | 341 | 4.3125 | 4 | #!/usr/bin/python3
'readTextFile.py--read and display text file'
#get file name
fname = input('please input the file to read:')
try:
fobj = open(fname,'r')
except:
print("*** file open error" ,e)
else:
#display the contents of the file to the screen.
for eachline in fobj:
print(eachline,)... |
6c9b1f856e9c1abb350336b26b76f48a87a9f1bb | antwork/pynote | /source/str.py | 1,872 | 4.25 | 4 | # encoding:utf-8
# len(str)
s = 'hello China'
print(len(s))
#
# capitalize
# Return a capitalized version of S, i.e. make the first character
# have upper case and the rest lower case.
print('big city'.capitalize()) # Big city
#encode:utf-8
#
# casefold
# out: **********************value**********************... |
9a146512774e7f58cca8ea6a1caae00a7cca78a9 | nlnadialigia/exercises-python-brasil | /estrutura-sequencial/ex07.py | 153 | 3.9375 | 4 | lado = float(input('Digite o valor do lado: '))
double = (lado * lado) * 2
print(f'O dobro da área de um quadro de {lado} de lado é igual a {double}')
|
4f5cac70e6f99d0481cf77accac0e1e8e930f308 | nlnadialigia/exercises-python-brasil | /estrutura-sequencial/ex17.py | 842 | 3.5625 | 4 | from math import ceil, floor
area = 100
area_com_folga = area + (area * 0.10)
litros_por_metro = 6
litros_utilizados = area_com_folga / litros_por_metro
litros_por_lata = 18
latas = ceil(litros_utilizados / litros_por_lata)
print(f'latas = {latas}')
print(f'Valor total das latas: R${(latas * 80):.2f}\n')
litros_por_g... |
6f6841131e000673f4625766259e59900c2c41e6 | nicolasvienot/n-puzzle | /generator/npuzzle-gen.py | 2,275 | 3.734375 | 4 | #!/usr/bin/env python
import sys
import argparse
import random
def make_puzzle(s, solvable, iterations):
def swap_empty(p):
idx = p.index(0)
poss = []
if idx % s > 0:
poss.append(idx - 1)
if idx % s < s - 1:
poss.append(idx + 1)
if idx / s > 0 and idx - s >= 0:
poss.append(idx - s)
if idx / s < ... |
1e15ee259128fbf410955879b0293015dde85302 | JesusDzul111498/ESTRUCTURA_DE_DATOS | /Unidad 3/Ejercicio3/operacion.py | 1,660 | 3.90625 | 4 | class pila_ligada:
def __init__(self,n,j):
self.nombres=[]
self.contacto=[]
self.n=n
self.j=j
def apilar(self):
while self.n and self.j != "":
self.nombres+=[self.n]
print("otro nombre")
self.n=input()
self.contacto+=[sel... |
ae787f8baba24f311f64ee942a180604686005ff | GeorgeVepo/Machine-Learning | /Designing a Machine Learning Model/dimensionality-reduction-PCA.py | 593 | 3.65625 | 4 | # Performing dimensionality reduction on linear data
# using Principal Component Analysis (PCA)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
diabetes_data = pd.read_csv('dataset/PimaIndians_processed.csv')
FEATURES = list(diabetes_data.columns[:-1])
de... |
be155f94cac5cc4f9e00bc517dcb3590bfa88994 | asadrao11/OOP-Python | /obj1.py | 319 | 3.828125 | 4 | class Employee:
def __init__(self, fname, lname, salary):
self.fname = fname
self.lname = lname
self.salary = salary
asad = Employee('asad', 'rao', 5500)
sarim = Employee('sarim', 'khan', 1500)
print(asad.fname, asad.lname, asad.salary)
print(sarim.fname, sarim.lname, sarim.salary)
|
eceaf4f98b5439ce4523c6ff737e6d731d1d3c00 | SantiSinesi/santino-sinesi-programacion | /trabajo programacion/ejercicio10.py | 172 | 3.8125 | 4 | n = input("Dividendo?(entero): ")
m = input("Divisor?(entero): ")
print(n + " dividido " + m + " da " + str(int(n) // int(m)) + " y de resto " + str(int(n) % int(m)))
|
e0825f9f6dd0aa3a894806755914b90a506b66fe | SantiSinesi/santino-sinesi-programacion | /trabajo programacion/ejercicio9.py | 185 | 3.71875 | 4 | peso = input("¿Cuanto pesas en kg? ")
altura = input("¿Cuantos medis en metros?")
imc = round(float(peso)/float(altura)**2,2)
print("Tu índice de masa corporal es: " + str(imc))
|
195877bb9aa006f8e4bcbf52275914ee2648ae9d | Gzxcn/python_daily | /Day1/sort.py | 1,523 | 4.0625 | 4 | from itertools import chain
# sort
# list里都是数字排序
number_list = [5,1,7,8,-10,50,-90,-5]
# print(sorted(number_list))
# 比较绝对值
# print(sorted(number_list,key=abs))
# 疑问 sorted 是否会改变原number_list顺序
number_list.sort()
print(number_list)
sorted(number_list)
print(number_list)
# 输出的是 [5,1,7,8,-10,50,-90,-5] 说明 不改变 而是创... |
57b52ff96d9c8b71bb40fb0e07b1ba86167359cd | Gzxcn/python_daily | /Day1/list_creator.py | 912 | 3.921875 | 4 | # 列表生成式 & 生成器
# 生成 [1x1,2x2,3x3,...,10x10]的列
l = list(range(10))
l1 = []
for x in l :
l1.append(x*x)
print(l1)
# 简化写法
l2 = [x*x for x in l ]
print(l2)
# 简化写法中 带条件判断
l3 = [x*x for x in l if x % 2 == 0] #偶数保留
print(l3)
# 多个参数的简化写法 每个会互相组合 char1的每一个字符与char2的每个字符组合
char1 = "helloworld"
char2 = "dlrowolleh"
l4... |
37a6b627006d966cd4cb33a98a95d8fa0c6e47c6 | yonibonen/Lesson-6 | /lesson_6_HomeAssign.py | 168 | 3.75 | 4 | def user_input():
var_str = input("Please Enter a String: ")
return var_str
def str_to_print(user_str):
print(user_str)
str_to_print(str(user_input()))
|
c4e052908f4548615e1bd075bf3bab04905385d3 | JAcciarri/Simulation | /TP2.1/__init__.py | 4,316 | 3.578125 | 4 | # -*- coding: utf-8 -*-
'''
UTN FRRO - Simulation 2020
TP2.1 - Pseudorandom Generators
Authors: Joshua Acciarri (44823) & Nicolás Antonelli (44852)
Professor: Torres, Juan
Final Date: 16/05/2020
Python Libraries/Modules Used:
- Numpy: Random Numbers and Array Manipulation
- Pyplot: Matplotlib Module for... |
235f1e9b1b6fbfb911a1638702e19911389ec568 | JAcciarri/Simulation | /TP2.2/__init__.py | 5,854 | 3.5625 | 4 | # -*- coding: utf-8 -*-
'''
UTN FRRO - Simulation 2020
TP2.2 - Pseudorandom Numbers Generation on Different Distributions
Authors: Joshua Acciarri (44823) & Nicolás Antonelli (44852)
Professor: Torres, Juan
Final Date: 10/06/2020
Python Libraries/Modules Used:
- Numpy: Mersenne-Twister Generator, Functions an... |
42db40859935dc3bfca4f40ccb32ba90abf8e3b6 | boksuh/Jump_to_Python | /02/02-3.py | 970 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Bokyung Suh
점프 투 파이썬
"""
odd = [1, 3, 5, 7, 9]
a = [1, 2, 3]
print(a)
print(a[0])
print(a[0] + a[2])
print(a[-1])
a = [1, 2, 3, ['a', 'b', 'c']]
print(a[0])
print(a[-1])
print(a[3])
print(a[-1][0])
a = [1, 2, 3, 4, 5]
print(a[0:2])
print(a[:2])
print(a[2:])
a = [1, 2, 3]
b ... |
e2e6565ce0f752479164b9ddcd8b1406ca941b28 | akashjakkula/hackrank | /meal_cost.py | 574 | 3.734375 | 4 | import math
import os
import random
import re
import sys
def solve(meal_cost, tip_percent, tax_percent):
tip_percent1=(tip_percent/100)*meal_cost
tax_percent1=(tax_percent/100)*meal_cost
meal_cost1=meal_cost+tip_percent1+tax_percent1
meal_cost2=round(meal_cost1)
return meal_cost2
if ... |
85ca1f40a0ce03d348445ce734574a47256bb8a5 | juancho20sp/Palabras-Encadenadas | /db_operations/users.py | 10,525 | 3.59375 | 4 | """
Hello from database_feature
"""
from db_operations.connection import users
from data_operations.verifications import validate_email
def create_user(name: str, lastname: str, username: str, email: str) -> int:
"""
Esta es la función que crea y almacena un usuario nuevo en la base de datos.
:param name... |
ee63617dd765f82c0f569defcbfae5b663745090 | afovio/python3 | /adnumero.py | 1,306 | 4.03125 | 4 | # Adivinhar Numero
from random import randint # Puxa o Modulo
# ===
Numero_Aletatorio = randint(1, 9) # Lanca os numeros aletoriamente
print ("===>", Numero_Aletatorio) # Chuta na tela o valor aleatorio.
# ===
print ("\n")
nome = input("COMO SE CHAMA: \n")
user_digita = int(input("Digite um Numero: \n")) #User Digita o... |
aef53eeab6ea638536fa96f90a986fce3649d0e7 | Amankesarwani2202/Tic-Tac-Toe | /TTT.py | 2,634 | 3.796875 | 4 | import os
l=['_','_','_','_','_','_','_','_','_']
ne=0
def win_condition(l):
if(l[0]=='0' and l[1]=='0' and l[2]=='0' or l[0]=='X'and l[1]=='X'and l[2]=='X'):
if(l[0]=='0'):
print("WINNER IS FIRST PLAYER")
else:
print("WINNER IS SECOND PLAYER")
return 1
elif(l[3]=... |
a988f35e8376fcd9c82ee7b463fab10240abb1fe | n0execution/prometheus-python | /lab3_1.py | 321 | 4.3125 | 4 | import sys
a = float(sys.argv[1]) #a is the first argument
b = float(sys.argv[2]) #b is the second argument
c = float(sys.argv[3]) #c is the third argument
if (a + b > c) & (a + c > b) & (b + c > a) :
print("triangle") #two sides > than the other
else :
print("not triangle") #two sides <= than the other
... |
8416779fee766e6ad1dbbf23bc88cdd02c7a7706 | n0execution/prometheus-python | /lab5_3.py | 635 | 4.40625 | 4 | """
function for calculating superfibonacci numbers
it is a list of whole numbers with the property that,
every n term is the sum of m previous terms
super_fibonacci(2, 1) returns 1
super_fibonacci(3, 5) returns 1
super_fibonacci(8, 2) returns 21
super_fibonacci(9, 3) returns 57
"""
def super_fibonacci(n, m) :
#chec... |
39a3ba15e6a0fe148f4977ccb5db70ad5142e2fe | n0execution/prometheus-python | /lab7_4.py | 1,866 | 4.34375 | 4 | import datetime, calendar
"""
function for displaying definite month of definite year
$ print create_calendar_page(1)
'--------------------
MO TU WE TH FR SA SU
--------------------
01 02 03 04 05 06 07
08 09 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31'
$ print create_calendar_page()
'--------... |
5cf0406aa64a6679f4aea84a4662d819dad13d4a | TaylorKolasinski/hackerrank_solutions | /strings/pangrams.py | 1,122 | 4.3125 | 4 | # Difficulty - Easy
# Problem Statement
# Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly because it is a pangram. ( pangrams are sentences constructed by using every letter of the alphabet at lea... |
010061a3a9938808c74dd3a17aa6c1c790c813bd | ZitingShen/Euler-Project | /7. 10001st Prime.py | 219 | 3.796875 | 4 | i=2
num=3
primes=[3]
while i<10001:
num+=2
rst=True
for p in primes:
if num%p==0:
rst=False
break
if rst==True:
i+=1
primes.append(num)
print(num)
|
9fcca234eaf694aac65f60dbecff274770f2ff3f | majchLR/euler | /problem_003.py | 362 | 3.5625 | 4 | prime_nums = []
def is_prime(num):
for x in range(2, num):
if num % x == 0:
break
elif x == num-1:
return num
for y in range(2, 10000):
if is_prime(y) is not None:
prime_nums.append(y)
for number in prime_nums:
if 600851475143 % number == 0:
print... |
32bc35a41e21f5a16b28b3666c56c2bd2f0ceddf | kwadjooe/workingwithdata | /parsexmlsample.py | 470 | 3.5625 | 4 | import xml.etree.ElementTree as ET
# get the xml data
stream = open('sampleXML.xml', 'r')
# parse the Data into an ElementTree Object
xml = ET.parse(stream)
# Get the "root" Element Object from the ElementTree
root = xml.getroot()
# Iterate through each child of the root element
for e in root:
# print the str... |
8c31f4a29804ccecb16daedd837a65ea8fd375bb | JAT117/Notes | /CSCE4910/PythonExamples/TexBoxWidget.py | 827 | 4.25 | 4 | #!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
#Handles Button Clicked
def clickMe():
#When clicked, change name of button.
... |
b2c0b85e7c00591eeffa9693588c826d163626dd | open-all/Algorithms | /863AllNodesDistanceKinBinaryTree/AllNodesDistanceKinBinaryTree.py | 1,411 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.righ = None
class Solution:
def distance(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
graph = defaultdict(list)
queue = collections.deque([r... |
e8df9c2cc4a3f8fb136c50cb9c6ef47886b69b72 | open-all/Algorithms | /74.Searcha2DMatrix/74.Searcha2DMatrix.py | 643 | 3.796875 | 4 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
#edge case, there is no matrix
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
left = 0
right = m * n - 1
#find value using binary search
... |
7f8e43d5ca8fdc857bc15a656a04b9639ef6eab4 | open-all/Algorithms | /2246.LongestPathWithDifferentAdjacentCharacters/2246.LongestPathWithDifferentAdjacentCharacters.py | 1,495 | 3.6875 | 4 | class Solution:
def longestPath(self, parent: List[int], s: str) -> int:
e = collections.defaultdict(list)
for i, x in enumerate(parent):
if x == -1:
continue
if s[i] == s[x]:
continue
e[i].append(x)
e[x].append(i)
... |
a33caa4d3d8ebc3a1429ab4b347aa4e506e05eeb | tmsteph/Guatemala-Teaching | /PythonStuff/GameTime.py | 275 | 4.09375 | 4 | name = input("What is your name? ")
coding = (input("How long have you been coding?"))
trueOrFalse = bool(int(input("are you truthy? Put 0 for True and 1 for False")))
print(f"myname is {name}. I've been coding for {coding} years. It's {trueOrFalse} that I'm truthful.")
|
e018cb6c8f63e29b7678b9e8b0d34f5f1c09181f | gsadhas/opencv-examples | /basic_image_operations/image_types_and_channels.py | 1,042 | 3.625 | 4 | import numpy as np
import cv2
color = cv2.imread("butterfly.jpg", 1)
cv2.imshow("Image", color)
cv2.moveWindow("Image", 0, 0)
print(color.shape)
height, width, channels = color.shape
b, g, r = cv2.split(color) # Split color channels into blue, green, red channel matrix
rgb_split = np.empty((height, width*... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.