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
b3fc68dceb1f57d89daa42ec09c214fe0807897c
mbarbour0/Practice
/Another Rock Paper Scissors Game.py
1,481
4.15625
4
# Yet another game of Rock Paper Scissors import os import random from time import sleep options = {"R": "Rock", "P": "Paper", "S": "Scissors"} def clear_screen(): """Clear screen between games""" if os.name == 'nt': os.system('cls') else: os.system('clear') def play_game(): """General...
dcb6d89fedc9ab9c2cd884a73904cf27633ba719
shraysidubey/pythonScripts
/Stack_using_LinkedList.py
1,634
4.21875
4
#Stack using the LinkedList. class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def appendHaed(self,new_data): new_node = Node(new_data) #create the new node 370__--> head ...
0e9a81319f95bd3d71e8154d7c8e1bfdce7da84c
EduardoScalise/PythonLab
/PyFuncao.py
934
3.890625
4
# Definindo uma função def primeiraFunc(): print('Hello World!') primeiraFunc() # Definindo uma função com parâmetro def primFunc(nome): print('Welcome %s' %(nome)) # Chamando a função e passando parãmetro (Neste caso solicitando o nome - entrada primFunc(input('What\'s your name: ')) def funcLeitura():...
7c3a7aae25ec16e4c4d4eeb06dde7daac390996f
hnzhangbinghui/ddt_excel
/ddt_json.py
856
3.59375
4
#coding:utf-8 ''' JSON是清零及的数据交换格式,json特点是:可读性强,有利于机器的解析和生成,一般用于提升网络的传输速率; python处理json这种格式的数据库,需要先导入JSON类库 import json 有两个比较重要的方法:dumps(),将python对象编码成JSON字符串 loads,将JSON字符串编码成python对象 ''' import json py_data={ "CalcCode":"testcode","Remarks":"test","Submitter":"ligl6","Approver":"duanmuqd1" } json_python=json.dumps(py...
ad27b373cd4c373c9bebf394ad7a446d730313b1
nvcoden/working-out-problems
/py_0710_2.py
565
3.5625
4
''' Create a function that takes a string as an argument and returns a coded (h4ck3r 5p34k) version of the string. In order to work properly, the function should replace all "a"s with 4, "e"s with 3, "i"s with 1, "o"s with 0, and "s"s with 5 ''' def hackerSpeak(string): return(string.replace('a', '4').replace('e',...
f0e18b65f8e66a9255a9dc7d110b775f916b6ff4
nvcoden/working-out-problems
/py_2409_1.py
744
4.21875
4
''' Question 1 Create methods for the Calculator class that can do the following: 1. Add two numbers. 2. Subtract two numbers. 3. Multiply two numbers. 4. Divide two numbers. Sample Output :- calculator = Calculator() calculator.add(10, 5) ➞ 15 calculator.subtract(10, 5) ➞ 5 calculator.multiply(10, 5) ➞ 50 calcula...
efd7316f602c25a66d62e092ba452c02d1cbd2d1
aaschlessman/SchoolWorkPython
/Homework5/HW5.py
3,154
3.640625
4
#Aaron Schlessman #CS4630 #Homework5 #Kinematics import sympy import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import display, clear_output t, a, v_t, s_t, v_x, v_y, s_x, s_y = sympy.symbols('t, a, v_t, s_t, v_x, v_y, s_x, s_y') v_i, vx_i, vy...
bd083887a8e122b13822c40f372aad7c8e72dfd4
znaichz/LeagueOfTetrisAI
/script/Clean_New_AI_Template.py
948
3.9375
4
class AI: # give your AI a name for display CONST_NAME = "Your Bot's Name" # method compute is mandatory for playing tetris def compute(self, my_map, op_map, current, next): # my_map is a 10 x 20 2D integer list representing the map for the player # op_map is the 10 x 20 2D integer list...
6dc53ca8c9d0a2735b8eeff3a452e6760f15d37e
Graff1/skillfactory_rds
/module_0/.ipynb_checkpoints/guess_algo-checkpoint.py
807
3.578125
4
# -*- coding: utf-8 -*- import numpy as np import random def score_game(game_core_v1): '''Let's run it 1000 times to deect the productivity of the algorithm''' count_ls = [] np.random.seed(1) #fix RANDOM SEED random_array = np.random.randint(1, 101, size=(1000)) for number in random_array: ...
22c05252e833d439d347654b134b4e5c0db6527c
Rdbaker/AI-HW-1
/solution/terrain.py
2,059
3.921875
4
""" solution file for AI Homework 1 solution Authors: Ryan Baker Matthew Beaulieu Anthony Romeo """ class Terrain(object): """ Class to handle interactions with the terrain. :param: terrain_map - 2d rectangular array of the terrain ex: [ [ 3, 3, 3, 3 ]...
0617325a1895f1c235d735c197f6221b9eba6a68
adelespinasse/cep-developer-assessment
/exercise2/submissions/percentiles.py
2,537
3.515625
4
#!python """ Exercise 2 of the CEP developer assessment. Author: Alan deLespinasse (aldel@aldel.com) """ import csv # Column names of survey questions on which to compute means. NOTE: # The task description said the final column name should be "undrorg", # but all example files use "impsust" instead. I took the ...
d16573cb2c78191a598895329f1889df7258c235
chaoshenglu/learnPythonEasily
/5基本数据类型之Tuple/2.Tuple.py
547
4.125
4
# 如何用元祖来表示全班同学的姓名? students = ('小明', '小红', '小强') # 如何获取元祖中第三个同学的姓名? print(students[2]) # 如何获取元祖中倒数第二个同学的姓名? print(students[-2]) # 如何获取元祖的第1个到第3个元素? print(students[0:3]) # 如何获取元祖的第1个到第-3个元素 print(students[0:-2]) # 将这个元祖重复两遍,形成一个新的元祖 students = students * 2 # 方法一 # students = students + students # 方法二 print(studen...
eed94415f3966db3f3a0f7cd64af3ca53211b703
chaoshenglu/learnPythonEasily
/4基本数据类型之List/4.List.py
423
4.1875
4
cities = ['北京', '上海', '深圳', '广州'] # 访问数组的第1个元素 print("cities[0]: ", cities[0]) # 访问数组的第1个到第3个元素 print("cities[0:3]: ", cities[0:3]) # 访问数组的第1个到第-3个元素 print("cities[0:-2]: ", cities[0:-2]) # 将这个数组重复两遍,形成一个新的数组 cities = cities * 2 print(cities) # 遍历这个数组 for city in cities: print(city)
8ee61eae2465e838480ce3d8604b72b5de064d44
chaoshenglu/learnPythonEasily
/3基本数据类型之String/5.String.py
271
3.5
4
# %s是字符串占位符,%d是整数占位符,%f是浮点数占位符 # .2f代表保留两位小数点 a = '李先生' b = 3 c = 58.8 d = '%s,您%d月份话费是%.2f元' % (a, b, c) e = '{0},您{1}月份话费是{2:.2f}元'.format(a, b, c) print(d) print(e)
84767e3725f4a7a867816be6a7262a459c2e951b
uwwwwwu/Algorithm_programmers
/secretmap.py
738
3.5
4
#n*n지도 # 비트 연산자 # 나눗셈 출력..? def solution(n,arr1,arr2): answer = [] result=[] for i in range(n): answer.append(arr1[i] | arr2[i]) # 최종 지도 # 이진법 표현 for i in range(len(answer)): data = "" while(answer[i] != 0): # 0이면 " " if answer[i]%2==0: data...
7c8517ad37f20254ca4c08fbe710b3bd51beed6b
uwwwwwu/Algorithm_programmers
/puppeteer_kakao.py
1,635
3.625
4
#시간 에러..? temp = [] move=0 for i in range(len(moves)): for j in range(len(board)): move=moves[i]-1 if board[j][move]!=0: temp.append(board[j][move]) #인형 바구니에 넣기 board[j][move]=0 break result=len(temp) #빼지 않은 상태에서 배열의 길이 체크 print(temp) # 같은 인형 제거 시작!!! i=0 while...
cbc71fbc8db4fae470041abeaf8ab44d7d9badff
suma917sh/Clustering
/K-means Clustering (Crime Data).py
1,342
3.625
4
#!/usr/bin/env python # coding: utf-8 # K-Means # In[14]: import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.cluster import KMeans # In[15]: crime= pd.read_csv("C:\\Users\\hp\\Downloads\\crime_data.csv") # In[16]: # Normalization function from sklearn.preprocessing imp...
9959c5f9629578a9b5e7541bc98bae733baa74dd
tanada14/python
/make_carrier30.py
1,316
3.5
4
#搬送要求のファイルを出力する import random import numpy.random as rd kumitate_sum = 2 #組み立て場所の総数 last_time = 200 #搬送物が発生する最終時刻 path_w = 'carrier_test4.txt' #保存するファイル carrier_sum = 30 #搬送物の総数 print('carrier_sum', 100) with open(path_w, mode='w') as f: sum_time = 0 for count in rang...
1b996a011c1f4d8d88c9b14a3f021cb4edb53f55
jwinf843/simple-calculator
/.ipynb_checkpoints/tests-checkpoint.py
795
3.8125
4
from calculator import add, subtract, multiply, divide, square, power, sqrt def test_add(): results = add(1, 2) assert results == 3 def test_subtract(): results = subtract(10, 7) assert results == 3 def test_multiply(): results = multiply(2, 3) assert results == 6 def test_divid...
1f495bb44e79bcb2cbe8ad34766207ac818dbc1c
dungna/python-course
/day6/btvn/bai00.py
133
3.828125
4
my_dict = { 1: 3, 2: 4, 3: 6 } tich = 1 for i in my_dict: tich *= my_dict[i] print("Tich cac phan tu: ", str(tich))
4d1ae0d7628bbe8eab51cd3494ccfd8bebc7efcb
dungna/python-course
/day6/main.py
338
3.796875
4
# my_dict = { # 1: 'Mot', # 2: 'Hai', # 3: 'Ba', # "hello": 2, # } # # print(my_dict) # print(my_dict[1]) # print(my_dict["hello"]) # # # my_dict.pop(3) # # print(my_dict) # my_dict.popitem() # print(my_dict) # print(my_dict.keys()) # print(sorted(my_dict)) dic = {} for i in range(10): dic[i] = (i ...
5960b138eeb05675d99f4dad908956445d650934
TatsukiSerizawa/NLP100Exercise
/08.py
352
3.625
4
# coding: utf-8 def cipher(sentence): new = [] for s in sentence: if 97 <= ord(s) <= 122: # 英小文字なら s = chr(219 - ord(s)) # (219-文字コード)に変換 new.append(s) return ''.join(new) test = 'I am an NLPer' new = cipher(test) # 暗号化 print(new) old = cipher(new) # 復号化 print(old)
6e3e64b37d1ab414599b42b9a6e7571fbb7f6084
edwardgorelik/practice
/Lesson14_SetBuilder.py
544
3.875
4
def buildSet(): basic = [] while True: try: loops = int(input("How many items are you putting into the list?")) except ValueError: print("Input must be a number") continue else: break for x in range(0, loops): growth = input("Wh...
b586aec2fc4a5dd88ac45825286342442077a9dd
gelila7/object-oriented-code_python
/oop.py
3,826
3.796875
4
class Assignment: def __init__(self, name: str, difficulty: float): self.name = name self.difficulty = difficulty def get_name(self): return self.name def get_difficulty(self): return self.difficulty def __str__(self): return sel...
62a4df544ba1447c343bd70d9d582260dc63c387
alexmal2804/rep1
/ex_3.py
1,755
3.8125
4
""" Простейшая система проверки орфографии может быть основана на использовании списка известных слов. Если введённое слово не найдено в этом списке, оно помечается как "ошибка". Попробуем написать подобную систему. На вход программе первой строкой передаётся количество d известных нам слов, после чего на d строках ука...
84d6f39ad1e78d7eea85da28e4bd27b8de899bd5
ksarvakar/Machine-Learning-Hindi-Playlist
/5.one hot encoding/dummy variable and one hot encoding.py
1,131
3.84375
4
#!/usr/bin/env python # coding: utf-8 # # One Hot Encoding # In[1]: import pandas as pd # In[2]: df = pd.read_csv("gujhome.csv") df # Create dummy variabl- pandas # In[3]: dummies = pd.get_dummies(df.city) dummies # In[4]: df_dummies= pd.concat([df,dummies],axis='columns') df_dummies # In[5]: df_...
73c0c5ecf65975a33de98d7f8bc62ca62ffa20da
ksarvakar/Machine-Learning-Hindi-Playlist
/7.Logostic Regression/logistic regression.py
1,124
3.6875
4
#!/usr/bin/env python # coding: utf-8 # We are Predicting if a person will buy LIC insurnace based on his age using logistic regression.(Two outcomes:YES/NO) # In[1]: import pandas as pd from matplotlib import pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: df = pd.read_csv("ins_data...
6f6a9f46ab6579674fae13714308ce6765837e7c
AbhaHimani/Spirograph
/spirography.py
562
3.625
4
import turtle as t from turtle import Screen import random t.colormode(255) tim = t.Turtle() def random_color(): r= random.randint(0,255) g=random.randint(0,255) b=random.randint(0,255) random_color = (r, g, b) return random_color tim.speed("fastest") def make_circle(): for _ ...
918828289c08c6683b3926c28d4cec2e573b9810
cdw/MothNavWorkspace
/scripts/minimizeArea.py
10,110
4
4
#!/usr/bin/python2.7 """ This script implements a toy problem that we will use to roughly understand how deap works. The problem involves covering a set of points with some set of squares of minimal area. The squares are defined by a point (x,y) describing the bottom-left corner and a length. The individual squares ca...
8e0d3da60bb8dbecf0d106a688405b61de31f9ed
yujun858/mypython
/day27_1119_python/example01.py
1,170
3.828125
4
# name = input('name:') # print(name) # s1 = input('input') # abc # s2 = input('input') #abc # print(name) # print(s1 == s2) #True # print(s1 is s2) #False # print(id(s1)) # print(id(s2)) # in 运算符号 # name = 'steven' # result = 't' in name # print(result) # True # 倒序,切片 str = 'hello python' # print(str[-1::-1]) # print...
652b053c4d98fa82b8ff28e161d898cd1e5bce60
yujun858/mypython
/day28_1120_python/example01.py
277
3.890625
4
# s1 = input('请输入第一个字符串:') # s2 = input('请输入第二个字符串') # s3='' # for i in s1: # if i not in s2: # s3 = s3+i # print(s3) # 列表添加 append extends insert # iterable: 可迭代 # 列表函数: hotpot_list = ['海底捞','','']
7899176361c186c5f953f4bab5b9f048e49e222c
yujun858/mypython
/day32_1124_python/b.py
352
3.75
4
class A(): name ='bbb' age = 18 def __init__(self): self.name = 'aaa' self.age = 200 def say(self): print(self.name) print(self.age) class B(): name ='ccc' age =19 a = A() a.say() print('------------') A.say(a) print('---------------') A.say(A) print('------------...
ff659057aa4b939990bb320b3e2223d0e368ef20
yujun858/mypython
/day29_1121_python/example02.py
1,246
4.34375
4
# 享元模式; # 咖啡出售系统 class Coffee(): name ='' price=0 def __init__(self,name): self.name = name self.price = len(name)#假设咖啡价格咖啡名字 def show(self): print('Coffee Name: %s Coffee Price %f'%(self.name,self.price)) class Customer(): name ='' coffeeFactory = '' def __init__(se...
d4d3a941b41d771d601f271c5ddefbbf7ac19086
valdepeace/ejercicios_python
/actividad 1a/ejericio1.py
1,450
3.75
4
import random import ast print('####################') print('# Actividad 1 #') print('####################') ###### Definicion de funciones para el ejercicio def dameNumero(): try: con = int(raw_input('Dame numero de 4 cifras:')) return con except ValueError: re...
f9c82f5a57876e2771e545fffa88e8b0ad23ac7f
prashi23/Python-Scripts
/encrypter/penc.py
5,640
4.09375
4
import time def intro(): print("Welcome to my own password Encrypter/Decrypter! Which action would you like to take?") print("+=====================================+") print("1: Encrypt a password") print("2: Decrypt a previously encrypted password") print("+=====================================+") choice...
ca7a2516586ac44e4c5e57a8aa3190ea62adfe1c
Jay-Liao/codility
/exercises/find_the_longest_time_slot.py
3,160
3.8125
4
import datetime def time_slice_to_datetime_duration(base_datetime, time_slice): # Mon 01:00-23:00 -> (datetime.datetime(2018, 7, 7, 1, 0), datetime.datetime(2018, 7, 7, 23, 0)) weekday_to_int_map = { "Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, ...
7faddbab36ea78c20620bcdb63f8447f3089f45a
Oindry/Advanced-Python
/Linked List/Recreate.py
668
3.890625
4
class node: def __init__ (self, data, node = None): self.data=data self.node=node def set_data(self,data): self.data=data def get_data(self): return self.data def set_node(self,node): self.node=node def get_node(self): return self.node class linked_list: def __init__(self,head=None): self.head= he...
10966b5ab1628c792b25fd90d430f48a5f599104
traciarms/random-art
/random_art.py
1,941
3.734375
4
from math import sin, pi, cos import random # Your job is to create better version of create_expression and # run_expression to create random art. # Your expression should have a __str__() function defined for it. def create_expression(): """This function takes no arguments and returns an expression that gen...
e2164210c928ad2d6db88c61eab833d8ab5a199a
rajjoan/PythonSamples
/Chapter 5/ADcalculator.py
729
4.34375
4
# Get user input num1 = input("Enter a number : ") num2 = input("Enter another number : ") symbol = input("Enter a symbol (* + - /) : ") # Subtraction if symbol == "-": if num2 >= num1: print(int(num2)-int(num1)) else: print(int(num1)-int(num2)) # Division if symbol == "/": if nu...
4db6fd1a4494278ad2900ba8b53ba19792fd18a0
rajjoan/PythonSamples
/TurtleRace.py
1,143
4
4
#Joannas favorite import turtle import random turtle.bgcolor("Black") p1=turtle.Turtle() p1.color("Cyan") p1.shape("turtle") p1.penup() p1.goto(-200,100) p2=p1.clone() p2.color("HotPink") p2.penup() p2.goto(-200,-100) p1.goto(300,60) p1.pendown() p1.circle(40) p1.penup() p1.goto(-200,100) p2.goto(300,-140) p2.pendo...
e853965a25662783b57054c0bf75a09a9ebe3615
rajjoan/PythonSamples
/Chapter 13/function7.py
215
4.25
4
def evenorodd(number): if number % 2 == 0: print("The number is even") else: print("this number is odd") n=int(input("Enter a number to finf even or odd : ")) evenorodd(n)
2ca2fbd729551db2db2c559b45e255bbfc60e673
rajjoan/PythonSamples
/for_2.py
123
3.65625
4
Harrypotter=["Slytherin","Griffindor","Ravenclaw","Hufflepuff"] #for var in list name: for i in Harrypotter: print(i)
e18bc1bd760a60ff7d252d524298a49a801a41a6
Baron-MC/traiteur_adresse_ip
/saisie.py
1,986
3.65625
4
def verification_masque( masque ): """ Verifie la validité du masque si ou renvoie de True sinon False """ masque_valide = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20','21', '22', '23', '24', '25', '26', '27', '28', '29', '30'] i...
94e8bd8c6c398ac43b896752fe2e2624499b91af
samuellly/dojo_assignment_file
/dojo_python/fundamentals/star.py
1,031
3.734375
4
x = [4, 6, 1, 3, 5, 7, 25] def print_Stars(arr): for i in arr: print i * "*" print_Stars(x) #2nd Star assignment x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] def print_Stars(arr): for i in range(len(arr)): if isinstance(arr[i], int): print arr[i] * "*" elif isinstance(arr[i], str): ...
1047e8c207b817e18cb593493597da1621f46247
samuellly/dojo_assignment_file
/dojo_python/oop/car/car.py
780
3.8125
4
import random class car(object): def __init__(self,price,speed, fuel, mileage): self.price = price self.speed= speed self.fuel= fuel self.miles= mileage if price>10000: self.tax =0.15 else: self.tax = 0.12 self.display_all() def display_all(self): ...
72d6890a9461b2d628bf2b80e62bd562c23467c1
b-Istiak-s/drawLove
/love.py
2,100
3.90625
4
import turtle screen = turtle.getscreen() pen = turtle.Turtle() # I def draw_i(): pen.forward(50) pen.backward(25) pen.right(90) pen.forward(140) pen.left(90) pen.forward(25) pen.backward(50) # define functions to draw things def love(fill='pink'): # draw love pen.fillcolor(fill) pen.begin_fill() pen.lef...
27e7203b162cd14bee4cd042ce1bdb32cde8d935
digital13468/ALGORITHMS
/Toolbox/Divide and Conquer/Majority Element/majority_element.py
1,300
3.578125
4
# Uses python3 import sys, math def get_majority_element(a, left, right): print(a) if left == right: print(-1) return -1 if left + 1 == right: print(a[left]) return a[left] k = math.floor((right + left) / 2) #print(k) left_sub_elem = get_majority_element(a, left,...
a8c021e6646fd489a2e762ac2dcdb7e2ff05299c
digital13468/ALGORITHMS
/Toolbox/Greedy Algorithms/different_summands/different_summands.py
610
3.75
4
# Uses python3 import sys def optimal_summands(n): summands = [] #start_number = 1 if n > 2: summands.append(1) sub_optimal_summands(n - 1, 2, summands) else: summands.append(n) return summands def sub_optimal_summands(n, start, array): if n > 2 * start: array.a...
ffe9b67ca8b34a7b0f0e2d9d263f4021a3719fcd
yuzisun/ooplbb
/examples/Range.py
1,097
3.59375
4
#!/usr/bin/env python3 # -------- # Range.py # -------- import sys import time class range_iterator () : def __init__ (self, b, e) : self.b = b self.e = e def __iter__ (self) : return self def __next__ (self) : if self.b == self.e : raise StopIteration() ...
0599a2b5b7d5f76058ed9671e9d2ebce56b58b83
yuzisun/ooplbb
/exercises/Employee.py
1,263
3.625
4
#!/usr/bin/env python3 # ----------- # Employee.py # ----------- """ ---------------------------------------------------------------------- Replace Type Code with State/Strategy (227) Replace Conditional with Polymorphism (225) """ from unittest import main, TestCase class Employee : ENGINEER = 0 SALESMAN =...
ee0ac84928794bc329bca5b6c27721f0846c9188
mantidproject/3rdpartylibs-mac
/Python/epics/alarm.py
5,968
3.640625
4
#!/usr/bin/env python # M Newville <newville@cars.uchicago.edu> # The University of Chicago, 2010 # Epics Open License """ alarm module -- Alarm class """ import sys import time import operator from . import pv from .utils import is_string class Alarm(object): """ alarm class for a PV: run a user-supplied ...
170505683210c2db4e57dbbec590e7fadb0ea737
securityn00b/net-sec-course
/Assignment1/ChatClient.py
2,307
3.96875
4
import socket # The socket module is the most important module used in this program. import sys from sys import argv script, server_ip_option, server_ip, server_port_option, server_port = argv # Arguments provided with the script def Main...
e5d40bf9e3adcfec83bb080d19c57f943d3711de
yingcliu/python
/3.py
79
3.828125
4
print("please enter a number:") a = input() a = int(a) print('result is:', a+a)
99e7295134f7f60294d91d2e0b3fc92cd01952d9
Dayeeta12/The_Intern_Academy_Internship
/Task2_Weather_Reporter/weather_report_byIP.py
5,156
3.578125
4
from PIL import Image, ImageTk import io import requests from tkinter import Tk, Label, Button, LabelFrame, Entry from urllib.request import urlopen # GUI Frame mainWindow = Tk() mainWindow.title("Weather App") mainWindow.geometry("1200x720") mainWindow.configure(bg="white") url = "https://weatherapi-co...
bb4ff2806ddabcd85f5537afcaf8993f8a2429f7
kuxingseng/learnPython
/TestDateTime.py
918
3.78125
4
from datetime import datetime now = datetime.now() print("now:", now) # 创建datetime类 dt = datetime(2022, 6, 13, 12, 00) print(dt) # 时间戳转换成时间 ts = 1521167218 print(datetime.fromtimestamp(ts)) print(datetime.utcnow()) # 格式化日期 day = datetime.strptime('2011-6-13 12:22:2', '%Y-%m-%d %H:%M:%S') print(day) print(now.s...
7fcf47e618ff34c9011d3cbd6ffca9bbaebff4b7
kuxingseng/learnPython
/TestItertools.py
544
4.1875
4
# 操作迭代器对象 # count # 死循环 # import itertools # natuals = itertools.count(1) # for n in natuals: # print(n) import itertools ns = itertools.repeat('abc', 2) for n in ns: print(n) # chain 串联迭代器 for c in itertools.chain('abc', 'def'): print(c) # groupby 把迭代器中相邻的重复元素挑出来放在一起 for key, group in itertools.g...
800f7de0c78d90cce9c420952710e6e1993db628
karthikeyan95/LeetCodeExamples
/general_problems/python/Longestsubstring.py
836
3.59375
4
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: result = "" result_length=0 for element in s: print("result string: " + result) print("iter string: " + element) index = result.find(element) if index == 0: resu...
9a7a35ac19f2dd419c4ed727193292da37693acd
karthikeyan95/LeetCodeExamples
/general_problems/python/checkifstraightline.py
729
3.578125
4
from typing import List class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if len(coordinates) == 2: return True x1 = coordinates[0][0] y1 = coordinates[0][1] x2 = coordinates[1][0] y2 = coordinates[1][1] for i in range(2,...
6c68c53a7b6c0dab56a6c22a647a9e832e213702
vikilink-io/goit-python
/lesson1/hw2.py
259
3.625
4
a = input ('Please enter a') b = input ('Please enter b') c = input ('Please enter c') a = int(a) b = int(b) c = int(c) D = b**2 - 4*a*c x1 = (-b + D*0.5) / (2*a) x2 = (-b - D*0.5) / (2*a) x1text = f"x1={x1}" x2text = f"x2={x2}" print (x1text) print (x2text)
26ab908f472ca24cf7334e9e1cfe5b017f92ad84
Hankych/BridgeHacks
/BridgeHacks/userinfo.py
1,252
3.859375
4
def login(): user = input("Input a username") password = input("Input a password") for account in open("accounts.txt", "r").readlines(): login = account.split if user == login[0] and password ==login[1]: print("You are now logged in.") return True else: ...
207c4e87a530256f38d15c89564a758c73f5d439
naorton/Advent-of-Code
/2016/Day 1/puzzle.py
3,430
3.609375
4
import sys def parse(file): directions = [] data = open(file).readlines() data = data[0].split() for entry in data: entry = entry.strip() entry = entry.strip(",") directions.append(entry) return directions def directionChanger(facing_direction, move_direction): if facing_direction == "North...
92f16d41714172748ad9596b46220c4faf68b658
naorton/Advent-of-Code
/2016/Day 6/day6.py
317
3.609375
4
import collections data =[entry.strip("\n") for entry in open("data.txt").readlines()] #print(data) entries = collections.defaultdict(list) for entry in data: i = 0 while i < len(entry): entries[i].append(entry[i]) i += 1 for key in entries: print(max(collections.Counter(entries[key])))
a9c28124180c59aa480e72bf84a5948028af6615
nihathalici/Google-IT-Automation-with-Python
/Automating-Real-World-Tasks-with-Python/Week-2/python_scripts.py
7,788
3.953125
4
######################### # Data Serialization # ######################### """ Instead of having a list of lists, we could turn this information into a list of dictionaries. In each of these dictionaries, the key will be the name of the column, and the value will be the corresponding information in each row. It ...
e11946a0b0b0d3648f9a08332edecec21ec2509d
jrabbe/vector-renderer
/renderer/color4.py
1,080
3.59375
4
#!/usr/bin/env python # encoding: utf-8 from __future__ import division class Color(object): def __init__(self, r, g, b, a=1.0): """ Initialize a color instance from its component. Each component is given in the range of 0.0 to 1.0. Keyword arguments: r -- the red compone...
5bcf95b1954ac33b4698863f3900d466a6805539
angelblue05/Exercises
/codeacademy/python/while.py
1,298
4.21875
4
num = 1 while num < 11: # Fill in the condition # Print num squared print num * num # Increment num (make sure to do this!) num += 1 # another example choice = raw_input('Enjoying the course? (y/n)') while choice != "y" and choice != "n": # Fill in the condition (before the colon) choice = ...
c0ad3bd28f887a19ea13b96fb02ca0f5fed36242
angelblue05/Exercises
/codeacademy/python/median.py
181
3.625
4
def median(lst): lst = sorted(lst) middle = len(lst) / 2 if len(lst) % 2 == 0: return (lst[middle] + lst[middle - 1]) / 2.0 else: return lst[middle]
8d55b63bb1f9d30799b942738faa6d989fccef36
jjtust/algorithm
/sort/LRUCache.py
1,060
3.84375
4
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.dict = OrderedDict() self.remain = capacity def get(self, key): if key not in self.dict: return -1 value = self.dict.pop(key) self.dict[key] = value return value ...
57dc7e4ef5e21ce1a686e74e3226b35f486123e8
haris-p/python
/latihan/latihan2.py
1,266
3.625
4
# hewan = ['kuda','gajah','kucing'] # buah = ['leci','apel','jeruk'] # data = [hewan,buah] # for subdaftar in data: # print(subdaftar) # for perdata in subdaftar: # print(perdata) # for i in range(1,15): # print(i) # if i is 10: # print("angka ditemukan") # continue # else: # ...
d3013b8d3c7724d6f18869e91a76ec56ab1fea16
iAnafem/Python_programming
/3.2.2.py
398
3.75
4
def get_dict(_string): return set(_string.lower().split()) def update_dictionary(_dict, _string): for word in get_dict(_string.lower()): _dict[word] = _string.lower().split().count(word) return _dict def main(): _dict = {} for item in sorted(update_dictionary(_dict, input())): pr...
31190e9a90801bf07ad135198dea4a7edbdb28e2
raja17021998/Exciting-Machine-Learning-Journey-on-Python-and-R
/Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/svr_wd.py
2,587
3.734375
4
#SVR # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values # Splitting the dataset into the Training set and Test set """from sk...
4b8217c2958f53bf01d842b75881fd79340bb245
cnguyen2049/Side_Programs
/Programs/stack.py
278
3.78125
4
class Stack : def __init__(self): self.objs =[] def push(self,obj): self.objs.append(obj) def pop(self): return (self.objs.pop()) def isEmpty(self): return self.objs == [] std = Stack() std.push("AIDS") std.push("Herp") while not std.isEmpty(): print std.pop(),
d499e166908e2f720a491e0da021c5ddeda95491
Gaoliu19910601/python3
/tutorial2_revamp/tut18_OOP_FULL.py
4,786
3.828125
4
class Employee(object): raise_amount = 1.04 # Class variable num_of_employees = 0 # Class variable def __init__(self, firstname, lastname, salary): self.firstname = firstname self.lastname = lastname self.salary = salary # self.email = '{}.{}@company.com'.format(self...
98c0a56d846d180558421ee8ad664466349e85fd
Gaoliu19910601/python3
/tutorial2_revamp/tut4_boolean_cond.py
1,418
4.1875
4
print('') print('-----------------BOOLEAN AND CONDITION-----------------------') print('') language = 'Java' # If the language is python then it is a true condition and would print # the first condition and so forth for the next. However if everything # is False there would be no match if language is 'Python': p...
e4771801e9edfa915000c7522e092b4447189169
Gaoliu19910601/python3
/tutorial2_revamp/tut5_loops.py
525
4.15625
4
nums = [1, 2, 3, 4, 5] # The for loop with an if condition along with a continue statement for num in nums: if num == 3: print('Found it!') continue print(num) print('') # Nested For loop for letter in 'abc': for num in nums: print(num,letter) print('') for i in range(1, 11): ...
3c1f414a6d56a4da51ec45f2484d79f3b4bc3b04
jkbockstael/projecteuler
/euler006-proc.py
458
3.734375
4
#!/usr/bin/env python3 # Problem 6: Sum square difference # https://projecteuler.net/problem=6 import sys def euler006(bound): numbers_sum = 0 squares_sum = 0 for number in range(1, bound + 1): numbers_sum += number squares_sum += number ** 2 return numbers_sum ** 2 - squares_sum def...
3432d5ff1968fcdb6ae0a7f744a0697bf140d95a
jkbockstael/projecteuler
/euler017-proc.py
1,207
3.5
4
#!/usr/bin/env python3 # Problem 17: Number letter counts # https://projecteuler.net/problem=17 import sys LENGTHS = { 0: 0, 1: 3, 2: 3, 3: 5, 4: 4, 5: 4, 6: 3, 7: 5, 8: 5, 9: 4, 10: 3, 11: 6, 12: 6, 13: 8, 14: 8, 15: 7, 16: 7, 17: 9, 18: 8,...
fa9ba2033866e57f72955bb9eb20c9e5a2ddf4f1
jkbockstael/projecteuler
/euler004-func.py
518
3.578125
4
#!/usr/bin/env python3 # Problem 4: Largest palindrome product # https://projecteuler.net/problem=4 import sys def palindrome(number): return str(number) == str(number)[::-1] def euler004(digits): return max([a * b for a in range(10 ** (digits - 1), 10 ** digits) for b in range(10 ** (di...
29c323cbe2f64ca48414ef9a10a9696910ebd1bc
dellas-coffee-blend/code-giuliaangeli
/src/exercises/adhoc.py
1,078
3.5
4
# coding=utf-8 """ Exercício 1: A Cifra de Vernam, conhecida também como "One-time Pad" é magnífica por ser extremamente simples e, ao mesmo tempo, poderosa. De fácil implementação, consiste em criptografar uma dada mensagem com uma chave usando uma operação XOR. No seguinte exemplo, sendo "a" a mensagem, "b" a chave...
47de4cf8b2e8ac30e5ed01605a5fc48f0c784224
AakashKB/5_python_projects_for_beginners
/magic_8_ball.py
670
4.125
4
import random #List of possible answer the 8 ball can choose from potential_answers = ['yes','no','maybe','try again later', 'you wish','100% yes','no freaking way'] print("Welcome to the Magic 8 Ball") #Infinite loop to keep the game running forever while True: #Asks user for inpu...
67bc28fe12ea3e4113546b3bcf82d2c72261a2ab
erishabh/restaurantClosuresCovid19
/acs_covid_combiner.py
587
3.515625
4
import pandas as pd # Importing the original data file acs_data = pd.read_csv('clean_data/SF_acs_data_clean.csv') covid_data = pd.read_csv('clean_data/SF_covid_conc.csv') # Combining the two dataframes combined_data = acs_data.merge(covid_data, on = 'census_tract') # Renaming some columns combined_data = combined_da...
1dac6eca9870c88144dd42ced0705ecefce60e42
Sunspawn/Bisection-method
/src/main.py
5,658
3.71875
4
"""Assignment 4 - Numerical Analysis Nikolay Babkin - 321123242""" import math from scipy.misc import derivative from src.userInput import read_polynomial, read_int, read_float # the error margin epsilon = 1e-6 # the test data a = 2.75 b = 3.1 k = 19 x = 3 inters = [0, 3] start = -1 end = 3.5 int...
eabfee0e5a216a8d171db44976447813de0be36f
danlimsw/Ph22
/RootFinder.py
4,140
3.984375
4
""" Root Finder Author: Soon Wei Daniel Lim Updated: 05 Jan 2015 """ from math import * def bisection(f,a,b,p): # Bisection Root Finder # f = Function of x, string # a = Guess, lower bracket # b = Guess, upper bracket # p = Precision (desired value of b-a) # Output = [a0,b0], bracket containing ...
19925883e02efc278f1c8c1b64c47007e4ee924e
Devakinandan-Sanapala/CampK12
/Pattern Printning.py
163
3.8125
4
n = int(input("Please enter a number")) patt = "()#@##@@@!!!!!#$%&&&&**(((((" for i in range(n): print(patt) patt += "()#@##@@@!!!!!#$%&&&&**((((("
b07ed227465ddff1e022d27eb6d1961c5f823f29
Devakinandan-Sanapala/CampK12
/Rock Paper Scissors.py
1,827
4.0625
4
import random user_Input = input("Please choose rock paper or scissors") lis = ["rock","paper","scissors"] computer = random.choice(lis) if computer == user_Input: print("The game is a tie") else: if user_Input == "rock" and computer == "scissors": print("Rock breaks Scissor User has won...
49275ff188a41ec6666fc54f714a5fc20f9116dd
Devakinandan-Sanapala/CampK12
/Temperature Converter.py
258
4.0625
4
temperature = int(input("Please type the temperature in celcius to convert")) x = str(temperature + 273.15) y = str((temperature * 1.8) + 32) print("The temperature in kelvin is" + x + "degrees") print("The temperature in farenheit is" + y + "degrees")
5109801883208e7a80f0ee0bd50fb808f9c112b0
huszarpp/CodewarsPython
/split_strings/string_split.py
210
3.59375
4
def solution(s): if len(s) % 2 == 1: s += "_" split_string = [] for i in range(0, len(s) - 1, 2): split_string.append(s[i] + s[i + 1]) print(split_string) return split_string
ae8028eeab978cd236370a5b5d91b5ee780ba903
oinkcat/scripting-lang
/compiler/compatibility.py
989
3.625
4
# -*- coding: utf-8 -*- """ Compatibility functions for Python 3 """ import codecs from sys import version_info IS_PYTHON_3 = version_info.major == 3 def num_range(start, end): """ Generate numeric range """ if IS_PYTHON_3: return range(start, end) else: return xrange(start, ...
8cd9995880ede0efa322fc190883e2309c8dfed0
andy5523/Python-
/2.py
359
3.734375
4
str = input("문자열:") def ic(str): for i in range(len(str)): a= "" a= a + str[i] return str def icro(str): for j in range(len(str)-1,-1,-1): b= "" b= b + str[j] b= "".join(reversed(str)) return b print("개별 문자 출력:",ic(str)) print("역순 개별 문자 출력:",icro(st...
4c99a58c3445f3f0b817531521a9e3f401ca7cca
Matt-CompSci/Unicode2020
/strike.py
2,908
3.53125
4
def get_score(input): score = 0 prevBall = 0 for ballIdx, ball in enumerate(input): if ball == "X": score += 10 if ballIdx + 3 < len(input): for i in range(min(len(input) - ballIdx - 1, 2)): if input[ballIdx + i + 1] == "X": ...
c1edebdfaeefb87d193b85a6625577f18abde90a
suhas99/Data-structures-python
/Arrays/ThreeNumberSum.py
1,748
3.84375
4
O(n^3) Time complexity def threeNumberSumSolution1(array, targetSum): triplets = [] array.sort() for i in range(len(array) - 2): for j in range(len(array) - 1): for k in range(len(array)): if array[i] + array[j] + array[k] == targetSum: triplets.append...
2c59e09680bf3844d61bf41394d55a1082354d9b
hsunami10/React-Native-Projects
/manager/src/assets/airports/parse_airports.py
920
3.546875
4
import sys import json # https://openflights.org/data.html if len(sys.argv) != 2: print "Error: Please include one argument" exit(1) try: file = open(sys.argv[1], "r") except Exception as e: print "Error: File not found." raise lines = [line.rstrip('\n') for line in file] airport_dict = {} for l...
c1f77aca918cb0b177d9f42a314ff9186c4cb051
rdegraw/numbers-py
/fibonacci.py
423
4.25
4
#---------------------------------------- # # Fibonacci number to the nth position # #---------------------------------------- position = int( raw_input( "Please enter the number of Fibonacci values you would like to print: " )) sequence = [0] while len(sequence) < position: # F(n) = F(n-1) + F(n-2) if len(sequen...
8ebdb90a1d7fdc072003979b2f35eae968b15548
lektor/lektor
/lektor/metaformat.py
3,252
3.640625
4
def _line_is_dashes(line): line = line.strip() return line == "-" * len(line) and len(line) >= 3 def _process_buf(buf): for idx, line in enumerate(buf): if _line_is_dashes(line): line = line[1:] buf[idx] = line if buf and buf[-1][-1:] == "\n": buf[-1] = buf[-1][:-1...
33729028b290275d8d72569b7b7d354bd2f35cf1
cristianj23a/Curso-Basico-de-Python
/conversor.py
731
3.703125
4
def conversor(tipo_moneda, valor_dolar): moneda = input("¿Cuántos " + tipo_moneda + " tienes?: ") moneda = float(moneda) dolares = moneda * valor_dolar dolares = round(dolares,2) dolares = str(dolares) print("Tienes $" + dolares + " dólares") menu = """ Bienvenido al conversor de monedas 💰 1 ...
2c9c32cf9cc8b5157829c720e8cc33f54ef84081
DomBouman/Bouman_Dominik_Ex45
/Chapter45.py
7,865
3.6875
4
## This game will be set in the year 2800 onea majestic planet ## You will be put through multiple rooms and problems that will change how you proceed ## Your goal is to get off this planet and find your way back to Earth ## Welcome to Ethereal from sys import exit ; from random import randint ; import Death class Sce...
4d0987b5fca0c8342c604f9e18cec3493dbea869
limchiahau/ringgit
/ringgit.py
2,001
4.15625
4
from num2words import num2words import locale locale.setlocale(locale.LC_ALL,'') def to_decimal(number): ''' to_decimal returns the given number as a string with groupped by thousands with 2 decimal places. number is a number Usage: to_decimal(1) -> "1.00" to_decimal(1000) -> "1,000.00...
076e392ca3b288c96e737482b278ab9833871ae7
laurajer04/Python.Challenge
/PyBank/main.py
686
3.5
4
import csv Pybankpath= r"C:\Users\laura\Desktop\LearnPython\Python.Challenge\PyBank\budget_data.csv" with open(Pybankpath, newline='') as Pybankcsv: pyreader = csv.reader(Pybankcsv, delimiter=',') pyheader = next(pyreader, None) months = [] profit = [] change = [] for row in pyreader: ...
edef4d13be4dc82ff2bc5fca6da200afdffcdb35
aayzaa/checkers-ai
/checkers/board.py
21,997
4.40625
4
"""Contains a class that represents a checkers board. It works as a game state representation for the checkers game. (CC) 2020 Alex Ayza, Barcelona, Spain alexayzaleon@gmail.com """ import copy import random import checkers.constants as constant from checkers.player import Player from checkers.piece import Piece c...
1bbc919cd396a4e5fdd3fe153ab397edb029c1a8
mvortizr/ds-act-diagnostica
/main.py
11,969
4.0625
4
### Para correrlo python3 main.py class Neighbours: def setNeighbour(self,direction,box): setattr(self, direction, box) class SquareNeighbours(Neighbours): def __init__(self,top=None, bottom= None, left = None, right = None): self.top = top self.bottom = bottom self.right = ri...
7ed6d36d397f2be510c44b06750ae4238d2294dc
GaYoung87/Algorithm
/python_algo/프로그래머스/20210618_괄호 회전하기.py
796
3.671875
4
s = "[](){}" # 3 # s = "}]()[{" # 2 # s = "[)(]" # 0 # s = "}}}" # 0 def check(s): temp = [] for word in s: if word in ['[', '(', '{']: temp.append(word) else: if not temp: # temp에 값이 없으면 return False # temp에 값이 들어있으면 x = temp...