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 |
|---|---|---|---|---|---|---|
2bdef9e5603d78a8739d5123b8d80a6b6021d567 | DanJimm/AlgorithmStudy | /[88]合并两个有序数组.py | 1,825 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/7/16
@Author : jim
@File : [88]合并两个有序数组
@Description :
"""
# 思路1:创建一个新数组,遍历两个目标数组,分别将头元素放进数组,不满足原地操作的要求
# 思路2:直接合并数组,然后排序,这个时间复杂度太高了
# 思路3:官方题解,从后方开始遍历,一次把较大元素放到nums1的结尾
# 自己看了题解写了一版代码,效率不好,感觉逻辑也有冗余
def merge(self, nums1: List[int], m: int, nums2: List[in... |
95a4b5c79ecf4c15acd1ff925dbec471b93d50cd | DanJimm/AlgorithmStudy | /DFS&BFS.py | 896 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/7/24
@Author : jim
@File : DFS&BFS
@Description :
"""
# DFS 迭代
# 记录遍历过的节点
def DFS(node,visited):
# 终止条件,全部节点都访问完了一遍
if node in visited:
return
visited.add(node)
# 将访问过的节点加入数组保存--重要
# 继续处理下一层的节点
for node_next in node.child:... |
04e8eebe6ea51d1b7c668608491a606dddf2f9a8 | DanJimm/AlgorithmStudy | /初级和高级排序.py | 3,758 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/8/22
@Author : jim
@File : 排序
@Description :
"""
arr = [45,23,65,9,24,1,5,62,88,14,3,41,42,33,24]
# 选择排序,依次遍历数组,每次取最小的一个放在最前,总的时间复杂度 O(n^2)
def selectionSort(arr):
n = len(arr)
for i in range(n-1):
smaller ,tmp = arr[i] ,i
for j in... |
6ce2a68c94ed4a2e14c01bce4042a79d41df8460 | koniiiik/libmultialn | /utils/alignment_density.py | 590 | 3.828125 | 4 | #!/usr/bin/env python3
"""
This simple utility reads a MAF file and calculates the density of the
sequences contained within (i. e. the number of dashes divided by the sum
of sequence lengths).
"""
from sys import argv, exit, stderr
if len(argv) != 2:
print("Usage: %s <file.maf>" % (argv[0],))
exit(1)
total,... |
2b57a40a3b3e9cbb7a00a5b7a4b9eeab1bb1e84b | schlerp/R-Pee-G | /world/mapping.py | 5,570 | 3.5 | 4 | from random import randint
import characters
import world
import items
def pick_rand_room(width, height, blacklist=[]):
'''selects a random room from the map'''
while True:
x = randint(0, width-1)
y = randint(0, height-1)
choice = world.world.Location(x,y)
if choice not in bla... |
7cc89197b544b3f66546da66eebc21d852db8a64 | schlerp/R-Pee-G | /items/consumables.py | 3,197 | 3.625 | 4 | #from items import Item
import items
# CONSUMABLES
class Consumable(items.Item):
'''base class for all consumable items'''
def __init__(self, name, description='consumable', quantity=1, removable=True):
super().__init__(name, description)
self.quantity = quantity
self.removable = remo... |
37a07322a2285e748b634cc639e28b779b4186c1 | jazywica/Computing | /_03_Principles_of_Computing_1/_05a_GreedyBos_practice.py | 4,577 | 3.890625 | 4 | # -*- encoding: utf-8 -*-
""" Simulator for greedy boss scenario: Incrementing salary by making bribes """
# use following link to test the program in 'codeskulptor': http://www.codeskulptor.org/#user45_oVlrvF97EJ_2.py
import math
try:
import simpleplot # access to plotting module
import codeskulptor
... |
b72a4368d238a2328ee2f39e73b5c82a148e5a8d | jazywica/Computing | /_03_Principles_of_Computing_1/_01_Merge.py | 1,182 | 4.0625 | 4 | # -*- encoding: utf-8 -*-
""" MERGE - Merge function for 2048 game: adds the same digits and removes zeroes """
# use following link to test the program in 'codeskulptor': http://www.codeskulptor.org/#user45_vCzpSt1yr2_3.py
def merge(line):
""" Function that merges a single row or column in 2048. """
... |
61cd6f0c5e879e94b8f44b5aefa5c30b5f55871f | jazywica/Computing | /_04_Principles_of_Computing_2/_03_TicTacToe_Minimax_testing.py | 4,577 | 3.515625 | 4 | # -*- encoding: utf-8 -*-
""" Template testing suite for TIc Tac Toe - this is the TESTING SUITE, all tests are run from here """
import poc_simpletest # this imports our testing engine
import _03_TicTacToe_Minimax as tictac # this imports the algorithms we are going to test
import poc_ttt_provided as provided
... |
8b0222d0314beb0a3ceb76d601ff1dd7803b8834 | jazywica/Computing | /_01_Interactive_Programming_1/_01_Rock-paper-scissors-lizard-Spock.py | 2,086 | 4.3125 | 4 | """ ROCK-PAPER-SCISSORS-LIZARD-SPOCK - simple game: player vs random computer choice """
# use following link to test the program in 'codeskulptor': http://www.codeskulptor.org/#user45_uPVHROOe6b_2.py
# The key idea of this program is to equate the strings "rock", "paper", "scissors", "lizard", "Spock" to numbers a... |
0bf933a09d8873a08bf01aaa073d5b46ac3777d3 | jazywica/Computing | /_04_Principles_of_Computing_2/poc_grid.py | 3,640 | 3.765625 | 4 | """ Grid class """
#http://www.codeskulptor.org/#poc_grid.py
EMPTY = 0
FULL = 1
class Grid:
""" Implementation of 2D grid of cells. Includes boundary handling """
def __init__(self, grid_height, grid_width):
""" Initializes grid to be empty, take height and width of grid as parameters. Inde... |
f84d5492e65008f41db8621ce7498e58dac971da | kodeskolen/tekna_agder_v21 | /dag2/live-koding/in_strenger.py | 236 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 18:35:32 2021
@author: Marie
"""
tekst = input("Skriv en beskjed: ")
tekst = tekst.lower()
print(tekst)
if "spam" in tekst:
print("Spam detektert!")
else:
print("Ingen spam!") |
343bed478ce28e026ec85d3e2056bb277e7006c2 | CrescenzoDeLuca/HelloWorld | /paridisp.py | 98 | 3.78125 | 4 | A=input("inserisci numero == ")
A=int(A)
if (A%2)==0:
print("pari")
else:
print("dispari") |
7cbc233e0289a4d8a78fa091347bd54db0c9ebbe | dongmeic/PythonLearning | /FB_PythonBasic/L0_functions/main.py | 1,436 | 4.09375 | 4 | import random
import time
###提示语部分
print('你好,我是机器人小埋,我们来玩个猜年龄的小游戏吧~(◆◡◆)')
time.sleep(2)
print('''
=============================
干物妹!うまるちゃんの年齢
=============================
''')
time.sleep(1)
print('小埋的真实年龄在1到10之间哦~')
time.sleep(1)
print('不过,你只有5次机会哦~')
time.sleep(1)
print('下面,请输入小埋的年龄... |
6658a147827c0582c57c8c2cfb644a1342ef51ef | arnaudmiribel/streamlit-extras | /src/streamlit_extras/word_importances/__init__.py | 2,050 | 4.15625 | 4 | from typing import List
import streamlit as st
from .. import extra
@extra
def format_word_importances(words: List[str], importances: List[float]) -> str:
"""Adds a background color to each word based on its importance (float from -1 to 1)
Args:
words (list): List of words
importances (list... |
e709bb323fc446f3bb725c0f99399f6679cfc1a3 | CharlesYang1996/Cells_Detection_Chromophobe_1.0.0 | /k_means_1D.py | 2,813 | 3.53125 | 4 | import random
import numpy as np
from math_test import*
file=open('test_list.txt', 'r')
test_dataset = [float(x.strip()) for x in file]
file.close()
print(test_dataset)
def k_means_1d_def(dataset,k,loop_times):
finial_result=[]
random_list=[]
counter=0
while (counter < k):
... |
df89794886fad74666ac50fcf7bbcfc878df3af9 | sonyarpita/ptrain | /arithmetic1.py | 251 | 3.953125 | 4 | a=float(input("Enter a number"))
b=int(input("Enter a numer"))
#a=10
#b=5
add=a+b
sub=a-b
mul=a*b
div=a/b
mod=a%b
coeffi=a//b
print("Add is",add)
print("Sub is",sub)
print("Mul is",mul)
print("Div is",div)
print("Mod is",mod)
print("Coeff is",coeffi)
|
d9760fcbe2c615552887a271c707beb0bc7018b3 | sonyarpita/ptrain | /function_recursive.py | 260 | 4.53125 | 5 | def calc_factorial(x):
"""This is recursive function
to find the factorial of an integer"""
# return(x*calc_factorial(x-1))
if x == 1:
return 1
else:
return (x*calc_factorial(x-1))
num=5
fact=calc_factorial(num)
print("Factorial of",num,"=",fact)
|
c83c122013317997832ccddf12878d532b6092c9 | sonyarpita/ptrain | /break.py | 58 | 3.890625 | 4 | for i in range(1,6):
if i==3:
break
print ("i is:",i)
|
43e17fcf7db3edb588ca8282643f0fdb23fa21a7 | sonyarpita/ptrain | /GUI/calc_button.py | 482 | 3.71875 | 4 | import tkinter as tk
import calculator as calcs
user_button=tk.Tk()
#user1_button=tk.Tk()
user_button.title("Creating a Button")
#user1_button.title("Quit a Button")
#button=tk.Button(user_button,text="Submit",width=50,command=user_button.destroy)
button=tk.Button(user_button,text="Calculate",width=50,command=calcs.sum... |
662ed97b3d686b28c2345a53425b37ffd871055d | sonyarpita/ptrain | /ReModule/Metacharacters/alternation.py | 222 | 4.34375 | 4 | import re
str = "The stays rain in Spain maui falls mainly in the plain!"
#Check if the string contains "falls" or "stays"
x=re.findall("falls|stays",str)
print(x)
if (x):
print("match")
else:
print("No Match")
|
f81c2ada9416a5e200312ef5086739fe1dd38768 | sonyarpita/ptrain | /Class/assignment_bank_account.py | 2,176 | 3.96875 | 4 | from random import randint
class BankAccount:
'''userName=""
aadharNumber=0
accountNumber=0
initialBalance=0
'''
def __init__(self):
self.username=input("Enter Username ")
self.aadharNumber=int(input("Enter aadhar number "))
self.accountNumber=randint(0,999999999999)
... |
8f167f28002b91f926c295843a0131fa194c04b9 | sonyarpita/ptrain | /Advanced_Functions/unzip_1.py | 570 | 4.25 | 4 | #Python code to demonstrate zip()
#initialize lists
name=["Sony","Arpita", "Das","Susmita"]
roll_no=[4,3,6,7]
marks=[90,98,89,99]
#using zip() to map values
mapped=zip(name,roll_no,marks)
#converting values to print as set
mapped=list(mapped)
#printing result values
print("Zipped result is: ",end=" ")
print(mapped)
pri... |
c5e479596ae378b626fbbc2ecec067aa5579a522 | sonyarpita/ptrain | /Assignment_22ndNov/swap_specific_elements_in_list.py | 769 | 4.09375 | 4 | num_of_nums=int(input("Enter number of numbers to be sorted: "))
user_input_num_list=[]
def enter_list_elements(x):
for i in range(x):
y=int(input("Enter elements: "))
user_input_num_list.append(y)
return user_input_num_list
print("List before swap",enter_list_elements(num_of_nums))
def print_... |
4a7a49042b781673d342d6a81359d895e393431f | sonyarpita/ptrain | /Modules/user_module3.py | 168 | 3.578125 | 4 | from calculator import *
x=int(input("Enter first number: "))
y=int(input("Enter second number: "))
print(sume(x,y))
print(subs(x,y))
print(mult(x,y))
print(divi(x,y))
|
34eac70c92dcde4bf83ce56fbf2d27614db596ad | sonyarpita/ptrain | /Collections/my_chainmap.py | 604 | 3.609375 | 4 | from collections import ChainMap
dict1={'name':"" , 'surname':"" , 'company': ""}
dict1['name']=input("Enter name: ")
dict1['surname']=input("Enter surname: ")
dict1['company']=input("Enter company name: ")
print(dict1)
dict2={'dept':"", 'design':"", 'salary':""}
dict2['dept']=input("Enter dept: ")
dict2['design']=in... |
a3fcfa1418dcab9e79889464cb57ffe03020ef61 | sonyarpita/ptrain | /Class/operator_overloading.py | 322 | 3.984375 | 4 | class addOvrld:
def __init__(self,a=0,b=0):
self.a=a
self.b=b
def __str__(self):
return "({0},{1})".format(self.a,self.b)
def __add__(self,other):
a=self.a+other.a
b=self.b+other.b
return addOvrld(a,b)
obj1=addOvrld(2,3)
obj2=addOvrld(2,2)
obj=addOvrld(2,3)
print("Addition of 3 Objects= ", obj1+obj2+obj)... |
90209c1052baab2eb3a7ab231fcd64d1538e3fc6 | sonyarpita/ptrain | /Threads/thread_2.py | 323 | 3.59375 | 4 | import time
from threading import Thread
def calculation():
a=10
b=20
res=a+b
return res
def sleepFun(x):
print("Thread",x,"is going to sleep for seconds")
time.sleep(2)
print("Thread",x,"is active now")
for i in range(10):
th=Thread(target=sleepFun,args=(i,))
th.start()
res=calculation()
print("Result= ",re... |
cf71d6e1551ef31ae66221a71592cba7504463bf | sonyarpita/ptrain | /Assignment_11thDec/convert_first_letter_in_a_sentence_to_capital_letter.py | 247 | 3.84375 | 4 | user_list=list(input("Enter word/sentence: "))
for i in range(len(user_list)):
if ord(user_list[i])==32 and ord(user_list[i+1])>96:
asci=ord(user_list[i+1])-32
user_list[i+1]=chr(asci)
str=''.join(user_list)
print("Evaluated Sentence: ",str)
|
45b48289f503fef6804ebe1cada32972c64d1af7 | sonyarpita/ptrain | /Assignment_22ndNov/without_list_methods_largest_smallest_list.py | 1,383 | 3.96875 | 4 | num_of_nums=int(input("Enter number of numbers to be sorted: "))
user_input_num_list=[]
simi=[]
def enter_list_elements(x):
for i in range(x):
i=int(input("Enter elements: "))
user_input_num_list.append(i)
return user_input_num_list
print("List=",enter_list_elements(num_of_nums))
def similar(user_input_num_lis... |
d0e168e50a08cc1cbf9efae1a3966ff02f3f3ab9 | sonyarpita/ptrain | /input_list.py | 119 | 3.796875 | 4 | a_list=[]
for i in range(5):
#abc=int(input("Enter data"))
abc=input("Enter data")
a_list.append(abc)
print(a_list)
|
f63386a5b3cb3c829f318691f3e87fb878d4a56a | sonyarpita/ptrain | /ReModule/Metacharacters/Period.py | 235 | 4.125 | 4 | import re
str = "hello world helo"
# search for a sequence that starts with "he", followed by two (any)characters, and an "o"
x=re.findall("he..o", str)
print(x)
x=re.findall("he...o", str)
print(x)
x=re.findall("he.o", str)
print(x)
|
3a9d2e9ddcb4ded42e2df4130db0cb1b87e5cf35 | sonyarpita/ptrain | /Advanced_Functions/zip_1.py | 317 | 4.28125 | 4 | #Python code to demonstrate zip()
#initialize lists
name=["Sony","Arpita", "Das","Susmita"]
roll_no=[4,3,6,7]
marks=[90,98,89,99]
#using zip() to map values
mapped=zip(name,roll_no,marks)
#converting values to print as set
mapped=list(mapped)
#printing result values
print("Zipped result is: ",end=" ")
print(mapped)
|
a8231b78e16cf3da03bb977ab5062361a87b68a7 | hellomichiyabu/Practice | /Python/じゃんけんゲーム/utils.py | 567 | 3.578125 | 4 | def validate(hand):
if hand < 0 or hand > 2:
return False
return True
def print_hand(hand, name='ゲスト'):
hands = ['グー', 'チョキ', 'パー']
print(name + 'は' + hands[hand] + 'を出しました')
def judge(player, computer):
if player == computer:
return '引き分け'
elif player == 0 and comp... |
61e9960800c4707b98c1a2bd3e4ce942f9cfc2ec | jasongoat12/Python-Learn- | /03_28_2021/given3nums.py | 1,021 | 4.0625 | 4 | # #Given three numbers x, y and m where 1 <= x < y <= m, use x and y to compose the largest possible number that is <=m. You can use any number of x and y.
# For instance, when x=17, y=25, and m=77, the output will be 76 because 17*3 + 25*1 = 76 and you can't compose 77 with 17 and 25.
# Think about how you solve thi... |
840198700ca7b067c8e6f44fea6bcb5ec3f4b544 | jasongoat12/Python-Learn- | /dupeints.py | 238 | 3.796875 | 4 | def dupefind(arrays):
empty_arr = []
for i in arrays:
if i in empty_arr:
return True
else:
empty_arr.append(i)
return False
arrays = [0,1, 1]
print(dupefind(arrays))
|
7577265cce5bc3eb08371d9a1f50e3ce915a72bf | diligent-1618/test1-python- | /15data view-learn/15.2折线图,散点图/02-折线图进阶.py | 549 | 3.671875 | 4 | import matplotlib.pyplot as plt
#相当于仅仅描绘出几个二维坐标点
squares = [1,4,9,16,25]
plt.plot(squares, linewidth=5)#相当于传输进入折线数据,并规定折线粗细
#设置图表标题,并给坐标轴加上标签fontsize是文字的大小
plt.title("Square Number",fontsize=24)#标注标题的名称
plt.xlabel("Value",fontsize=14)#标注x轴的名称或者单位
plt.ylabel("Square of Value",fontsize=14)#标注y轴的名称或单位
#设置刻度标记大小
plt.t... |
34d9f963f488157744b873b1d6eb7e67cfefbe72 | Chirkh/Gravity-simulation | /Gravity.py | 5,318 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created in August 2021
@author: Chirayu
"""
'''This is a gravity simulation for the n-body problem. I have used pygame for the animation and classes to make
planet objects. In order to calculate changes of position of the planets I have assumed constant acceleration
for a given ... |
b92aafbb88ec580b5cce1ac9ac43d0fbcd482937 | seekerFactory/spelled | /testCases/basic.py | 473 | 3.71875 | 4 | def test(case_types):
testinput={}
if (case_types == 'hindi'):
testinput = {"हिन्दी" : "हीन्दी", "घर": "घार", "घर": "घरम", "बाहर": "बहर", "अगर": "आरग"};
elif (case_types == 'english'):
testinput = {'correct': 'corect', 'in': 'iin', 'going': 'goin', 'see': 'cee'};
elif(case_types == 'special'):
testinput = {'... |
4a709ced79a10b6617a2250456839a61b374f3c8 | bezzzon/python-basics | /home_work1/task5.py | 1,370 | 4.125 | 4 | """
- Запросите у пользователя значения выручки и издержек фирмы.
- Определите, с каким финансовым результатом работает фирма
(прибыль — выручка больше издержек, или убыток — издержки больше выручки).
- Выведите соответствующее сообщение.
- Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение... |
1d406ac301ee070563197fb69a6f7d9c7702b6f5 | bezzzon/python-basics | /home_work5/task3.py | 956 | 4.21875 | 4 | """
Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
Выполнить подсчет средней величины дохода сотрудников.
"""
threshold_amount = 20000
def get_salary(record):
return ... |
fa584d09f53a69bc362b3c614455df709e181ed4 | bezzzon/python-basics | /home_work2/task2.py | 1,953 | 4.34375 | 4 | """
Для списка реализовать обмен значений соседних элементов, т.е.
Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input().
"""
arr = []
while True:
el = input('Pl... |
a138925a0d2a186a8dae773eab7505d761d9b59e | bezzzon/python-basics | /home_work7/task3.py | 4,361 | 3.921875 | 4 | """
Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка.
В его конструкторе инициализировать параметр, соответствующий количеству клеток (целое число).
В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (__add__()), вычитание (__sub__()),
умножение ... |
fb2742b091b766ba7418bd90444777c0e1f80ee1 | vergeeva/learning_python | /Day_2/cycle_for.py | 811 | 3.71875 | 4 | for x in ['spam', 'eggs', 'ham']:
print(x, end=' ')
# spam eggs ham
print('\n___________________________')
object1 = [{1, 4}, {44, 33}, {12, 45}]
for a, b in object1:
print(a, b)
# 1 4
# 33 44
# 12 45
print('___________________________')
for i in range(len(object1)):
print(object1[i])
# {1, 4}
# {33,... |
66a9927438da0694cebab7cb9ceee7c5e8e2e856 | TavoGLC/Competitions-And-Puzzles | /Puzzles/CodingChallenges/findminmax.py | 451 | 3.84375 | 4 | #Find the minimum and maximum of a list
def find_min_max(number_list):
list_length=len(number_list)
local_min=number_list[0]
local_max=number_list[0]
for k in range(list_length):
if number_list[k]<local_min:
local_min=number_list[k]
else:
... |
25248f8c85ec13abbacdffaac212278ecc892786 | AngelRBL/curso-python | /python/aritmetico.py | 288 | 3.796875 | 4 | print('Ingresa el primer valor')
num1 = int(input())
print('Ingresa el segundo valor')
num2 = int(input())
# Al sumarlos sucede un error y es concatenacion(en vez de sumarlo los une)
# Par aresolverlo tenemos que poner el input() dentro de int()
resultado = num1 / num2
print(resultado) |
4ed3ae99dd5152e93809e0feff89b8080085e70c | leeeakes/currency-converter | /currency_convert.py | 610 | 3.6875 | 4 | def get_rate(rates, orig_cur, new_cur):
"""Pulls coversion rate between two currencys"""
for rate in rates:
if orig_cur in rate[0] and new_cur in rate[1]:
conv = round(rate[2],2)
return conv
elif orig_cur in rate[1] and new_cur in rate[0]:
conv = round(1 / rat... |
3c3563aa3d40a680942c30f2b4c498ce94a768d2 | parisa-a/wave1 | /unitsoftime2.py | 934 | 3.984375 | 4 | import math
# user input of seconds
seconds = int(input("Enter a duration of time in seconds: "))
# number of days
days = math.floor(seconds / 24 / 60 / 60)
remainder1 = seconds - (days * 24 * 60 * 60)
# of hours
hours = math.floor(remainder1 / 60 / 60)
remainder2 = remainder1 - (hours * 60 * 60)
# of minutes
m... |
27ff939dd78bf7cdec3c1e27fed44784c8650d53 | Clydeclyne/collect-intelligence | /numpyLearning/1_linear_algebra.py | 213 | 3.703125 | 4 | '''
Created on 2015-6-17
@author: XXYF18
'''
import numpy as np;
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
print x
print y
print x.dot(y) # equivalently np.dot(x, y) |
700cc924cbf4725c015746ee27a3c0742c0ba2f8 | DJohnie/python_test_project | /python_project/milestone_2.py | 2,946 | 3.96875 | 4 |
# CSP 017
# Final Project - Milestone #2
data = []
choice = None
def sort():
global choice
if (choice == 0) or (choice == 1) or (choice == 2):
sortD = sorted(data, key = lambda r:r[choice], reverse = True)
else:
sortD = sorted(data, key = lambda r:(int(r[choice])), reverse = True)
... |
fac69a75140476bd6d497e92284c646d80da2da4 | Angelagoodboy/ProjectWrite | /写入程序/OpenFile.py | 1,192 | 3.578125 | 4 | import os
from tkinter import filedialog
global file_path
file_path=''
global tmp
tmp=bytes(1024)
def openbinFile():
'打开文件'
global file_path
file_path = filedialog.askopenfilename(title='选择文件',initialdir=(os.path.expanduser('C:/')),filetypes=[('BIN', 'bin')])
print('打开文件:', file_path)
return ... |
22eef780824abff7b9b4ecafe87edb0e31f66c4e | hrshenk/advent_of_code_2016 | /02/challenge_2.2.py | 1,010 | 3.65625 | 4 | class Keypad:
def __init__(self):
self.keys = []
self.keys.append([0,0,0,0,0,0,0])
self.keys.append([0,0,0,1,0,0,0])
self.keys.append([0,0,2,3,4,0,0])
self.keys.append([0,5,6,7,8,9,0])
self.keys.append([0,0,10,11,12,0,0])
self.keys.append([0,0,0,13,0,0,0])
... |
3557d49eb70f47166fc1dde01d5843b46b2f0b9d | hrshenk/advent_of_code_2016 | /07/challenge_7.1.py | 907 | 3.625 | 4 | import re
def test_ABBA(string):
for i in xrange( len(string)-3 ):
print string[i]
if ( string[i] != string[i+1] ) and ( string[i] == string[i+3] ) and ( string[i+1] == string[i+2] ):
return True
return False
file = open("input.txt", 'r')
count = 0
for line in file:
fla... |
fcc6eac74883cf64a19b5a829d4589521435c2cc | hrshenk/advent_of_code_2016 | /01/challenge_1.2.py | 1,121 | 3.59375 | 4 | file = open('input.txt', 'r')
directions = file.read().split(', ')
direction = 0 # 0 is North, 1 is East, 2 is South, 3 is West
coordinates = [0, 0]
history = {}
for d in directions:
#determine how many blocks we'll travel in this instruction
blocks = int(d[1:])
#determine the direction we'll be facing
... |
d35737cfecdb7ca18646653cb99ffe469155f494 | jalbalah/Python_DataStructures | /BinarySearch.py | 1,473 | 3.921875 | 4 | class Stack:
def __init__(self):
self.items = []
self.size = 0
def push(self, elem):
self.items.append(elem)
self.size += 1
def pop(self):
self.size -= 1
return self.items.pop()
def peek(self):
return self.items[-1]
def isEmpty(self):
r... |
b1e6630fb5d49ce89d42e2d317b8ccdbd543bb85 | zzsyjl/crack_the_coding_interview | /chap01数组与字符串/02是否互为字符重排.py | 1,458 | 3.8125 | 4 | import unittest
"""
给两个字符串,判断能否经过重新排列,让一个变成另一个。我们也要测试对中文字符的支持。
这次把中文字符给测了,但以后不必了,因为本质上都是unicode,肯定都支持的。而testcase则
要都重新写一遍,没有必要。
"""
def is_permutation(string1, string2):
"""都按照某种规则重新排列,然后直接比较即可,可以使用sorted内置函数
"""
string1_sorted = sorted(list(string1))
string2_sorted = sorted(list(string2))
return s... |
4f0156ec3aeec40da129bc7e8be6aac27b9dd3a4 | zzsyjl/crack_the_coding_interview | /chap02链表/02返回倒数第k个节点.py | 957 | 3.8125 | 4 | import unittest
from linked_list import LinkedList
"""
找出单向链表中倒数第k个节点
思路:
两个pointer之间相隔k-1的长度, 当前哨节点到最后了, 那么后面的自然就是target了
"""
def kth_to_the_last(ll, num):
assert len(ll) >= num
front = target = ll.head
for i in range(num - 1):
front = front.next
while front.next:
front = front.next
... |
fb4b545d13b911e29c21c6f9b6f9e8a85e316451 | jeik0s/DNAChecker | /geneticAlgorithm.py | 2,306 | 3.53125 | 4 | from random import random, choice
from abc import abstractmethod, ABC
import sys
class Element(ABC):
@abstractmethod
def __init__(self):
self.fitness = self.evaluate_function()
def mutation(self):
self.mutation_of_DNA()
self.fitness = self.evaluate_function()
@abstractmet... |
c54b18568c3e1822b377feff31ff5e17fce82b68 | littlerichey/Programming1Portfolio2016-17 | /pigLatinAR.py | 587 | 3.78125 | 4 | #!/usr/bin/env python3
fvowel = False
hitvowel = False
word = input('word: ')
char = 0
while (hitvowel == False):
if (char > 0):
if (word[char] == 'a' or word[char] == 'e' or word[char] == 'i' or word[char] == 'o' or word[char] == 'u' or word[char] == 'y'):
addon = word[:char]
word =... |
52111c5bd5824c5df3bfdba0a4cfbc7988ae9aba | hamin924/python-study | /star 2.py | 162 | 3.78125 | 4 | num=int(input("몇줄?"))
for i in range(0,num):
print(" "*(num-(i+1))+"*"*(2*i+1))
for j in range(num-1,0,-1):
print(" "*((num-1)-(j-1))+"*"*(2*j-1))
|
e86ec5c1672dadf36739b3f0f84f70801002fb79 | christianparker512/HelloWorld | /escapecharacter.py | 682 | 3.8125 | 4 | splitString ="This string has been \nsplit over \n over several\n lines"
print(splitString)
tabbedString ="1\t2\t3\t4\t5"
print(tabbedString)
print ('The pet shop owner "Nogit, no, \'e\'s uh, he\'s resting".')
print("The pet shop owner said \"No,no, 'e's uh, ....he's resting\".')")
print("""the pet shop owner said ... |
4737293ff47de6fc0259e948bb55e6e70c8f8f6e | LAYTONWOOHBILL/ALGO | /Closest_Pair/Closest_Pair.py | 6,910 | 4 | 4 | import math
class Point:
"""Summary of class here.
Create a class Point with xcoord and ycoord
Attributes:
__repr__: A boolean indicating if we like SPAM or not.
__gt__: Compare two point xcoord and ycoord, first on ycoord then xcoord
__lt__: Compare two point xcoord and ycoord, ... |
9c242ea33ef919e930a1851a910e982bb0545440 | LAYTONWOOHBILL/ALGO | /Dynamic Programming/bill_exchange.py | 731 | 3.8125 | 4 | '''
In a previous life, you worked as a cashier in the lost Antarctican colony,
spending the better part of your day giving change to your customers.
Because paper is a very rare and valuable resource in Antarctica,
cashiers were required by law to use the fewest bills possible whenever they gave change.
The currency o... |
009f19ba53a9d84d2ae3db49f56a090edcbf932b | andrewblance/roci | /roci/structure/src/day01.py | 1,423 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
from src.utils import bcolors
class DayOne:
def import_expense_report(self, loc: str) -> List[int]:
data = open(loc).read().split()
expense = [int(x) for x in data]
return expense
def find_two_factors(self, L: List... |
0f8155a645505d9ae0e17b51b12efb804c6f11d5 | soumilk/Python-GUI | /Tkinter basics/11-Canvas.py | 764 | 3.671875 | 4 | from tkinter import *
import random
root=Tk()
canvas=Canvas(root,width=300,height=300)
canvas.pack()
# creating rectangle and providing the inintial and final x and y coordinates
canvas.create_rectangle(10,10,200,60)
canvas.create_line(1,2,44,98)
canvas.create_polygon(304,188,69,22,39,86,55,99,fill="lightgreen")
l=[... |
454bbdee13ee5de0bb6f52902dd25a25c9f5fca3 | shraypungaliya/PyCowsAndBulls | /UI_CowsAndBulls.py | 3,911 | 3.8125 | 4 | from cows_bulls_game import CowsAndBullsGame
import sys
def play():
print("\nWelcome to Cows and Bulls.")
difficulty = _get_difficulty()
total_guesses = 10
print("You have " + str(total_guesses) + " guess(es) to find my " + str(difficulty[1] + 2) + " letter word.")
game = CowsAndBullsGame(total_gu... |
ed4096a95f9f3abcb6eef3744c7df7e5404f3329 | jlmasson/Ayudant-asFundamentos2017-I | /Unidad 5 - Numpy/semi-magic.py | 1,039 | 3.640625 | 4 | # -*- coding: utf-8 -*-
#
#Autor: Madelyne Velasco
#
from numpy import*
from random import randint
# Un cuadrado semi-mágico es una matriz cuadrada conteniendo números tales que la
#suma las dos diagonales principales producen el mismo resultado.
#Escriba un programa que coloque números enteros aleatorios de una ci... |
861003fbc3b2e37975a8a63f97eb6334a22752a6 | jlmasson/Ayudant-asFundamentos2017-I | /Unidad 5 - Numpy/indexing.py | 743 | 3.703125 | 4 | # -*- coding: utf-8 -*-
#
#Autor: Madelyne Velasco
#
"""
Crea un arreglo de la lista [2, 3.2, 5.5, -6.4, -2.2, 2.4] a y asígnalo a la variable a
"""
a = np.array([2, 3.2, 5.5, -6.4, -2.2, 2.4])
"""
¿Qué va a dar a[1]
"""
print a[1]
#3.2
"""
¿Qué va a dar a[1:4]?
"""
print a[1:4]
#[ 3.2 5.5 -6.4]
"""
Crea un arre... |
dc69ec3d5d384af20fcf69eac9c3eed6eed821f4 | ufshk/Python6.00.1x | /Problem Set 2/problemset2.1.py | 482 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 22 21:56:13 2018
@author: Journey
"""
balance = 3329
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
for month in range(12):
monthlyPayment = monthlyPaymentRate * balance
balance = balance - monthlyPayment
balance = balance + (monthl... |
4398675df657c5a010f5af7f2400a99a29086809 | olijng7/PersonalPracticeVS | /Hangman/Hangman.py | 693 | 4.15625 | 4 | print("Welcome to hangman! V")
print('-----------------------')
import getpass
word = getpass.getpass("What's the word? ")
for character in word:
answer = word
print('_ ', end='')
print("")
print("Ok, let's go!")
print('-------')
print('| |')
print('|')
print('|')
print('|')
print('|')
print('-------')
d... |
fd54f25b14689a099e0821d419b98a84d2248ca3 | luocong2013/FirstPython | /cn/com/MapReduceModel.py | 532 | 3.59375 | 4 | from functools import reduce
def f(x):
return x * x
numLst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
r = map(f, numLst)
print(list(r))
print(list(map(str, numLst)))
def add(x, y):
return x + y
print(reduce(add, numLst))
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
de... |
d48509477432b6e1be728dff9565702182057704 | luocong2013/FirstPython | /cn/com/FilterModel.py | 692 | 3.953125 | 4 | # filter
def is_odd(n):
return n % 2 == 1
numLst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(is_odd, numLst)))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])))
# 求素数 START
def _odd_iter():
n = 1
while True:
n += 2
yield n... |
becf29d4ff0d7fdbbedc0ad4cb56b4846d211583 | abhishekshakya/Linear-regression-Implementation | /pred.py | 1,833 | 3.625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')
def hypothesis(X,theta):
y_ = np.dot(X,theta)
return y_
def gradient(X,Y,theta):
n = X.shape[1]
m = X.shape[0]
y_ = hypothesis(X,theta)
# print(y_)
grad = np.ones((X.shape[1],1))
for j i... |
653f55c62a2697f902f96032753c36eed41c556a | jacben13/adventofcode2020 | /day12/part1.py | 1,076 | 3.703125 | 4 | from aoc_modules import aoc_library
import re
def calc_manhattan_dist(northing, easting):
return abs(northing) + abs(easting)
def map_hdg_to_direction(hdg):
if hdg == 0:
return 'N'
elif hdg == 90:
return 'E'
elif hdg == 180:
return 'S'
elif hdg == 270:
return 'W'
... |
361f1449b3d79b757d5ebfe245c31bedf0fb073b | alyson6918/tabuada_e_calculadora | /CLass_calculator.py | 348 | 3.515625 | 4 | #criando classes
class Calculadora:
def __init__(self, valor1, valor2):
self.a = valor1
self.b = valor2
def soma (self):
return self.a + self.b
def subtracao (self):
return self.a - self.b
def divisao (self):
return self.a / self.b
def multiplicacao (self):
... |
218a3558226e194444ac8ced336d57da070c50eb | CARPINCH0/AoC-2020 | /day_03/Code.py | 2,203 | 3.984375 | 4 | '''
move from one line to the next 3 units to the right and one unit down,
how many trees do I hit before getting to the bottom of the Queue
the tree patterns repeat themselves.
this can be solved as a mathematical problem, where different values are true for each line, and they repeat themselves
every 31 characters ... |
ea432dac08ffdb693b68bacdf63fd700a0a1a7bc | graystent/python | /python_fundamentals/session1.py | 709 | 3.921875 | 4 | # section a
print("hello, world")
print("1,2,3,4,5")
print("hello\nworld")
print("my list of names\n\talice\n\tbob\n\tcharlie")
# section b
answer = (1+2)
print(answer)
print(len("hello, world"))
# section c
# question 1
width = int(input("what is the width of the rectangle? "))
height = int(input("what is the height... |
7b57b0422a4dd2d4b59932e4afeb6b384610cca6 | NPRA/image-anonymisation | /tests/helpers.py | 868 | 3.859375 | 4 | import os
def check_file_exists(path, filename=None, ext=None, invert=False):
"""
Assert that the given file exists.
:param path: Path to directory containing the file.
:type path: str
:param filename: Name of file (with extension)
:type filename: str
:param ext: Optional extension to use... |
73dca9b45ccd8e0ef89a8aa93177344ee33600c6 | dubirajara/learning_python | /decorador.py | 723 | 3.640625 | 4 | #Example Basic
def decorador(func):
def wraper():
print('iniciando funcion')
func()
print('terminando funcion')
return wraper
@decorador
def other_function():
print('funcion del medio')
other_function()
#example 2
import time
# Crea el decorator
def calc_ex(func):
def wrap... |
bb699c692c649f5a3a6a2a5df0a2ff6b598eb0f2 | dubirajara/learning_python | /add_length.py | 274 | 4.125 | 4 | '''
write a function that takes a String and returns an
list with the length of each word added to each element.
'''
def add_length(words):
return [f'{i} {str(len(i))}' for i in words.split()]
assert add_length('carrot cake') == ['carrot 6', 'cake 4'] # testcase
|
3fd8e7d92e4cee14ff36f80a32da3a6cb10d41b8 | patrick-replogle/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 1,177 | 3.828125 | 4 | def intersection(arrays):
arr_of_dicts = []
result = []
for arr in arrays:
# create a hashTable for each array to log each elem in the curr array
numsMap = {}
for num in arr:
numsMap[num] = True
# append each hashTable to the array of dictionaries
arr_of... |
26f6891620e951adfed4484ef4c8a200a9deea89 | AbsurdMantis/Stuff | /vetor.py | 322 | 3.9375 | 4 |
lin = 0
col = 0
matriz = []
while lin < 5:
linha = []
col = 0
while col < 2:
num = int(input(f"Número: "))
linha.append(num)
col+=1
matriz.append(linha)
lin+=1
print(matriz)
for linha in matriz:
for coluna in linha:
print(coluna, end=' ')
print(" ")
... |
6483828a17630a3eebe89b764c439b3f569ac6f1 | despitegfx/glblcd_python | /PYTHON ADVANCE/EXERCISE/NOT_EVEN FUNCTION.py | 224 | 3.796875 | 4 |
numbers = [1,56,234,87,4,76,24,69,90,135]
#normal function
def is_even(x):
return not x%2 == 0
f = list(filter(is_even,numbers))
print (f)
#lambda function
g = list(filter(lambda a: not a%2==0,numbers))
print (g)
|
6782a930258196cd582ed3176bccfdd93b3161d1 | despitegfx/glblcd_python | /PYTHON ADVANCE/EXERCISE/FOLD.py | 1,514 | 4.09375 | 4 | #print length of each words in the sentence
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
print ("Lenght of each word in the sentence: ",[len(word) for word in words])
#print positive numbers from the list
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
p = list (filter (la... |
af4f7d5f3aa973f30d1aa2bbc3d02f5c09e8c506 | karanadapala/leetcode | /defangIPaddr.py | 411 | 3.515625 | 4 | class Solution:
def defangIPaddr(self, address: str) -> str:
tmp = ""
count = 0
lastI = 0
for i in range(len(address)):
if address[i] == '.':
if count == 2:
return tmp +'{}[.]{}'.format(address[lastI:i],address[i+1:])
tm... |
84e64a4869422cc8e8e908f6a24d43e4c545b8a2 | Preymark9/Python_Challenge | /PyBank/main.py | 1,051 | 3.953125 | 4 | import os
import csv
csvpath = r"C:\Users\major\OneDrive\Documents\WASHSTL201806DATA4-Class-Repository-DATA\Week 3 - Python\Homework\PyBank\Resources\budget_data.csv"
with open(csvpath, "r") as csvfile:
#find the highest value on the revenue column
#also find the lowest value on the revenue column
#what wa... |
4ddbac016153aef0d6bde7f8e1d2ff6ff1a50719 | Cecilesg/DonkeyKong_Labyrinth | /dklabyrinth.py | 3,334 | 3.859375 | 4 | #! /usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Donkey Kong Lavbyrinth Game
This is a game in which we must move DK until he finds his way through the labyrinth to the bananas.
Script Python3
Files: dklabyrinth.py, classes.py, constants.py, level1, level2 + images
"""
# TODO: import libraries
import pygame
from p... |
99760282e1c167f5597067ec8118f9bd20494892 | WayneChen1994/Python1805 | /day17/组合.py | 484 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
'''
组合:从n个不同元素中,取m个元素进行组合
我们就称n个元素中m个元素的组合
[1, 2, 3, 4] 取3个
'''
import itertools
'''
itertools.combinations(iter, num)
参数一:序列/可迭代对象
参数二:取值的个数
功能:返回从序列中取num个对象的组合,以迭代器的方式返回
'''
list1 = [1, 2, 3, 4]
res = itertools.combinations(list1, 3)
print(list(res))
|
ae7aaa2f67a866940bfd7145a2379712c10db334 | WayneChen1994/Python1805 | /day11/mysum.py | 476 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
# 求和:1+2+……+n
def getSum(n):
return sum([x for x in range(1, n+1)])
# 求1到n之间的偶数之和
def getSumEven(n):
return sum([x for x in range(1, n+1)[1::2]])
# 求1到n之间的奇数之和
def getSumOdd(n):
return sum([x for x in range(1, n+1)[::2]])
# 求1到n之间的任意倍数之和
d... |
2680ecba6fb8682cdeb0d6871c0bba8c11da6300 | WayneChen1994/Python1805 | /day06/函数.py | 1,457 | 3.890625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# author: Wayne.Chen
'''
函数的定义:
在项目开发的过程中,有些功能,我们会反复的使用,为了方便使用,我们将这些功能封装成一个函数,在需要使用此功能的时候,调用即可。
优点:
1、简化代码结构,增加代码的复用性
2、增加代码的可维护性,若想修改某个bug或者某个功能,找到对应的函数更改即可
'''
'''
语法:
def 函数名(参数列表):
语句块
return 表达式
def:关键字来声明函数
函数名:标识符
参数列表:参数与参数之间使用逗号隔开
: 标识函数语句块的开始
语句块:函... |
8720720da05d744f28b3312e3eb77145ec42c7e9 | WayneChen1994/Python1805 | /day04/5、列表的拷贝.py | 982 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Wayne.Chen
print()
'''
赋值拷贝:=
引用拷贝,类似于Windows快捷方式
'''
list1 = [1, 3, 4, 5]
# list2 = list1
# print(list1)
# print(list2)
# list2[-1] = "hello"
# print(list1)
# print(list2)
'''
list1.copy()
拷贝是一个内存拷贝,并非是一个完全内存拷贝
'''
# list2 =... |
72fd26de55a4748d45652a31191f09bece86ef5a | WayneChen1994/Python1805 | /day02/zuoye.py | 1,090 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Wayne.Chen
# year = int(input("请输入一个年份:"))
# if year%100 != 0 and year%4 == 0 or year%400 ==0:
# print("%d为闰年"%year)
# else:
# print("%d不是闰年"%year)
# num = int(input("请输入一个三位数:"))
# bai = num // 100
# ge = num % 10
# shi = num // 10 % 10
... |
6832c8e55f48c855d87c93751cff964942106cbe | WayneChen1994/Python1805 | /day02/随机数random.py | 1,086 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Wayne.Chen
# 导入模块
import random
# random.choice(序列)
# 功能:从指定的序列中随机的挑选一个元素
print(random.choice([1, 2, "hello", 56, True, False]))
'''
random.randrange(100) 从0到99之间随机挑选一个整数
random.randrange([start,]stop[,step])
参数一:指定从哪开始【包含】,默认为0
参数二:指定到哪里结束... |
594128be7a4175ebc70ad4376a3cdbfa0dd5c8a1 | WayneChen1994/Python1805 | /day07/匿名函数.py | 767 | 4.0625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# author: Wayne.Chen
'''
匿名函数
概念:是指一类不需要定义函数名的函数
特点:
1、不需要使用def定义,使用lambda定义
2、不需要定义函数名
3、函数体只有一个表达式
4、不需要return,表达式的结果就是返回值
语法:
lambda 参数1,参数2,……,参数n:表达式
若无参数可不写,但冒号不能省略
优点:函数没有名字,不用担心函数名冲突
匿名函数的调用:
1、将匿名函数赋值给一个变量
2、通过变量来进行函数的调用【与之前的函数调用相同】
'''
# func = lambda a,b... |
4cd864a2a03398f0e67089dddadd70f510c0b47b | WayneChen1994/Python1805 | /day12/黑魔法.py | 276 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
class Student:
def __init__(self, name, age):
self.name = name
self.__age = age
if __name__ == "__main__":
stu = Student("lili", 18)
# print(stu.__age)
print(stu._Student__age)
|
580d495c9f7cf284d7a1bea54e695168e2d29167 | WayneChen1994/Python1805 | /day02/作业.py | 1,182 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Wayne.Chen
'''
闰年:
year = int(input("请输入一个年份:"))
if (year % 100 != 0 and year % 4 == 0) or (year % 100 == 0 and year % 400 == 0):
print(str(year) + "年是闰年")
else:
print(str(year) + "年不是闰年")
'''
'''
水仙花数:
num = int(input("请输入一个三位数:"))
a =... |
0b922049ccb8e7f1b03d8ccad86ddce0caefe02a | WayneChen1994/Python1805 | /day07/装饰器.py | 1,393 | 3.6875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# author: Wayne.Chen
'''
什么是装饰器?
在代码运行期间,动态增加功能的方式,我们称之为装饰器
'''
'''
在打印时间之前,给我打印一个分隔符*******当前时间********
要求:不能改变原函数
'''
# print("当前时间".center(50, "*"))
# func()
# def func2():
# print("当前时间".center(50, "-"))
# func()
# func2()
'''
登陆功能
'''
'''
最简单的装饰器... |
a6d343559e47cf50670c1fc004941eb98714155a | WayneChen1994/Python1805 | /day14/读写文件.py | 1,777 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
'''
在Python中使用的文件读写,是由Python给我们提供的一个内置函数。
一般情况下,系统不允许我们直接操作磁盘,所以对于磁盘操作,是由操作系统留下的接口,我们来进行调用。
因此我们的文件读写其实就是请求操作系统打开一个文件对象,然后通过操作系统的接口来读取或者写入文件。
'''
'''
open(path, encoding='utf-8', errors='ignore')
参数一:文件路径
参数二:指定文件的编码格式
参数三:若出现编码问题的错误则忽略不计
功能:请求打开一个文件对象
f.... |
5f51e9b0c67b0ddd52351616f6bed787c8a97261 | WayneChen1994/Python1805 | /day17/正则表达式.py | 1,289 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
'''
需求1:判断QQ号是否合法:
1、必须全部为数字
2、不能以0开头
3、长度5~12
写成函数
'''
def isqq(s):
if s.isdigit() and 5 <= len(s) <= 12 and not s.startswith("0"):
return True
else:
return False
# if __name__ == "__main__":
# astr = "1231434"
# astr2 = ... |
4a733fe5fda9768008cdeec707c1e1a16cc5e127 | mlsamsom/PyFrictionTools | /frictionstats.py | 2,815 | 3.8125 | 4 | """
Compute confidence interval for a quantile.
Suppose I'm interested in estimating the 37th percentile. The
empirical CDF gives me one estimate for that. I'd like
to get a confidence interval: I'm 90% confident that the 37th percentile
lies between X and Y.
You can compute that with two calls to the following fun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.