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 |
|---|---|---|---|---|---|---|
58a8e887a02b201b207a8da8b2a31d314eb42e51 | 13424010187/python | /源码/【30】函数制造者-课程资料/【30】函数制造者-练习二-成果包.py | 267 | 3.796875 | 4 | '''函数制造者-练习二'''
tpl = (1, 4, -5, 64, 78, 12, 0, 3, 3.5, 3)
# 定义最小值函数
def mymin(x):
m = x[0]
for i in x:
if i < m:
m = i
return m
# 调用最小值函数
res = mymin(tpl)
print('最小值是:'+str(res))
|
09efa10c5ed07aee7f739edb79f444daf42346ea | 13424010187/python | /源码/【19】图书管理员-课程资料/【19】图书管理员-成果包.py | 1,671 | 3.703125 | 4 | '''图书管理员-成果包'''
'''阿短一共收到了同学拿来分享的7本图书,分别是《哈利波特》、
《流浪地球》、《封神演义》、《三国演义》、《红楼梦》、《西游记》、
《水浒传》,请你基于这7本书籍建立一个书单,并实现书单展示、借书、还书的功能,
完成图书管理程序。'''
# 创建书单
lib = ['哈利波特', '流浪地球', '封神演义', '三国演义', '红楼梦', '西游记', '水浒传']
while True:
print('end:结束管理图书', '0:展示书单', '1:借书', '2:还书')
message = input('你好!要图书助手帮你做什么:')
if message =... |
b112e13c968d7661837c1c5407265de891c0f738 | 13424010187/python | /源码/【21】随机怪兽生成器-课程资料/【21】随机怪兽生成器-练习包.py | 1,093 | 3.59375 | 4 | # 调用random库
import random
# 实践一:用随机索引访问列表中的元素
mylist = [1, 45, 'a', 'fd', 3, 's']
# randint(a,b):随机的索引(下标)从0到mylist长度减一
x=random.randint(0,len(mylist)-1)
print(mylist[x])
# 实践二:随机生成一个怪兽
names = ['时空魔神', '海底猿人', '植物怪兽', '火山怪鸟', '刺客超兽']
where = ['猪圈', '厕所里', '房顶上', '办公室']
doing = ['引起大规模停电', '抄作业', '喜极而泣', '偷西瓜', '玩火自焚'... |
7d586dd6cfe6dd6f302dc820f37afbc901484f75 | 13424010187/python | /源码/【13】海龟螺旋线-课程资料/【13】海龟螺旋线-练习包.py | 956 | 3.796875 | 4 | '''海龟螺旋线-练习包'''
#调用模块
# import turtle
import turtle as t
# from turtle import pensize, forward
#画条线小例
t.forward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(100)
#隐藏画笔
t.hideturtle()
#阻止界面自动关闭(改为点击关闭)
t.done()
#进阶练习:正方形作图练习
#画笔设置
t.pensize(2)
t.speed(10)
t.pencolor("red")
#前进再右转的代码重复四次实现正方形的绘制
t.forward(50)
... |
35e0689ce008c42fb8adb4ef4e55bc8abe0c30d6 | 13424010187/python | /源码/【16】智慧画手-课程资料/16.py | 1,971 | 4.09375 | 4 | ''''''
'''
随机产生小数:random.uniform(小,大)
切换RGB色彩模式:t.colormode(mode)
1、RGB小数模式:1.0
2、RGB整数模式:255
'''
'''circle螺旋线'''
# import turtle as t
# t.speed(0)
# for i in range(200):
# t.circle(i,30)
# t.hideturtle()
# t.done()
'''多彩繁星'''
# import turtle as t
# import random
# # t.speed(0... |
26124a9ac3e6650f73c4bf3adfdc046a3be26ecf | 13424010187/python | /2021暑假课/编程与数学/04-常胜将军/04-常胜将军.py | 535 | 3.75 | 4 | spare = 21
print("游戏开始:")
while True:
print("---------剩余火柴数量为:", spare, "---------")
gamer = int(input("你取火柴: "))
if gamer < 1 or gamer > 4 or gamer > spare:
print("你取的火柴数量犯规!")
continue
spare -= gamer
if spare == 0:
print("计算机获胜,游戏结束")
break
computer = 5 - gamer
... |
1253602c714aeb7c4d9752808da61ce83352f1c6 | 13424010187/python | /源码/4-对答如流/垃圾分类2.py | 850 | 3.859375 | 4 | '''练习2成果包——垃圾分类v2.0'''
'''
自行完善垃圾分类的判断
分类:
1.有害:锂电池
2.可回收:作业纸、塑料、电池
3.厨余:鱼骨、炒米饭、鸡蛋壳
4.其它:大棒骨、渣土、污染纸
根据以上提示的垃圾分类方式,制作垃圾分类提示小帮手,输入要扔的垃圾,给出判定类型
如:
Input:
请输入要丢弃的垃圾:电池
Output:
可回收垃圾
'''
rubbish1 = '锂电池'
rubbish2 = '作业纸、塑料、电池'
rubbish3 = '鱼骨、炒米饭、鸡蛋壳'
rubbish4 = '大棒骨、渣土、污染纸'
message = input('请输入要丢弃的垃圾:')
if message in rubbi... |
20d4008bc3c535eaef01c7363bf3cac3fb8fc4ed | 13424010187/python | /源码/【19】图书管理员-课程资料/【19】图书管理员-练习包.py | 388 | 3.90625 | 4 | '''图书管理员-练习包'''
# 实践1
mylist = ['c','o','d','e','m','a','o']
for i in mylist:
print(i)
# 实践2
s = 'hello codemao'
# 1小题
print(s[8])
# 2小题
print(s[6:10:1])
# 3小题
print(s[0:14:2])
stop = len(s)
print(s[0:stop:2])
# 实践3
s = 'hello codemao !'
mylist = []
for i in s:
if i != ' ':
mylist.append(i)
mylist.... |
d5fca40ab9bdfe8255845236e981c7c590f2c8cb | 13424010187/python | /源码/【45】我的英语词典(上)-课程资料/【45】我的英语词典(上)-成果包/我的英语词典-成果包.py | 1,824 | 3.8125 | 4 | '''我的英语词典上-成果包'''
def load_dict():
'''加载词典'''
'''
输入:无
输出:包含所有单词的字典,格式如{'apple':{'NO.':'1', 'mean': 'n.苹果'}, ......}
'''
#建立空字典用来存储加载出来的单词信息
wordsDict = {}
#打开词典文件
with open('wordsSpace.txt', 'r', encoding='utf-8') as w:
#读取全部数据
word_list = w.readlines()
... |
5a53ec8a58ebb4e2a5c3fac372b9d383a11908d0 | 13424010187/python | /源码/9-猜数字游戏/挑战包.py | 812 | 3.890625 | 4 | '''猜数字游戏-挑战包'''
'''stamp:标记修改点,本文共有4个标记'''
import random
number = random.randint(0, 100)
i = 1
#stamp1:设置start和end记录猜测的结果
start = 0
end = 100
print('开始猜数字小游戏吧!')
print(number)
while i <= 3:
#stamp2:修改猜数字游戏提示
send = '第' + str(i) + '次(' + str(start) + '-' + str(end) + '):'
message = int(input(send))
if m... |
f55215172e71f730c7a47572a74e8bcf3b219468 | Patricia-Henry/Python-Project- | /Your Life in weeks.py | 556 | 4.09375 | 4 |
age = input("What is your current age?")
# age_as_int is the oldest you will be in this case, 90
age_as_int = 90
# years is referring to how many years you have left based on your current age
years = (int(age_as_int) - int(age))
# days refers to how many days you have left until you reach 90
days = (365*y... |
355a3f8d35015788ce9ed76d70fa4df4b5db56a4 | gjcasanova/Devsu-Code-Jam-2021 | /Knockout Round/Arrays creator/Arrays creator.py | 939 | 4.09375 | 4 | """
Given two integers size and u, return the number of all the possible arrays of length size
you can create using u different integers with the condition that no more than 2 elements
are repeated one after another. The elements you use do not matter, just make sure they
are different.
"""
def solve(size, u):
de... |
bfe74256f9d31cb8dffc264eeec1ac5cd98a5440 | ml4ai/fed-recon | /fed_recon/util/early_stopper.py | 2,047 | 3.640625 | 4 | import operator
from typing import Tuple
class EarlyStopper:
"""
Computes stopping criterion given a metric and a patience.
"""
def __init__(
self,
patience: int = 20,
metric_should_increase: bool = True,
min_steps: int = 0,
):
"""
Args:
... |
64d2755419a9f310c85290bd1083e18c17a4299f | hftor/aiMaze | /ticTacToe/haftor/ticTacToe.py | 3,941 | 3.578125 | 4 | #!/bin/python
import random
class Node:
def __init__(self, gameState, i, j):
self.state = gameState
self.value = 0
self.children = []
self.xCoordinate = i
self.yCoordinate = j
self.hasValue = False
def formNewState(world, i, j, player):
newState = []
for k in range(3):
if(k == i):... |
629d204d76e6545d713ec221aebff2c8bd627a6a | cstarr7/daily_programmer | /hard_2.py | 1,852 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# @Author: Charles Starr
# @Date: 2016-03-08 23:51:13
# @Last Modified by: Charles Starr
# @Last Modified time: 2016-03-09 00:14:55
#Your mission is to create a stopwatch program.
#this program should have start, stop, and lap options,
#and it should write out to a file to be viewed later... |
a388858021542a586073ae6f0cea563423bedd17 | cstarr7/daily_programmer | /easy_267.py | 1,223 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# @Author: Charles Starr
# @Date: 2016-07-06 23:20:28
# @Last Modified by: Charles Starr
# @Last Modified time: 2016-07-06 23:53:49
#https://www.reddit.com/r/dailyprogrammer/comments/4jom3a/20160516_challenge_267_easy_all_the_places_your/
def input_place():
#ask user what place their dog ... |
1c08013a24a864149594bca77840be49accde646 | Anju-PT/pythonfilesproject | /functionalprogramming/listcomperhension.py | 523 | 3.875 | 4 | # lst=[1,2,3,4,5]
# squres=[num**2 for num in lst]
# print(squres)
#
# fruits=["apple","orange","mango"]
# fruit=[(fruit,fruit) for fruit in fruits]
# print(fruit)
# lst1=[10,20]
# lst2=[30,40]
# pairs=[(num1,num2) for num1 in lst1 for num2 in lst2]
# print(pairs)
# lst1=[1,2,3,4,5,6,7]
# #print evens
# evens=[num f... |
b06d342a45fb97dd350a2aacd2badc595393b9e7 | Anju-PT/pythonfilesproject | /functionalprogramming/2list.py | 658 | 3.734375 | 4 | lst1=[10,20,21,22,23]#check both are same
lst2=[20,21,10,22,23]
c=[]
# for i in lst1:
# if i in lst2:
# c.append(i)
# else:
# print("lists are different")
# if(c==lst1):
# print("lists are same")
#--------------------------------------
# l1=sorted(lst1)
# l2=sorted(lst2)
# if(l1==l2):
# ... |
4191e7432e2a0b84fdab621387e41da82fe94f81 | Anju-PT/pythonfilesproject | /collections/list/sumofelemt.py | 134 | 3.546875 | 4 | lst=[10,20,30,40,50,60,70,80,90,100]
s=0
for i in lst:
s+=i
print(s)
print(sum(lst))#predefined function to calculate sum in list |
56c5bbf6bb450e62659331342996f1c4089d9153 | Anju-PT/pythonfilesproject | /advancedpython/regularexpression/irule.py | 293 | 3.765625 | 4 | # import re
# n="hello"
# x="\w*[^0-9]"
# match=re.fullmatch(x,n)# take the full string
# if match is not None:
# print("Valid")
# else:
# print("Invalid")
import re
n="45kg"
x="\d{2}[a-z]{2}"
match=re.fullmatch(x,n)
if match is not None:
print("Valid")
else:
print("Invalid") |
9aed22e388d8876dacfe86f9854e9e95c4306183 | Anju-PT/pythonfilesproject | /Functions/arithmetic.py | 277 | 3.796875 | 4 | def add(num1,num2):
s=num1+num2
return s
def sub(num1,num2):
su=num1-num2
return su
def mul(num1,num2):
m=num1*num2
return m
def div(num1,num2):
d=num1/num2
return d
#module:each python program is module #.py
#package :collection of modules
|
971c13669f170cdc964f36ee594da4212e6d680f | Anju-PT/pythonfilesproject | /functionalprogramming/filter.py | 126 | 3.65625 | 4 | lst=[2,3,4,5,6,7]
evens=list(filter(lambda num:num%2==0,lst))
print(evens)
nums=list(filter(lambda num:num>5,lst))
print(nums) |
39f3e3296243e99bf3438df5f38445fbd74b6f7a | Anju-PT/pythonfilesproject | /flow controls/even.py | 117 | 4.21875 | 4 | num=int(input("Enter a number"))
if(num%2==0):
print("The num is even",num)
else:
print("The num is odd",num) |
1e645008c7915cab471887182834b55a1486ac77 | Anju-PT/pythonfilesproject | /collections/set/set.py | 431 | 3.9375 | 4 | #set
#set={}#it creates dictionary not as set
#only using set function
st=set()
print(type(st))
st={2,5,7,8,10}
print(st)
st1={2,"anju",3.5,True,False}#it support hetrogenous data
print(st1)
#insertion order not preserved
st2={1,1,2,2,5,5,3,3,"luminar","luminar",True,True}
print(st2)#it not supported duplicates value... |
2428edb7a08c931729894c03642847956f875f33 | Anju-PT/pythonfilesproject | /flow controls/while/demo.py | 232 | 3.90625 | 4 | #looping
#for
#while
#continous execution of statement
#syntax
#1.initialization
#2.codition
#3.statement
#incriment/ decriment
i=1 #initialization
while(i<=10): #condition
print("hello") #statement
i+=1 #incriment |
f314b01a897416b095711df77411df216d60abf9 | Anju-PT/pythonfilesproject | /advancedpython/regularexpression/rules.py | 721 | 3.75 | 4 | #Rules
#1 # x="[abc]" either a or b or c
#2 # x="[^abc]" not abc
#3 # x="[a-z]" #from a to z(lowercase only)
#4 # x="[A-Z]" #from A to Z(uppercase only)
#5 # x="[a-zA-Z]" #from a to z and A to Z(uppercase and lowecase only)
#6 # x="[0-9]" #from 0 to 9
#7 # x="[^a-zA-Z0-9]" #special symbols only
#8 # x="\s" #space
#9 # ... |
3fcc0995a9a1b90bce65db55251c384b1e6cccd0 | Anju-PT/pythonfilesproject | /advancedpython/oop/class/multipleinheritance.py | 2,237 | 4.03125 | 4 | #multiple inheritance:2 parent and 1 child
# class Parent1():#parent
# def m1(self):
# print("Inside Parent1")
# class Parent2():#child
# def m2(self):
# print("Inside Parent2")
# class Child(Parent1,Parent2):#subchild
# def m3(self):
# print("Inside Child class")
#
# ch=Child()
# ch... |
a947eee5e2cd02838c3f2382f7cbb71f7ae864da | Anju-PT/pythonfilesproject | /flow controls/for loop/pattern9.py | 147 | 3.734375 | 4 | for i in range(5,0,-1):
for j in range(0,i+1):
print(j,end=" ")
print()
#output
# 0 1 2 3 4 5
# 0 1 2 3 4
# 0 1 2 3
# 0 1 2
# 0 1 |
af0c334dbcb331868dc25fbd0d0e9629a0d6b309 | Anju-PT/pythonfilesproject | /flow controls/while/reverse.py | 128 | 3.734375 | 4 | num=int(input("enter num"))
rev=0
digit=0
while(num!=0):
digit=num%10
rev=(rev*10)+digit
num=num//10
print(rev)
|
70f4d092647670dfb5bf3946b80114111ca45c24 | Anju-PT/pythonfilesproject | /advancedpython/oop/class/constructor.py | 599 | 3.921875 | 4 | #constructor = to initialise instance variable
#constructor automatically invoke when creating object
# class Person:
# def __init__(self,name,age,gender):
# self.name=name
# self.age=age
# self.gender=gender
# def printval(self):
# print(self.name,self.age,self.gender)
# pe=Pe... |
505c6c674d121a8606cca299b5c1b8553ae2396e | aeterna-quinque/python-oop | /Pizzeria_5/OutOfRangeError.py | 631 | 3.796875 | 4 | class OutOfRangeError(Exception):
"""
Класс исключений OutOfRangeError.
Вызывается при выходе значения за допустимые рамки в методе ingredients_interface.
"""
def __init__(self, ingredient):
self.ingredient = ingredient
def set_default(self):
"""
Метод, который возвра... |
50d76d894d2f1499d647ff3316ba38879f6e9420 | Justyouso/python_syntax | /my_descriptor/data_descriptor.py | 1,549 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# @Author: wangchao
# @Time: 19-10-29 上午10:20
"""
math 是数据描述符,而 chinese 是非数据描述符。从下面的验证中,可以看出,
当实例属性和数据描述符同名时,会优先访问数据描述符(如下面的math),
而当实例属性和非数据描述符同名时,会优先访问实例属性(__getattribute__)
"""
# 数据描述符
class DataDes:
def __init__(self, default=0):
self._score = default
def __set__(self, in... |
b44285fc26b71623d3447ee9dc10497bebfa01e0 | Justyouso/python_syntax | /my_decorator/function_decorator_has_param.py | 895 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Author: wangchao
# @Time: 19-10-23 上午10:43
"""
带参数方法装饰器
"""
def say_hello(country):
def wrapper(func):
def deco(*args, **kwargs):
if country == "china":
print("你好!")
else:
print("Hello!")
func(*args, **kwargs)
... |
5143a31045bf46715346dec5e2a1e47b0ce139a6 | Xundril/CursorHW | /HW Advanced Classes/HW8 Advanced classes.py | 6,216 | 3.75 | 4 | from __future__ import annotations
from typing import Dict, Any
from abc import ABC, abstractmethod
import random
import uuid
import time
class Animal(ABC):
def __init__(self, strength: int, speed: int):
self.id = None
self.max_strength = strength
self.current_strength = strength
s... |
1815e973d9dca1e660265f131a41a9b1e4d4bf4b | arogovoy/leetcode | /py/sqrtx.py | 1,310 | 3.734375 | 4 | # 67. Add Binary
class Solution:
def mySqrt(self, x: int) -> int:
m, left, right = 0, 0, x
while left < right:
m = left + int((right - left) / 2)
s = m * m
if s == x:
return m
if s < x:
left = m + 1
if s... |
d3e51a5ccfb355d53bd60f94d77342460f6f40dd | arogovoy/leetcode | /py/squares_of_sorted_array.py | 1,232 | 3.921875 | 4 | # 977. Squares of a Sorted Array
#
# Given an integer array nums sorted in non-decreasing order,
# return an array of the squares of each number sorted in non-decreasing order.
#
# Example 1:
# Input: nums = [-4,-1,0,3,10]
# Output: [0,1,9,16,100]
# Explanation: After squaring, the array becomes [16,1,0,9,100].
# After... |
604016808bbff27aa0c6c089939b7e59866c0211 | arogovoy/leetcode | /py/best-time-to-buy-and-sell-stock.py | 605 | 3.765625 | 4 | # 121. Best Time to Buy and Sell Stock
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
low, high = prices[0], prices[0]
profit = 0
for i in range(len(prices)):
if prices[i] < low:
low = prices[i]
high = low
... |
f1f91e460417472113b5adcac62ae93063bb734a | arogovoy/leetcode | /py/remove-linked-list-elements.py | 615 | 3.703125 | 4 | # 203. Remove Linked List Elements
from typing import Optional
from py.utils import ListNode, array_to_list
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode()
dummy.next = head
prev = dummy
while head:
... |
5e09ad7e820282c1a7eec847733626c3df1663b4 | arogovoy/leetcode | /py/remove-duplicates-from-sorted-array.py | 767 | 3.6875 | 4 | # 26. Remove Duplicates from Sorted Array
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
k, i, res = 0, 1, 1
length = len(nums)
while i < length and k < length - 1:
if nums[i] <= nums[i - 1]:
while k < length - 1 a... |
aa5d5322d84d8c10d9a5c9ccb2cebc5173caf933 | arogovoy/leetcode | /py/permutations.py | 1,820 | 3.84375 | 4 | # 46. Permutations
# Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
#
# Example 1:
# Input: nums = [1,2,3]
# Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
#
# Example 2:
# Input: nums = [0,1]
# Output: [[0,1],[1,0]]
#
# Example 3:
# In... |
9a409e5b252e856fc4babf6283effd2b864fe710 | mikegoodspeed/euler | /036.py | 743 | 3.671875 | 4 | import time
def print_time(func):
def wrapper(*args):
start = time.time()
func(*args)
print func.func_name, time.time() - start
return wrapper
def is_palindrome(n):
n = repr(n)
start = 0
end = len(n) - 1
while start <= end:
if n[start] != n[end]:... |
869214b553b6fde41ed55f3da288797eb3b73d2b | mikegoodspeed/euler | /007.py | 231 | 3.734375 | 4 | def is_prime(n):
for x in range(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
i = 1
primes = 0
while primes < 10001:
i += 1
if is_prime(i):
primes += 1
print i
|
b88d74d0677db6c31e179e69921195af962df1b9 | mikegoodspeed/euler | /023.py | 785 | 3.5 | 4 | def divisors(n):
divisors = []
for i in range(1, int(n**.5) + 1):
if n % i == 0:
divisors.append(i)
other = n / i
if other not in (n, i):
divisors.append(other)
return divisors
def sum_of_proper_divisors(n):
count = 0
for i in range(1, int... |
4716f163934e44151fc844d1b9b3fce527db53f2 | mikegoodspeed/euler | /035.py | 445 | 3.578125 | 4 | def is_prime(n):
for x in range(2, int(n ** 0.5) + 1):
if n % x == 0:
return False
return True
def rotations(n):
yield n
n = str(n)
for i in range(len(n) - 1):
n = n[1:] + n[0]
yield int(n)
def is_circular(n):
for i in rotations(n):
if... |
170a21649aa5ad7ff42108f0d6f0ed5c94354265 | vorpus/python_linear_algebra | /matrix.py | 1,683 | 3.890625 | 4 | class Matrix(object):
def __init__(self, matrix):
if (type(matrix[0]) is list):
self.matrix = matrix
self.rows = len(matrix)
self.cols = len(matrix[0])
else:
self.matrix = [matrix]
self.rows = len(self.matrix)
self.cols = len(self.matrix[0])
def is_vector(self):
retu... |
467c98457c3b8689b1ab7f6851df463907c1c9e4 | CedricFigarol/19C | /my19C.py | 3,205 | 3.703125 | 4 | """
Class - My19C: used for creating an object which attributes contain all the 19C information with methods for properly
generate the reference
Claas - Sub19C : subclass used by My19C - used for creating an object which attributes contain 19C sub-information.
MAIN METHODS purpose :
- Load the SQLite Database
- Inject ... |
a6ec948fe0ce62776d8b609d279349bd36fa4860 | Gakur/password-locker1 | /locker_details.py | 7,649 | 4.09375 | 4 | #!/usr/bin/env python3.8
from Locker import User
from Locker import Credentials
def function():
print(" ____ _____ _ ")
print(" | _ \ / ____|| | ")
print(" | |_) ) ____... |
f2f4e422ec009d70af3a630dfdd7f591d5e43720 | Alex7734/lee-algorithm | /Board.py | 1,610 | 3.546875 | 4 | __author__ = 'Mihoc Alex'
from Tkinter import *
import time
import random
window = Tk()
window.title("Lee's Algorithm - Pathfinding in a matrix - BFS INSPIRED")
size = input('Size of matrix:')
Walls = [(1, 2), (1, 7), (1, 8), (2, 7), (2, 8), (3, 7), (3, 8)]
rows = size
cols = size
player = (0,0)
end = (cols-2,rows-2)... |
34409c67de5b24a50987e1a86be10ec2e9c299ae | suryanisaac/mathwithcode | /Math_With_Code/Triplet.py | 449 | 4.3125 | 4 | # Program to find if a given set of numbers are pythagorean triplets
num1 = int(input("Enter The Largest Number: "))
num2 = int(input("Enter The Second Number: "))
num3 = int(input("Enter The Third Number: "))
pt = True
n1s = num1 * num1
n2s = num2 * num2
n3s = num3 * num3
if (n1s == n2s + n3s):
pt = True
... |
044c952baa4ab71e113d62a7b6f4e53eda04c13e | suryanisaac/mathwithcode | /Math_With_Code/Angles/complement.py | 165 | 4.15625 | 4 | # Program to find the complement of an angle
cp1 = int(input("Enter the angle in degrees: "))
cp2 = 90 - cp1
print("The complement of ", cp1, "˚ is ", cp2, "˚")
|
bcdf93ea36a3afa6632324742bf0b9acae82a7ef | nguyent57/Algorithms-Summer-Review | /square_root_of_int.py | 1,388 | 4.28125 | 4 | def square_root(x):
# BASE CASE WHEN X == 0 OR X == 1, JUST RETURN X
if (x == 0 or x == 1):
return(x)
# STARTING VALUE FROM 2 SINCE WE ALREADY CHECKED FOR BASE CASE
i = 2
# PERFECT SQUARE IS THE SQUARE NUMBER ON THE RIGHT OF THE GIVEN NUMBER
# SAY, WE HAVE 7 -> PERSQUARE IS 9, 3 P... |
fd525d79b0b9b683440ef6e52a268feb1550e4e3 | nguyent57/Algorithms-Summer-Review | /shortest_palindrome.py | 1,682 | 4.21875 | 4 | # RUN TIME
# USE: TAKE THE REVERSE STRING OF THE GIVEN STRING AND BRING IT TO THE END
# TO SEE WHAT IS THE SUFFIX OF THE STRING COMPARING TO THE PREFIX OF THE STRING
# REMOVE THE SUFFIX --> SHORTEST PALINDROME
def palindrom(str):
# CREATE AN EMPTY STRING FOR PALINDROME
reverse = ''
# FOR... |
7bbe8947b97d2bd27773d003f3b3eedf9eaa712a | nguyent57/Algorithms-Summer-Review | /all_unique_char.py | 814 | 4.25 | 4 | # METHOD 1: USING A FUNCTION
# RUN TIME: O(n)
# CREATE A FUNCTION THAT WOULD TAKE ANY STRING
def all_unique_char(str):
# CREATE A DICTIONARY TO STORE THE COUNT OF EACH CHARACTER
count = {}
# CREATE AN ARRAY TO STORE THE CHAR
char = []
# FOR EVERY ITEM IN STRING
for i in str:
# ... |
0f6633f03b958e1c606f41ec4c82e660b6dfd350 | UdayQxf2/tsqa-basic | /BMI-calculator/03_BMI_calculator.py | 2,937 | 5.125 | 5 | """
We will use this script to learn Python to absolute beginners
The script is an example of BMI_Calculator implemented in Python
The BMI_Calculator:
# Get the weight(Kg) of the user
# Get the height(m) of the user
# Caculate the BMI using the formula
BMI=weight in kg/height in meters*height in me... |
fba5a5017e2f9b1f5b91a3f877e45a7c63f758eb | UdayQxf2/tsqa-basic | /BMI-calculator/02_BMI_calculator.py | 1,797 | 5.09375 | 5 | """
We will use this script to learn Python to absolute beginners
The script is an example of BMI_Calculator implemented in Python
The BMI_Calculator:
# Get the weight(Kg) of the user
# Get the height(m) of the user
# Caculate the BMI using the formula
BMI=weight in kg/height in meters*height in me... |
cc67cc94b948638f04c2cca6e8e874ecfa5c1395 | kou466/Python | /src/Ch5/7.py | 112 | 3.6875 | 4 | a = int(input("a: "))
b = int(input("b: "))
tmp = a+b-b*b
if(tmp >= 0):
print(tmp)
else:
print("음수") |
1d06833e3f001e238e13e955502690fb4f259bdc | kou466/Python | /src/Ch9/05.py | 222 | 3.65625 | 4 | num1 = int(input("정수1: "))
num2 = int(input("정수2: "))
def div_qr(n1, n2):
return (n1 // n2, n1 % n2)
(quotient, remainder) = div_qr(num1, num2)
print("몫: {0}, 나머지: {1}".format(quotient, remainder))
|
2d6c439e5bba4937ddd34fc9952a876770592f29 | kou466/Python | /src/Ch9/09.py | 361 | 3.5625 | 4 | data = [[21, 7, 43, 65], [2, 8, 72, 52]]
search = int(input("찾을 값: "))
flag = 0
for i in range(len(data)):
for j in range(len(data[0])):
if str(search) == str(data[i][j]):
print("위치: ", i + 1, '행', j + 1, '열')
flag = 1
break
if i + 1 == len(data) and flag == 0:
... |
f1c325ac6b788f5586ff815d3137b2fce0629cef | MrScabbyCreature/Chinese_phonetics | /chinese.py | 8,732 | 3.859375 | 4 | import pandas as pd
import numpy as np
from random import shuffle
from IPython.display import display as display_dataframe
print("Practice what?\n1) Left column(hanze->pinyin) \n2) Right column(meaning->hanze+pinyin)")
choice = input()
### left column
if choice == '1':
df = pd.read_excel("left_row.xlsx")
if '... |
bd1268244c535712fa6616edbf7b2a015867b30e | mikephys8/The_Fundamentals_pythonBasic | /week7/9-1.py | 1,005 | 4.1875 | 4 | __author__ = 'Administrator'
tup = ('a', 3, -0.2)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[-1])
print('-------------')
print(tup[:2])
print(tup[1:2])
print(tup[1:3])
print(tup[2:3])
print(tup[2:])
print('-------------')
# tuples arer immutable!!cannot be assigned with other
# value in opposition with list
#... |
df03c816a727f6c4afc895554fa9b27ff178e830 | mikephys8/The_Fundamentals_pythonBasic | /week6/8-5.py | 736 | 3.578125 | 4 | __author__ = 'Administrator'
flanders_filename = 'lecture_code_week6_In Flanders Fields.txt'
file = open(flanders_filename, 'r')
# --------------------------------------------
# with open(flanders_filename, 'r') as flanders_file:
# for line in flanders_file:
# print(type(line))
# # print(flanders_fi... |
4c7509bcf3d66b2d1f76e319704beca51caa275d | mikephys8/The_Fundamentals_pythonBasic | /week3/4-4.py | 596 | 3.9375 | 4 | __author__ = 'Administrator'
import math
def perimeter(side1, side2, side3):
return side1 + side2 + side3
def semiperimeter(side1, side2, side3):
return perimeter(side1, side2, side3) / 2
def area_hero(side1, side2, side3):
"""
(number, number, number) -> float
Return the area of a triangle ... |
287562dd5e27e13c7e13b78f28b43482b68677b4 | mikephys8/The_Fundamentals_pythonBasic | /week5/7-6.py | 493 | 4 | 4 | __author__ = 'Administrator'
for i in range(10):
print(i)
help(range)
# for presenting only odd indices starting at 1, ending at 11-1, with pace 2
for i in range(1, 11, 2):
print(i)
print('\n\n')
# for presenting only even indices starting at 0, ending at 11-1, with pace 2
for i in range(0, 11, 2):
print(... |
74193ef2ceb97651df706dd1664ddd00e9055684 | ferozumair786/UTDS-Python-HW | /PyBank/main.py | 2,665 | 3.859375 | 4 | import os
import csv
import random
#import file
banking = os.path.join("budget_data.csv")
#Set variables
months = 0
total = 0
profit = []
difference = 0
dates = []
#delta doesn't start out empty to keep the same number of items as the original csv
#this helps when we zip the two lists
delta = [0]
maximum = 0
minimum... |
fe41b44e50f5fe906a383ea7dd7de93e73356974 | SrinivasAniruddh/Python-CI | /Aniruddh-Homework-6.py | 9,735 | 3.671875 | 4 | import argparse
import os.path
import csv
import matplotlib.pyplot as graph
import numpy as np
""" Variables """
file_dictionary = {}
sorted_list = []
def parser_function():
""" Take arguments from command line """
parser = argparse.ArgumentParser()
parser.add_argument("data_file", type=s... |
bc3fcbb74e18772fca6ab9465545aa15c079e509 | cdp404/Lecture_5 | /if_comp_func.py | 228 | 4.03125 | 4 | n_list = list(range(1,100))
#짝수만 제곱하여 배열 만들기
squre_arr = [x**2 for x in n_list if x%2 ==0]
print(squre_arr)
print("")
squre_arr_2 = [x**2 for x in n_list if (x%2 == 0 and x%3 == 0)]
print(squre_arr_2) |
bc7ee177ac538cc0b220a85d1237344b26e8daeb | yzk19930501/optopsy | /optopsy/strategy.py | 8,211 | 3.765625 | 4 | class Node(object):
"""
The Node is the main building block in bt's tree structure design.
Both StrategyBase and SecurityBase inherit Node. It contains the
core functionality of a tree node.
Args:
* name (str): The Node name
* parent (Node): The parent Node
* children (dict, list):... |
bdfffd477107af8364d89f7b57586da334e31291 | brianmirabito/SentimentBH | /visualize.py | 2,414 | 3.59375 | 4 | import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import os
green = (62, 201, 83)
red = (194, 52, 33)
# pos_per : int - Positive Percentage
# neg_per : int - Negative Percentage
# neu_per : int - Neutral Percentage
# title : str - title of the piechart
# labels : tuple of str - IN THE ORDER... |
fa0a5339fb9ab705810c28b143a04ea14540659e | mboglesby/learning-python | /followLinks.py | 4,201 | 3.796875 | 4 | ##########################################################################
## followLinks.py - v1.0 ##
## Created by Michael Oglesby for 'Using Python to Access Web Data' ##
## class offered by University of Michigan on Coursera ##
## Usage: python3 followLinks.py ##
## Description: Prompts the user for a url... |
035b6c28e1b373fef200773cdc73a940a98d8f7c | arrpitsharrma/PreCourse_1 | /Exercise_4.py | 1,528 | 4.25 | 4 | # Time Complexity : not sure
# Space Complexity : not sure
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : had a hard time dealing with tree, I get stuck when I come across trees and linked list for basic things sometimes
# Python program to insert element in binary tree... |
840f4b5f3d7dbb11fd65e266fbff83561e4f729b | kancha-supriya/python_samples | /test2.py | 1,139 | 4.25 | 4 | """
Return true for palidrome
test with case sensitive and non case sensitive
EG : Madam
"""
import string
class Palindrome:
@staticmethod
def is_palindrome(word):
if word[::-1] == word:
return True
if word[::-1].lower() == word.lower():
return True
... |
bcee89239b819b7f8f694857a2179b7fab6c2276 | kancha-supriya/python_samples | /python_property.py | 2,162 | 3.734375 | 4 | class Song:
def __init__(self, title, artist):
self.title = title
self.artist = artist
def show_title(self):
print("Listening to {} and {}".format(self.title, self.artist))
def get_title(self):
return self._title
def set_title(self, title):
self._ti... |
eeb3c3d09ed90cb91f03bc21991b292d7be58f9a | emmas0507/leetcode | /largest_number.py | 339 | 4 | 4 | def sort_func(a, b):
if (a+b) > (b+a):
return 1
else:
return -1
def largest_number(list):
list = sorted([str(l) for l in list], cmp=sort_func)
print(list)
res = ''
for i in range(len(list)-1, -1, -1):
res = res + list[i]
return res
list = [3, 30, 34, 1, 9]
print(lar... |
de46554d58c60d17ab16934e1ef2cac51da0ad59 | emmas0507/leetcode | /word_search.py | 1,677 | 3.8125 | 4 | def word_search(board, target):
def helper(board, i, j, visited, target):
print('board char is {}'.format(board[i][j]))
if len(target) == 0:
return True
res = False
if i > 0 and board[i-1][j] == target[0] and ~visited[i-1][j]:
visited[i-1][j] = True
... |
af336045fbc767422f3142442bfa426bffbe18bc | emmas0507/leetcode | /reverse_words_in_string.py | 627 | 3.890625 | 4 | def reverse_words_in_string(str):
str = str + ' '
rev_str = ''
word = ''
for i in range(len(str)-1):
if str[i] == ' ' and str[i+1] != ' ':
word = ''
elif str[i] != ' ' and str[i+1] == ' ':
word = word + str[i]
rev_str = word + ' ' + rev_str
eli... |
0c5b50ce4ad025cc0f4006bbbe782ac3725b9dd8 | emmas0507/leetcode | /mini_parser.py | 836 | 3.625 | 4 | def mini_parser(input):
if input[0] != '[':
return input
s = []
val = ''
for i in range(len(input)):
curr = input[i]
if curr.isdigit():
val = val + curr
else:
val = ''
if curr.isdigit() and i != len(input)-1 and (not input[i+1].isdigit()):
... |
d23f40bbecc03a92b9d619293b3f2c6059fd27d0 | amaguri0408/AtCoder-python | /nomura2020/b.py | 113 | 3.625 | 4 | S = input()
ns = ""
for i in S:
if i == '?':
ns += 'D'
else:
ns += i
print(ns) |
addeb9021eab137056a04246b4ae31a13f85aa73 | amaguri0408/AtCoder-python | /ABC153/d.py | 174 | 3.875 | 4 | h = int(input())
mon_num = 1
count = 1
while True:
if h <= 1:
break
else:
h //= 2
mon_num *= 2
count += mon_num
print(count) |
3cf081e6e3c92f6ba722ff083a34d47c86e117b9 | AusadaNuchpramul/workshop2 | /python_dictionaries/loop_dictionarise5.py | 116 | 3.546875 | 4 | thisdict = {"brand":"Ford", "model": "Mustang", "year":1964}
for key,value in thisdict.items():
print(key,value) |
1435d216e02c7adc0254b452a46c4a764d69e23e | AusadaNuchpramul/workshop2 | /python_lists/join_list.py | 93 | 3.75 | 4 | list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 +list2
print(list3) #list = [1, 2, 3, 4, 5, 6] |
cbd06065723c79d4d659f5124673a496b1f07aae | eyesolaris/Patterns | /Spectator/Spectator.py | 1,360 | 3.78125 | 4 | from abc import abstractmethod, ABC
class ISubscriber(ABC):
@abstractmethod
def notify(self, video):
pass
class Video:
def __init__(self, name):
self.name = name
class User(ISubscriber):
def __init__(self, user_name):
self.user_name = user_name
def notify(self, video):
... |
4eed0186c31fc98be8be7f9f0c435bc2568bce9f | angelobento/comandos-simples- | /comando find.py | 307 | 4.0625 | 4 | frase =input("digite uma frase:")
f = (input("o que quer encontrar?"))
r = frase.find(f)
if f == r:
print("{} existe na sua frase".format(f))
#esse comando não terminado tem por objetiva achar uma palavra dentro de
#uma frase, não consegui fazer dar certo
|
c862dcc4f21c93f23d002b8de1eae73ad617b27a | angelobento/comandos-simples- | /correção p.py | 894 | 3.53125 | 4 | #imprima com o po na frente
# s = "a casa branca"
# n=len(s)
# ns = "P"
# for k in range (n):
# if s[k]==" ":
# ns=ns+" P"
# else:
# ns=ns+s[k]
# print(k,ns)
s = "10 de outubro de 2019"
res = "10/01/2019"
n=len(s)
if s[6:9]=="jan":
print(s[0:2]+"/01/"+s[n-4:n])
if s[6:9]=="fev":
pr... |
ac868e4ce6c57d500cdf96d4600dc601f5baf91e | y0y00700/python | /python_workspace/0712.py | 812 | 3.515625 | 4 | import os
import calendar
import random
print(os.environ)
#os 관련 함수 os.mkdir 디렉터리 생성
# print(calendar.calendar(2021)) // 2021년 달력 출력
print(random.random()) # 0.0 ~ 1.0 사이의 랜덤 난수
print(random.randint(1,45)) # 로또
def random_pop(data):
number=random.randint(0,len(data)-1)
return data.pop(number)
data=[... |
ce0c70bdb4fb838610a27d861f742310121b19cd | ArkadeepAdhikari/Mini-Blockchain | /block.py | 1,414 | 3.953125 | 4 | import datetime
from hashlib import sha256
#sha256 generates a 256 bit (32 byte) signature or hash for a given text data
class Block:
"""
Defines variables and functions for a block of transactions of the Blockchain
"""
def __init__(self, transactions, previous_hash):
"""
Initializes the esse... |
2136514c60681b0f410f8df550d035381f09be43 | 20132464/yiguo_leetcode | /剑指offer/01二维数组的查找.py | 903 | 3.96875 | 4 | # 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
# [
# [1,2,8,9],
# [2,4,9,12],
# [4,7,10,13],
# [6,8,11,15]
# ]
# 给定 target = 7,返回 true。
# 给定 target = 3,返回 false。
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
... |
cead2e23392bd37de5a16e9d862b02283e81e79a | d-shipley/MTMW12_assig1 | /Q2-3_gaussian-quadrature.py | 8,189 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# gaussian-quadrature.py
#
# A program to integrate any function of one variable between any limits and
# to any required resolution.
#
# The integration is carried out by the function "gauss_int".
#
# A couple of test functions, whose integrals are known analy... |
dab28b079bc639c5dfe548c8df4aee114d4593e5 | ggeo/Machine_Learning | /Linear_regression.py | 1,651 | 3.703125 | 4 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import linear_model, cross_validation
sns.set()
data = pd.read_csv("./Datasets/Advertising.csv", names=['TV', 'Radio', 'Newspaper','Sales'], header=0)
fig = plt.figure()
ax = plt.axes()
tv = data.loc[:, 'TV'].t... |
a662d0ba108c778eabc880a98c81767894b9e31e | jon-rutledge/Notes-For-Dummies | /Python/ListsAndStrings.py | 1,198 | 4.1875 | 4 | #strings and lists
testList = list('Hello')
print(testList)
print(testList)
#strings are immutable data types, they cannot be modified
#if you need to modify a string value, you need to create a new string based the original
#References
#with one off variables you can do something like this
spam = 42
cheese = spam... |
7627b6e875fd19b364ffa887b44cf73d87b244cb | ravikiranrv/session9-ravikiranrv | /session9.py | 3,335 | 3.5 | 4 | from time import perf_counter, localtime
from collections import defaultdict
from functools import wraps, singledispatch
from datetime import datetime, timezone
from decimal import Decimal
from html import escape
def odd_sec_run(time:datetime):
"""
This is a decorator factory which takes a parameter
# par... |
035632d93b68218570bf07d3fddd64e63b1ede39 | sztanko/flightprices | /data/distance.py | 760 | 3.71875 | 4 | from math import radians, cos, sin, asin, sqrt
import sys
def haversine( lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [float(lon1)... |
dfad69ddd3d7eb4fa0d7c2ab3ed72edd4bc28d61 | jwraw94/CS50-2019-Projects | /pset6/sentimental/caesar/caesar.py | 851 | 4.03125 | 4 | import cs50
import sys
from cs50 import get_string
def main():
count = len(sys.argv)
# Check correct no. of arguments
if count != 2:
print("Usage: ./caesar k")
sys.exit(1)
else:
print("plaintext: ", end="")
instring = get_string()
print("ciphertext: ", end="")
... |
bb29a2643efdbb31fa0ebe8c5c92442a874f3e5b | gergodanko/1st-SIW-2019-09-13 | /riskdice.py | 1,598 | 3.875 | 4 | import random
x="y"
while x=="y" or x=="Y":
attacker=[]
defender=[]
attunit=0
defunit=0
natt=0
ndef=0
while natt==0 or natt>3 :
while True:
try:
natt=int(input("How many units attack? :"))
break
except:
... |
afb121bba2aad421c5253423f6e9efbbc4b64325 | mapleyustat/classes | /bigData/HW/HW6/hw6.py | 1,971 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
conn = sqlite3.connect(":memory:");
def run_in_db(txt):
# print "running: " + txt
conn.execute(txt)
def create_table( tbl_name, *rest):
qry = "CREATE TABLE " + tbl_name + " (" + tbl_name + " text, "
for r in rest:
qry = qry + r + " tex... |
3cdc151abf8b3d094b0efe4b833ffee6d05866e9 | nikhil-kamath/Scheduling | /DateTimeInput.py | 1,685 | 4.1875 | 4 | import datetime as dt
class DateTimeInput:
def __init__(self):
pass
def input_date(self) -> dt.date:
'''gets input from console and returns DATE object'''
goal_date_str = input("Enter a date at which our code should run: ").split()
if goal_date_str[0] == 'today':
re... |
712f5c9a5b8e449043d441f23458045a5ccb5740 | DeepLearningMoviesProject/back-DeepLearningMoviesProject | /MovieProject/tests/unit/test_tweets.py | 2,995 | 3.515625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 8 15:08:55 2017
@author: coralie
"""
from MovieProject.preprocessing import tweets
from MovieProject.preprocessing.tools import opinionDict
import unittest
class TweetsTest(unittest.TestCase):
"""Test case used to test the module 'preprocessi... |
7eac991b9e3580a24f45ff3ba8826b26e37a0229 | itsskylinee/Casual-Programs | /quadratic.py | 646 | 4.09375 | 4 | from math import *;
print("We support equations like ax^2+bx+c=0");
print('Let "a" be zero to get a linear equation.');
print();
a = eval(input('input coefficient "a":'));
b = eval(input('input coefficient "b":'));
c = eval(input('input coefficient "c":'));
DELTA = b*b-4*a*c;
if DELTA < 0:
print("Your ... |
d4a8bd4e8e212950b246d5b1a2dba83eb08c669e | mhipo1364/takh | /test.py | 1,008 | 4.1875 | 4 | __author__ = 'moefar'
def is_divisible(x, y):
"""
Check if x is divided by y
:param x: int
:param y: int
:return: bool
"""
if x % y == 0:
return True
def divisible_by_three(x):
"""
Returns proper string if x is divided by 3
:param x: int
:return: str/None
... |
c0cb5fd5f34afc1665cefcd9ef72ace9c7bcaf34 | weiyang-1/sort_practice | /Heapsort.py | 1,353 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
@Created: 2020/10/19 16:23
@AUTH: MeLeQ
@Used: pass
"""
from tools import *
def build_heap(p_list: list) -> None:
"""
构建大顶堆
:param l:
:return:
"""
l_len = len(p_list)
for i in range((l_len - 2) // 2, -1, -1):
re_heap(p_list, l_len, i)
def re_heap(r_l... |
bc30eede52bb85c8ffb728ac9b423c7be351d661 | e-petrova/pass-miniproject | /mypasswd/passwd.py | 784 | 3.609375 | 4 | import random
def read_words(filename):
file = open(filename, 'r')
words = []
for word in file:
words.append(word.strip())
return words
nouns = read_words("./nouns.txt")
adjs = read_words("./adjectives.txt")
def generate():
noun = random.choice(nouns)
adj = random.choice(adjs)
noun = noun[0].upper() + no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.