blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
51d6d7e809e0ac1577f68cb27cb5aef4dd2ac7d5 | yoskovia/python_uat | /notebooks/src/Python Basics.py | 2,484 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Python Basics
#
# This notebook contains examples of basic Python syntax.
#
# ### Topics
# - Getting Help
# - Basic Operations
# - Lists
# - Functions
# In[ ]:
# Click this cell, and then click the "Run" button above to execute the code within
print('Hello world!')
# ##... |
700977eac87b6d1d82716fc43a2f9ba2f3293ca8 | jonmagnus/IN3110 | /assignment6/visualize.py | 4,039 | 3.703125 | 4 | '''
Display the predictions of classifier.
'''
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
from data import plot_with_columns
from data import get_split_table, get_labels
from fitting import fit
def visualize_confidence(classifier, table, col1, col2, ax=None, **kwargs):
'''
... |
db82c6951e52f364893ee8575bbd2af211d094a6 | Huijuan2015/leetcode_Python_2019 | /355. Design Twitter.py | 2,110 | 3.890625 | 4 | class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
import collections
self.follower = collections.defaultdict(set)
self.tweets = collections.defaultdict(list)
self.timer = 0
def postTweet(self, userId, tweetId):
... |
51af00325626738a46a5aee2dad846984e3e5271 | mdebowska/Gra_w_Pana | /src/GameClass.py | 4,354 | 3.828125 | 4 | from src import CardClass
class Game:
def __init__(self):
self.stack = []
self.players = []
self.restart()
def __repr__(self):
"""
Wyświetla karty ze stosu
:return:
"""
return 'gra0: '+','.join( [card.__repr__() for card in self.stack] )
... |
affe24da0f780822a8031dd251401d54be6dd757 | Frankiee/leetcode | /archived/string/1784_check_if_binary_string_has_at_most_one_segment of Ones.py | 848 | 3.96875 | 4 | # [Archived]
# https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/
# 1784. Check if Binary String Has at Most One Segment of Ones
# History:
# 1.
# Apr 10, 2021
# Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones.
# Otherw... |
f47544f7d05bf415364282f1b7a66fa0cfd2b9cc | number23/iLibrary | /pyLib/_date.py | 1,294 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = [
'prev_month',
'next_month',
'get_Monday'
]
from datetime import timedelta
def prev_month(d):
"""Calculate the first day of the previous month for a given date.
>>> prev_month(date(2004, 8, 1))
datetime.date(2004, 7, 1)
... |
dc12be306513bde65bf03b921c5d99531090fc29 | BbillahrariBBr/python | /Book1/10-13-18-4-prime-1.py | 491 | 4.21875 | 4 | def is_prime1(n):
if n<2:
return False
prime = True
for x in range(2, n):
if n%x == 0:
print(n, "is divisable by: ",x)
prime = False
return prime
while True:
number = input("Please enter a number enter (0 for exit):")
number = int(number)
if number ... |
69390dd009e5305d8ed06c01b8624fb8e42e7d29 | abdlhhelal/automate-the-boring-stuff-with-python-answers | /Chapter7/RegStrip.py | 551 | 3.625 | 4 | import re
def regStrip(*String):
try:
if String[1]!=True:
StripChar=String[1]
except:
StripChar='\s'
StripRegex = re.compile(r'^[%s]*((\w|\W)*?)[%s]*$'%(StripChar,StripChar))
try:
StrippedString=StripRegex.search(String[0]).group(1)
return StrippedString
... |
711c775990736bd586f39f82bda381f943066558 | stefanVanEchtelt/blok_1_opdrachten_prog | /Control Structures/2. If with 2 boolean operators.py | 172 | 3.703125 | 4 | age = eval(input('Geef je leeftijd: '))
hasPassport = str(input('Nederlands paspoort: '))
if (age >= 18) & hasPassport == 'ja':
print('Gefeliciteerd, je mag stemmen!') |
f4f7f785d6cf6317ca93dc440ccae019c2888485 | roshan2M/edX--mitX--introduction-to-computer-science-and-programming-with-python | /Week 2/Lecture 3 - Simple Algorithms/Questions/Lec3Problem5b.py | 85 | 3.9375 | 4 | for num in range(10, 0, -2):
if (num == 10):
print "Hello!"
print num |
9d4ee9560ba9b87a8bf746c64abfc2837239c4c0 | skinder/Algos | /PythonAlgos/Done/Find_Difference.py | 1,123 | 3.796875 | 4 | '''
https://leetcode.com/problems/find-the-difference/
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Expl... |
8e739e1c7460aa1aa8ae1569936353a43abd0c14 | LiangJinYong/PythonRpa | /rpa_basic/desktop/2_mouse_move.py | 842 | 3.5625 | 4 | import pyautogui
# 마우스 이동
# pyautogui.moveTo(200, 100) # 지정한 위치(가로 x, 세로 y)로 마우스를 이동
# pyautogui.moveTo(100, 200, duration=5) # 0.25초 동안 100, 200 위치로 이동
# pyautogui.moveTo(100, 100, duration=0.25)
# pyautogui.moveTo(200, 200, duration=0.25)
# pyautogui.moveTo(300, 300, duration=0.25)
# 상대 좌표로 이동 (현재 커서가 있는 위치로 부터)
#... |
1348d67a60332c661887f783248771b3c3774125 | daniel-reich/turbo-robot | /biJPWHr486Y4cPLnD_13.py | 832 | 4.28125 | 4 | """
Write a function that divides a list into chunks of size **n** , where **n**
is the length of each chunk.
### Examples
chunkify([2, 3, 4, 5], 2) ➞ [[2, 3], [4, 5]]
chunkify([2, 3, 4, 5, 6], 2) ➞ [[2, 3], [4, 5], [6]]
chunkify([2, 3, 4, 5, 6, 7], 3) ➞ [[2, 3, 4], [5, 6, 7]]
chunki... |
cc41e712dcaddc187b319f263ee8e941badfe398 | AnTznimalz/python_prepro | /fibooooo.py | 311 | 3.78125 | 4 | def fib(num):
'''Func. fib for super speed algorithm for fibo'''
fib(num) = fib(2*num)+fib(2*num-1)
fib(2*num) = fib(num-1)**2 + fib(num)**2
fib(2*num-1) = (2*fib(num+1)+fib(num))*fib(num)
if num == 0 or num == 1:
return num
else:
return fib(num)
print(fib(int(input()))) |
052b8f657b5ed71debf9de708a39fa43f9048dd6 | makhmudislamov/leetcode_problems | /book_cci/check_permutation.py | 1,380 | 3.78125 | 4 | """
Chaoter 1, Page 90
given two strings, check if one is a permutation of another
"""
# questions to ask:
# acceptable and optimal time and space
# case sensetivity, whitespace, upper, lower cases. Assume case sensetive to whitespace
# base case
# if lenghts are differetn then return false
# approach 1. Time and s... |
b736c65837feb958bed1d64662c7ec4f68eff265 | DreamingFuture/python-crawler | /视频随堂/18.xpath的使用.py | 681 | 3.578125 | 4 | # 作者 :孔庆杨
# 创建时间 :2019/1/29 14:42
# 文件 :18.xpath的使用.py
# IDE :PyCharm
'''教程网址: w3shcool'''
import requests
from lxml import etree
from fake_useragent import UserAgent
url = 'https://www.qidian.com/rank/yuepiao?chn=21'
headers = {
"User-Agent": UserAgent().random
}
response = requests.get(... |
c76a9467a7de411078b256474d3e7b2250da1cf6 | vqpv/stepik-course-58852 | /9 Строковый тип данных/9.2 Срезы/6.py | 163 | 3.78125 | 4 | string = input()
print(len(string))
print(string * 3)
print(string[:1])
print(string[:3])
print(string[-3:])
print(string[::-1])
print(string[1:len(string) - 1])
|
e9d2d9634ede05e54e21768aaf69f26f12dea34f | apb7/ProjectEuler | /p5.py | 198 | 3.5 | 4 | def is_div(n):
for i in range(2,21,1):
if n%i!=0:
return False
return True
i=2520
while True:
if is_div(i):
break
i=i+1
print str(i)
|
9e29f220459cfdfebd5d51709649909b54e0a22f | JSYoo5B/TIL | /PS/BOJ/1874/1874.py | 857 | 3.5 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
cnt = int(input())
sequence = []
for i in range(cnt):
num = int(input())
sequence.append(num)
# Reverse sequence to avoid popleft operation costs
sequence.reverse()
operations = ['+']
current = 2
stack = [1]
whi... |
2b6a314f7e7ea8b26c44c84db441fa98095e84fc | noveoko/thecalculatorgamesolver | /parse.py | 551 | 3.78125 | 4 | import re
def parse_all(string):
regex = re.compile(r"((?P<add>\+\d+)|(?P<multiply>x\d+)|(?P<divide>\/\d+)|(?P<balance>\(\d+\))|(?P<subtract>\-\d+)|(?P<remove_digit>\<\<)|(?P<first_digit_to_second>(\d+)\=\>(\d+))|(?P<insert_number>\d))")
match = regex.match(string)
groups = match.groupdict()
return [(a... |
09a4ad861fb2764f9793649ca8fe23af9b7e11bd | Misora000/google-foobar | /l3_prepare_the_bunnies_escape.py | 8,543 | 3.90625 | 4 | '''
Prepare the Bunnies' Escape
===========================
You're awfully close to destroying the LAMBCHOP doomsday device and freeing Commander Lambda's bunny prisoners, but once they're free of the prison blocks, the bunnies are going to need to escape Lambda's space station via the escape pods as quickly as possib... |
95be0e08e4407fa760ec2f66779789e5fc8a9714 | negi317145/python_assignment | /merge1.py | 299 | 3.703125 | 4 | l=[]
num1=input('enter first number')
num2=input('enter second number')
num3=input('enter third number')
num4=input('enter forth number')
print(l.append(num1))
print(l.append(num2))
print(l.append(num3))
print(l.append(num4))
print(l)
a=["google","apple","facebook","microsoft","tesla"]
print(l+a)
|
589946b60871892ebc42ebdb47ec78f6e2cfe08b | Ryann-W/python | /practice.py | 9,655 | 4.125 | 4 | # the practice in py4e.com
# here is the question
#5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
# Once 'done' is entered, print out the largest and smallest of the numbers.
# If the user enters anything other than a valid number catch it with a try/except and ... |
784bcfbf7638136acdb4fb68c9884098800f8c95 | SafeeSaif/Personal-Code | /Sum of 0 till 100.py | 186 | 3.53125 | 4 | n = 100
s = 0
counter, z = 1, 1
while counter < n:
counter += 1
z = z + counter
print (counter)
print("Sum of 1 until %d: %d" % (n,z))
placeholder = input("")
|
60ec7f0cb4ccef8894def44f9d1ff64a12c3261e | poisonivysaur/LOGPROG | /Python Exercises/Day 5/EXERCISE4-Month, Day, Year.py | 634 | 4.125 | 4 | '''Exercise 4
Write a program that will allow the user to enter an 8-digit number to
represent a date value (with the format of mmddyyyy). The rst 2 digits
of this number represent the month, next 2 digits the day and the last 4
digits represent the year.'''
strInput=input('Enter a number: ')
n=int(strInput)
... |
80ab76aec811e0e6c19012e5d3e4e897dd4a6a1c | fengyehong123/Python_skill | /03-if条件判断较多的时候的优化.py | 2,115 | 3.71875 | 4 | import random
from enum import Enum
# 定义一个常量类
class Condition(Enum):
A = 1
B = 2
C = 3
D = 4
values = [1, 2, 3, 4]
choice = Condition(random.choice(values))
"""if choice == Condition.A or choice == Condition.B or choice == Condition.C:
print('go to step one')
else:
print('go to step two')
"... |
1853a6b93f34980c11ec98da0a1096d4b10b571c | dacastanogo/holbertonschool-interview | /0x10-rain/0-rain.py | 616 | 3.5625 | 4 | #!/usr/bin/python3
"""
Calculates how much water will be retained
"""
def rain(walls):
"""
Calculates water retained given width of walls
"""
if walls is None or len(walls) < 2:
return 0
water = 0
n = len(walls)
left = [0] * n
right = [0] * n
left[0] = walls[0]
for id... |
dcfa51a2ab221533eee590e3c920a24734f6c8c7 | huyquangbui/buiquanghuy-fundamental-c4e23 | /session4/hw/se1.py | 1,701 | 4.03125 | 4 | sheep1 = [5,7,300,90,24,50,75]
print ("Hello here is my flock ")
print(sheep1)
#
# writing a program is very misleading when it is (just) a function
#
# sheep = sorted(set(sheep1))
# for r in sheep:
# count = 0
# for t in sheep:
# if r >= t:
# count += 1 #if there were 2 sheep with same siz... |
016ba7b349e7f2008e6f8629f07c547333928fda | gerrycfchang/leetcode-python | /matrix/flodd_fill.py | 2,234 | 4.09375 | 4 | # 733. Flood Fill
#
# An image is represented by a 2-D array of integers, each integer representing the pixel value of the image
# (from 0 to 65535).
#
# Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill,
# and a pixel value newColor, # "flood fill" the image.#
#
# To ... |
6f0122af149b2ac8509a4526ce0a738e86f55703 | maxgreat/fileSort | /comicSort.py | 1,616 | 3.53125 | 4 | import glob
import sys
import os
def dirExplore(dirname, extension=''):
"""
Explore a directory, and the sub directory and return everry file with a given extension
"""
els = []
for path in glob.glob(dirname+'/*'):
if os.path.isdir(path) :
print(path, 'is a directory')
els += dirExplore(path)
elif os.p... |
f56cfb8105fc6fbd18fecbc17e16b90ef24d5ea6 | activehuahua/python | /pythonProject/exercise/6/6.6.py | 543 | 3.59375 | 4 | import string
def myStrip(s):
aList1=[]
aList2=[]
for i in range(len(s)):
if s[i].isspace():
continue
else:
str2=s[i:]
break
for i in range(-1,-len(str2),-1):
if str2[i].isspace():
continue
else:
if i==-1:
... |
69dab0eaa7321052752be014b79e5c7ec82ed9cd | Tsingzao/MyLeetCode | /Longest Univalue Path.py | 832 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 25 21:24:13 2018
@author: Tsingzao
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivalu... |
b9f3f3fe58995a147ad29ae82dd030a57d90db15 | itayzaga/matala1 | /equations.py | 1,152 | 3.75 | 4 | def exponent (x):
n = 1
mone = 1.0
mahane = 1
a = 1
while n <= 150:
mone = mone * x
mahane = mahane * n
a = a + (mone/mahane)
n = n + 1
return a
def Ln (x):
if (x <= 0.0):
return 0.0
yi = x - 1.0
while True:
yi_1 = yi + 2 * ((x - exponent(yi)) / (x + exponent(yi)))
if (yi - yi_1 >= 0):
if (yi... |
60d69b8b0e55fcb31921b44277a120ac02c65a0c | arundeepkakkar/Reeborg | /Step 07.py | 999 | 3.75 | 4 | from library import multi_move, turn_right, turn_back
def mov_n_put(count=1):
for _ in range(count):
move()
put()
def draw(num):
if num:
move()
turn_left()
mov_n_put(5)
turn_back()
multi_move(5)
turn_left()
move()
else:
move()
... |
4e793a09b75addab242e2ba21192bae83cad2e2e | aumc-bscs5th/Lab-Submissions | /Lab Test -17 Nov 2017/153174/GuessRandomNumber.py | 305 | 4.09375 | 4 | import random
num = random.randint(1,50)
while NumGuessed != num :
NumGuessed = int(input("Enter a number to guess the computer's random number: "))
if (NumGuessed==num):
print("You won, you guess the number, what a LUCK :D ")
else:
print("Try Again, you can guess it :D ")
|
843237490efacea3c5c65c35713414bf400ef9d2 | huyinhou/leetcode | /path-sum-ii/lcode113.py | 1,706 | 3.625 | 4 | import unittest
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
... |
76f26d3ae6ed244971955001c7784c40c0e51969 | felixzhao/WordSegmentation | /MaxWordSegmentation/MaxWordSegmentation.py | 1,966 | 3.765625 | 4 | # -*- coding: cp936 -*-
#ƥ䷨зִ, ļΪMaxWordSegmentationTest.py
#author
#date 2013/3/25
import string
import re
#ʱļڴlist
#:ʵļ, :ʵдʵlist,ʳ
def load_dict(filename):
f = open(filename,'r').read()
maxLen = 1
strList=f.split("\n")
#Ѱʳ
for i in strList:
if len(i)>maxLen:
maxLen=len(i)
return strList,maxLen;
#ִʷ.
... |
b79c0e77eff10435ebfffa69029b0b4829964ceb | nahyunsung/python | /qullze02.py | 651 | 3.578125 | 4 | import random as r
import tkinter as tk
def num():
global q_num
as_num = int(a_num.get())
if as_num == q_num:
lbl.configure(text = "정답 !!")
txtnum.configure(state = 'readonly')
elif as_num > q_num:
lbl.configure(text = "더작은 수자를 넣어봐!!")
else:
lbl.configure(text= "더큰 숫... |
becf6fdcd8ca5320e1eb57932ca4dee47cea0d21 | Ehtesham22/codeforce | /team.py | 220 | 3.59375 | 4 | n = int(input())
count = 0
for x in range(0, n):
friend_1, friend_2, friend_3 = [int(x) for x in input().split()]
vote = friend_1 + friend_2 + friend_3
if vote >= 2:
count += 1
print(count)
|
cfad42fd8831e2161755765ea45d321c24de7ae9 | kangli-bionic/algorithm | /lintcode/374.py | 1,291 | 3.6875 | 4 | """
374. Spiral Matrix
https://www.lintcode.com/problem/spiral-matrix/description?_from=ladder&&fromId=131
BFS
"""
DIRECTIONS = [
(0, 1),
(1, 0),
(0, -1),
(-1, 0)
]
from collections import deque
class Solution:
"""
@param matrix: a matrix of m x n elements
@return: an integer list
"""
... |
ab6057c146a8cd5624d52c58e56870abe87be9a9 | dhanashreesshetty/Project-Euler | /Problem 26 Reciprocal cycles/pyprog.py | 760 | 3.84375 | 4 | def checkLength(n):
rem=1
i=1
num=1 #number is the dividend and its updated in every loop
array=[] #array stores positions of obtained remainders-can be use to check if that remainder had occurred before as well as its position
array=array+n*[0]
while rem!=0 and i<=n:
rem=num%n
... |
01973cccbbcd3f29b2f0362d0703380888a9603f | MilesBurne/BalloonPopGame | /Projectile_Module.py | 3,865 | 3.90625 | 4 | #Projectile Module by Miles Burne 13/03/19
#projectile class, takes the size for the projectile
class Projectile():
#init, takes the surface of the screen, the start position, and the Quadratic class, as well as an optional input of size
def __init__(self, surface, pos, Quadratic, size=15):
#impo... |
44a17099e4bec7e03e4e6076384af876a64a40c2 | HaraHeique/Jogo-da-vida | /mundo.py | 489 | 3.5 | 4 | # -*- coding: utf-8 -*-
def carrega_mundo(arquivo):
with open(arquivo, "r") as arq:
linhas = arq.readlines()
matriz_mundo = []
matriz = [[caractere for caractere in linha[:-1]] for linha in linhas]
#Esse condicional serve para quando o arquivo(mundo) não for o arquivo 1, pois os outros arquivos e... |
32e14893649b922f2e5a92b40f803655e0f99772 | urishabh12/practice | /dfs.py | 315 | 3.578125 | 4 | n = int(input())
adjacency = []
visited = [False]*n
for i in range(n):
adjacency.append(list(map(int, input().split())))
def dfs(at):
if visited[at]:
return
print(at)
visited[at] = True
neighbours = adjacency[at]
for i in neighbours:
dfs(i)
print("-------------")
dfs(0)
|
8b85a4cc77387a4c66aad4e630c28d2b333bbb82 | huynmela/CS161 | /Project 6/6a/find_median.py | 570 | 4.34375 | 4 | # Author: Melanie Huynh
# Date: 5/6/2020
# Description: This program takes a list of numbers and returns the median of those numbers.
def find_median(list):
"""Returns the median of a list of numbers"""
list.sort() # Sorts the lists from low to high
length = len(list) # Gets length of the list
if length % 2 != ... |
e4f3429003a33bf57389b2709fb9f83800309253 | Roger-random/python_tutorials | /flow_control.py | 1,523 | 4.625 | 5 | #!/usr/bin/env python3
#############################################################################
#
# Multiple assignments takes everything on left of equal and assigns them
# everything on the right, in order. Demonstrated in this Fibonacci while loop
def fib(fib_limit):
"""This is a documentation string (docst... |
60103cf81ef0c5eac9408b436ef66aab19f250aa | jeanDeluge/pythonForEverybody | /Chap6_5.py | 338 | 3.59375 | 4 | #문자열을 저장하는 아래 파이썬 코드에서 find와 문자열 슬라이스를 사용해서 콜론 이후의 문자열을 가져온 다음,
#float 함수를 써서 실수로 변환시켜보자.
str = 'X=DSPAM-Confidence:0.8475'
char = str.find(':')
last =str.find("5",char)
answer = float(str[char+1:last+1])
print(answer) |
9357fe59a0b956edfe980f3d26da609eea0e5ea9 | AnjaliMewada12/hackerearth_programs | /The Great Kian.py | 1,285 | 3.515625 | 4 | '''The great Kian is looking for a smart prime minister. He's looking for a guy who can solve the OLP (Old Legendary Problem). OLP is an old problem (obviously) that no one was able to solve it yet (like P=NP).
But still, you want to be the prime minister really bad. So here's the problem:
Given the sequence a1, a2, ... |
882023cde8bba1262eb818079b322dbde5bff8f1 | shivamrai/pycode | /linkedlist.py | 2,588 | 3.71875 | 4 | class Node:
def __init__(self,val):
self.val = val
self.next = None
def __repr__(self):
return "Node data is = {}".format(self.val)
def getval(self):
return self.val
def setval(self, new_val):
"""Replace the data with new"""
self.val = new_val
... |
27aea80d75d8025f06f0d75b334e213d99cac09b | JoshuaHing/cs2041 | /revision/15s2/17.py | 498 | 3.609375 | 4 | #!/usr/bin/python3
import sys, re
string1 = sys.argv[1]
string2 = sys.argv[2]
if (string1 == string2):
print(string1)
else:
match = re.search(r'(.*?)(\d+)(.*)', string1)
if match:
bef = match.group(1)
lower = int(match.group(2))
aft = match.group(3)
match = re.search(r'(\d+)',... |
c08e7a8c884a7be016ee2a311b9bf8ae4209ede1 | Shafin-Thiyam/Python_prac | /func.py | 92 | 3.578125 | 4 | def greeting(name):
print("hello " + name)
n=input("Enter your Name")
greeting(n)
|
f35954e4835e906ed9972fa3fb19efa3fd9927cf | alexhla/programming-problems-in-python | /linkedlist_add.py | 861 | 3.71875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addNumbers(self, l1, l2):
carry = 0
head = ListNode(0) # create head node
curr = head
while l1 != None or l2 != None:
v1 = l1.val if l1!=None else 0
v2 = l2.val if l2!=None else 0
n = v1 + v2 + carry... |
e0dd4e919c585cf36edd0ea96a9e143e9a801fa1 | taoyan/python | /Python学习/day10/json序列化.py | 977 | 3.59375 | 4 | import pickle
import json
class Student():
def __init__(self,name,age):
self.name = name
self.age = age
s = Student('yant',26)
#dumps()方法,返回序列化后的bytes
print(pickle.dumps(s))
f = open('student.txt','wb')
pickle.dump(s,f)
f.close()
f = open('student.txt','rb')
s2 = pickle.load(f)
f.close()
print(s2... |
2ac633d31721ae8e8d245d1643bfeb72d1a02b7f | vektorelpython19/pythontemel | /OOP/Inheritance.py | 1,383 | 4.0625 | 4 | # Inheritance
class A:
def __init__(self):
self.__gizli = 1
self.a = "A"
def aFonk(self):
return 1
class B(A):
def __init__(self):
super().__init__()
self.b = "B"
class C(B):
def __init__(self):
super().__init__()
self.c = "C"
class D:
... |
c881aa3dc9b4f97dc107f67c2b0a45ce93613bed | famaxth/Way-to-Coding | /snakify-problems-python/6/The index of the maximum of a sequence.py | 149 | 3.578125 | 4 | max = 1
i = 1
max_i = 1
a = int(input())
while a != 0:
if a > max:
max = a
max_i = i
a = int(input())
i += 1
print(max_i) |
9f51d3d9d39fc4425e3b83e13018f13d6b43d376 | MontessoriSchool-CS/Intro-Python-2.1-Simple-Maths | /main.py | 358 | 3.625 | 4 | # FORK ME or copy the code! Please don't request edit access. This is the original so it needs to stay undedited for all users.
# Task 1 - Add comments to this code to predict what it will do.
print(8 + 2)
print( 8 - 2)
print(8 * 2)
print(8 / 2)
print(8 // 2)
# Task 2 - Write code that calculates and outputs the... |
4cf0e25d1658afb75acd0d30918a323d10d2a398 | Torbacka/adventofcode | /2021/day1/main.py | 259 | 3.53125 | 4 | from utils import *
numbers = [int(line) for line in open("input/input.in").readlines()]
if __name__ == '__main__':
print(sum([int(b) > int(a) for a, b in zip(numbers, input[1:])]))
print(sum([int(b) > int(a) for a, b in zip(numbers, input[3:])]))
|
600c0fd97db4ccf46cb63d96dc0dcaada576f671 | Joes-BitGit/Leetcode | /leetcode/num_island.py | 1,818 | 3.765625 | 4 | # DESCRIPTION
# Given a 2d grid map of '1's (land) and '0's (water),
# count the number of islands. An island is surrounded by water
# and is formed by connecting adjacent lands horizontally or vertically.
# You may assume all four edges of the grid are all surrounded by water.
# EXAMPLE 1:
# Input:
# 11110
# 11010
# ... |
5f69cbc463a59cf9febc23025dcea957834ca17c | Bukio-chan/sotsuken_flask | /calc.py | 12,168 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from matplotlib.image import imread
from matplotlib import pyplot
import numpy as np
import random
import operator
import pandas as pd
import matplotlib.pyplot as plt
import string
import csv
class Attraction:
# distance.csvのデータを2次元配列distance_listに格納
with open("static... |
d72b0ff579977b6d6d3384e179d0f422fca1ff19 | mukoedo1993/Python_related | /python_official_tutorial/chap5_3/tuple.py | 600 | 4.09375 | 4 | t = 12345, 54321, 'hello!'
print(t[0])
print(t)
# Tuples may be nested
u = t, (1, 2, 3, 4, 5)
print(u)
# Tuples are immutable:
#t[0] = 88888
"""
Traceback (most recent call last):
File "tuple.py", line 14, in <module>
t[0] = 88888
TypeError: 'tuple' object does not support item assignment
"""
# but they c... |
8bec6339bcb2a8ce60a1cb4dbfd4e3d68d117104 | cpeixin/leetcode-bbbbrent | /tree/levelOrder.py | 1,446 | 3.921875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2021/4/29 8:05 上午
# @Author : CongPeiXin
# @Email : congpeixin@dongqiudi.com
# @File : levelOrder.py
# @Description:给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
#
#
#
# 示例:
# 二叉树:[3,9,20,null,null,15,7],
#
# 作者:力扣 (LeetCode)
# 链接:https://leetcode-cn.com/l... |
45a5b4a1ed375577bd77af12cced2cece7fa5960 | jedzej/tietopythontraining-basic | /students/hyska_monika/lesson_02_flow_control/BishopMoves.py | 563 | 3.796875 | 4 | # The program print that Bishop can move from one field to second field
import math
v1 = int(input("Put vertical position for 1st field (from 1 to 8): "))
h1 = int(input("Put horizontal position for 1st field(from 1 to 8): "))
v2 = int(input("Put vertical position for 2nd field(from 1 to 8): "))
h2 = int(input("Put ho... |
6469622c5371a5d9c6551ef0e3ceb245b52fca01 | ashfaqrehman/calculator | /tests/test_add.py | 844 | 3.515625 | 4 | """
Test the add() function of the calculator
"""
import pytest
#import pdb;pdb.set_trace()
from calculator import add
def test_two_plus_two():
"""
If given 2 and 2 as paramters, 4 should be returned
"""
assert add(2,2) == 4
def test_three_plus_three():
"""
If given 3 and 2 as paramters, 6 shou... |
0f007964f6d6f037ebcadc88ef781963bb70b027 | xpeeperp/Python | /ftp/ftp5.py | 5,064 | 3.640625 | 4 | # !/usr/bin/python
# coding:utf-8
# write:JACK
# info:ftp example
import ftplib, socket, os
from time import sleep, ctime
def LoginFtp(self):
ftps = ftplib.FTP()
ftps.connect(self.host, self.port)
ftps.login(self.name, self.passwd)
# 未进行判断地址输入是否为ip或者域名;可以进行判断是否包含<或者实体符号以及';其他可以忽略
class LoFtp(object):
... |
787ece1d731649dfe63bb3f58597113eb08a732e | rika/TCC11 | /filter/old/animation.py | 4,159 | 3.96875 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
'''
Animation of tracking data
Author: Ricardo Juliano Mesquita Silva Oda <oda.ric@gmail.com>
Data: 24/09/11
Filename: simulation.py
To run:
python simulation.py [FILENAME] [STARTFRAME] [ENDFRAME]
The program will run an animation of the tracking data in the interval
of fram... |
55e38f479e83cc1e37e5ae854f80e7c79add8fa4 | melandres8/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 1,316 | 4.625 | 5 | #!/usr/bin/python3
"""Square class"""
class Square():
"""__init__ constructor: Runs always when we
create a new instance of a class
Attributes:
attr1 (int): is the size of a square
"""
def __init__(self, size=0):
"""
Inicializing my class with
Args:
si... |
ede227bd6cb479c516d598399d0506a025064855 | aolbrech/codility-lesson-solutions | /Tasks/Painless_Lesson05_PassingCars/Solution_PassingCars.py | 705 | 3.75 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
nrCarsTravellingEast = 0
for value in A:
nrCarsTravellingEast += value
nrPassingCars = 0
for value in A:
if value == 0:
... |
326cf8cc6cbb625f5cf36ff4a836f7ed0337e37d | ravisjoshi/python_snippets | /Strings/NumberOfSegmentsInAString.py | 627 | 4.25 | 4 | """
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Input: "Hello, my name is John" / Output: 5
"""
class Solution:
def countSegments(self, _str):
count = 0... |
0e73e46a6b04bec969f6624b596a7025d25c027a | Gafficus/Delta-Fall-Semester-2014 | /CST-186-14FA(Intro Game Prog)/Nathan Gaffney CHapter 4/N.G.Project2.py | 209 | 4.28125 | 4 | #Created by: Nathan Gaffney
#14-Sep-2014
#Chapter 4 Project 2
#THis program will reverse a string
phrase = raw_input("Enter a phrase: ")
strLen = len(phrase)
while strLen > 0:
print phrase[strLen-1]
strLen-=1
|
89196e1879dc9d6c0c088bd89bf1c734cd60bcdf | oneshan/Leetcode | /accepted/147.insertion-sort-list.py | 1,454 | 3.8125 | 4 | #
# [147] Insertion Sort List
#
# https://leetcode.com/problems/insertion-sort-list
#
# Medium (32.81%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '[]'
#
# Sort a linked list using insertion sort.
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(sel... |
546d50a0ffc35a2ba9cf50068d0c22ce1411c314 | liliankotvan/urionlinejudge | /URI1042.py | 205 | 3.8125 | 4 | x, y, z = raw_input().split(" ")
x, y, z = int(x), int(y), int(z)
list = [x, y, z]
list_sorted = sorted(list)
for s in list_sorted:
print (s)
print ("")
for l in list:
print (l)
|
352fac621bb95f9a93a289b4168c906f518be640 | ksami/cg3002py | /timer.py | 628 | 3.515625 | 4 | # Timer.py
import time
# Raises a flag when x seconds are up
# params: num of seconds
def alarm(x):
try:
time.sleep(x)
print "timer up!!"
except KeyboardInterrupt:
#Ctrl-C
pass
# Puts x onto queue q once x seconds are up
# params: queue, num of seconds
def timer(q, x):
try:
for i in xrange(1, x+1):
t... |
969f9a0d96c66c5ec75e74ae90d628a4b22f0cc6 | Donn-Lee/Py-algorithm-leetcode | /algo/20.Valid Parentheses.py | 1,611 | 3.9375 | 4 | '''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
'''
... |
f790e6e4c8ee11f24b50f055e8306d519be2ba51 | waynessabros/Linguagem-Python | /script_18.py | 379 | 4.125 | 4 | #listas em python
#-*- coding: utf-8 -*-
lista = [124,345,72,46,6,7,3,1,7,0]
lista.sort()#vai ordenar numericamente do menor ao maior
print(lista)
lista.sort(reverse=True) #vai ordenar numericamente do maior ao menor
print (lista)
lista.reverse()#reversão da lista
print(lista)
lista2 = ["bola", "abacate", "dinhe... |
cb315996c93f24797d0e2016e26a0c07b8f832f0 | TerryRPatterson/PythonHardWay | /ex9.py | 517 | 3.90625 | 4 | # Here's some new strange stuff, remeber type it exactly.
#The days of the week
days = "Mon Tue Wed Fri Sat Sun"
#backslash is the espcace character n incidates a new line
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
#Printing the variables
print("Here are the days: ", days)
print("Here are the months ",months)
... |
232d26a3ec5d0f9c80c58d9135d2b079e50d3a11 | TechGirl254/Training101 | /OperatorsBasic.py | 219 | 3.765625 | 4 | modulus =23334 % 8
print(modulus)
# Arithmetic
# comparison Operators
result=2==3
print (result)
# equality
# inequality
results=2!=3
print((results))
# logical operators
# AND,OR,NOT
res =2 < 3 and 10 <20
print(res) |
19b0c4a7a8e248466766b6fdac9bf6977cd391f3 | CarlTheUser/PythonPractices | /venv/AreaCalculationOperation.py | 2,524 | 4.03125 | 4 | from abc import ABCMeta, abstractmethod
from Operation import Operation
import math
class AreaCalculationOperation(Operation):
__metaclass__ = ABCMeta
SQUARE = None
RECTANGLE = None
TRIANGLE = None
CIRCLE = None
def __init__(self, name):
super().__init__(name)
@abstractmethod
def calculate_area(self):... |
aa8cf5d668f79020c9dfb1124e239a4bf0b116f9 | alexmovsesyan/othello | /othello_game_logic.py | 15,273 | 3.96875 | 4 | #othello_game_logic.py
#Alexandra Movsesyan
#42206297
Black = 1
White = 2
class InvalidMoveError(Exception):
'''
Raised whenever an invalid move is made
'''
pass
class GameOverError(Exception):
'''
Raised whenever an attempt is made to make a move after the game is
already over
'''
... |
814199dda7f71f5006db447ca1e310adcf7d7c56 | timseymore/depths-of-madness | /src/models/enviroment/platform.py | 4,762 | 3.9375 | 4 | import pygame
class Platform(pygame.sprite.Sprite):
"""Platform that floats or moves in the game."""
def __init__(self, x, y, x_speed, y_speed, min_x, max_x, min_y, max_y):
""" Constructor Method
- x: int : x position of platform
- y: int : y position of platform
- x_speed: i... |
d45232f1c2aaaf31531ebcd09a544d410f8c0c00 | Yanfreak/datastructurealgorithm | /Chapter7/link.py | 18,013 | 4.0625 | 4 | class Empty(Exception):
pass
class LinkedStack:
"""LIFO Stack implementation using a singly linked list for storage."""
# nested _Node class
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next' # streamline memory usa... |
3fb3173413fc7e48258a7e965e749704b5f34bf9 | mgarchik/P2_SP20 | /Labs/hangman.py | 3,490 | 4.34375 | 4 | """
Matthew Garchik
Hangman
February 2020
"""
import random
# Hangman game
# PSEUDOCODE
# setup your game by doing the following
# make a word list for your game
# grab a random word from your list and store it as a variable
# in a loop, do the following
# display the hangman using the gallows
# display the used le... |
3a22e30eeef061f243ed350b149b318153731ea6 | akash30g/Shoping-list | /AkashGuptaA1.py | 16,880 | 4.15625 | 4 | """
Made by: Akash Gupta. Date: 8nd September 2016
Detail:
This program has two list to store the data which is type of dictionary. When program begin, it will load the data
from items.csv into shopItem. Then, user can choose display or add or mark those items which have been loaded in the
r... |
9e560d2c12a0c2efed6461224af0c7adb7145c39 | AllenLiuX/My-LeetCode | /leetcode-python/数独.py | 2,585 | 3.625 | 4 | # -*- coding: utf-8 -*-
import datetime
class solution(object):
def __init__(self,board):
self.b = board
self.t = 0
def check(self,x,y,value): #检查每行每列及每宫是否有相同项
for row_item in self.b[x]:
if row_item == value:
return False
for row_all in self.b:
... |
3227d51141d6674ffa184f79b9818c5621d6d69c | rodolfoghi/urionlinejudge | /python/1255.py | 585 | 3.84375 | 4 | testes = int(input())
for teste in range(testes):
palavra = input().lower()
caracteres = {}
for c in palavra:
if c.isalpha() and c not in caracteres:
caracteres[c] = palavra.count(c)
# Ordenar o dicionário em ordem
#decrescente de valor e crescente de chave
caracteres_orden... |
67a6cdba83e0f0b0ddd1a6fda7997673702d8f28 | Timidger/Scripts | /Math/Real Zeros.py | 1,065 | 3.6875 | 4 | def RealZeros(equation):
numerator,denominator, answer = [],[],[]
firstcoe,lastcoe = equation[0],int(equation[-1])
for i in range(1,lastcoe/2 + 1):
if lastcoe % i == 0:
numerator.append(i)
numerator.append(lastcoe)
if firstcoe.isdigit() is False:
denominator = [1... |
fb0b7cdd94d592620f372ecd6d28c372d6f307f3 | limmihir-test/analytics | /test2.py | 988 | 4.03125 | 4 | # The below code has some issue and will throw errors. Plese fix them so that the output is as follows:
# value error
# invalid literal for int() with base 10: 'a'
# My name is Brandon Walsh
# That's totally the present!
import sys
def error_1():
e = None
try:
x= int('a')
... |
e3ba40d190a2d59a51c455ef0f0ca03f1af07a78 | chrisvanndy/holbertonschool-higher_level_programming | /0x0B-python-input_output/11-student.py | 2,017 | 4.03125 | 4 | #!/usr/bin/python3
"""Modue creates method class_to_json() which returns the\
dictionary description as simple data structure for JSON\
serialization of an object."""
class Student:
"""class Student declared with publid instance attr\
first_name, last_name, and age"""
def __init__(self, first_name, last_... |
b34ce665798b7bcc23f0d8668d41a2e95bd0d266 | CodeEMP/DCpython | /week1/sat/caesarcipher.py | 435 | 3.75 | 4 | l2i = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26)))
i2l = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
key = 13
text = input("What to Cipher? ")
cipher = ""
for c in text.upper():
if c.isalpha():
cipher += i2l[(l2i[c] + key)%26]
else:
cipher += c
text2 = ""
for c in cipher:
if c.isa... |
07562dea45508d73752f8b1f0ca50718d2fd9a47 | sudocoder98/BE-Coursework-and-Practicals | /Current_Semester/DWM/knn.py | 1,154 | 3.71875 | 4 | # K-Nearest Neighbours for 2D Data in Python
# Define Math function
def sq(n):
return n**2
def sqrt(n):
return n**0.5
# Accept Data
classifiers = [[x,0] for x in input("Enter the list of classifiers separated by spaces: ").split()]
historic_data = [tuple([y for y in x.strip().split()]) for x in input("Enter the dat... |
4515d630a46e45e5829cf1341867715ff990de62 | nkukarl/notes | /py_partial.py | 428 | 3.796875 | 4 | from functools import partial
def foo(a, b, c):
print a, b, c
# create partial function, let b=1 and c=2
p_foo = partial(foo, b=1, c=2)
# for p_foo, only provide one argument, 3 is assigned to a
p_foo(3)
# provide two arguments, explicitly mention b=4 to overwrite b=1
# in the definition of p_foo
p_foo(3, b=4)
# ... |
8f7f61c55b579f6319e5f933531156518db36a7c | EmanuelYano/python3 | /URI - Lista 2/1040.py | 608 | 3.71875 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
n1, n2, n3, n4 = input().split()
n1, n2, n3, n4 = float(n1),float(n2),float(n3),float(n4)
m = (n1 * 2 + n2 * 3 + n3 * 4 + n4 * 1) / 10
if m < 5.0:
print("Media: %.1f"%m)
print("Aluno reprovado.")
elif m > 7.0:
print("Media: %.1f"%m)
print("Aluno aprovado.")... |
312c010bc1e11e1fb3f38481ec41265859380568 | MHKNKURT/python_temelleri | /6-Pythonda Döngüler/while-demo.py | 1,262 | 4 | 4 | # sayilar = [1,3,5,7,9,12,19,21]
#1saylar listesini while ile yazdırın.
# i = 0
# while (i < len(sayilar)):
# print(sayilar[i])
# i += 1
#2 Başlangıç ve bitiş değerlerini kullanıcıdan alıp, aradaki tüm tek sayıları yazdırın.
# baslangic = int(input("Başlangıç: "))
# bitis = int(input("Bitiş: "))
# i = baslangic... |
0237eb989651118a7f95c382d312880b67335af7 | subhasmitasahoo/leetcode-algorithm-solutions | /number-of-corner-rectangles.py | 807 | 3.5 | 4 | # Problem link: https://leetcode.com/problems/number-of-corner-rectangles/
# Time complexity: O(R*C*C)
# Space complexity: O(C*C)
class Solution:
def countCornerRectangles(self, grid: List[List[int]]) -> int:
store = {}
rlen = len(grid)
clen = len(grid[0])
res = 0
... |
09b6c952844ecbb1dc5b9c298be6c6ad20a52d83 | evtodorov/aerospace | /SciComputing with Python/ISA/Calc-ISA.py | 2,677 | 3.796875 | 4 | import math
#data
p0 = 101325.0 #Pa
T0 = 288.15 #K
rho0 = 1.225 #kg/m3
hTrop = 11000. #m
hStrat = 20000. #m
aTrop = -0.0065 #K/m
g0=9.80665 #m/s^2
R = 287.
TStrat = T0 + aTrop*hTrop
pStrat = (TStrat/T0)**(-g0/aTrop/R)*p0
rhoStrat = (TStrat/T0)**(-g0/aTrop/R-1)*rho... |
5cf9bbed603334d9bcd576b87cec30a2ab411389 | ebbitten/Courses | /6.00.1/Quiz/InterDiff.py | 948 | 4.09375 | 4 | def dict_interdiff(d1, d2):
'''
d1, d2: dicts whose keys and values are integers
Returns a tuple of dictionaries according to the instructions above
'''
# Your code here
#Initialize any parameters that you'll populate
sharedKeys=[]
d1Only=[]
d2Only=[]
interS={}
diffS={}
#... |
e9ec487b00e82eafe54a87fcac8b0f3332830dd8 | Qondor/Python-Daily-Challenge | /Daily Challenges/Daily Challenge #9 - What's Your Number/number.py | 469 | 4.15625 | 4 | def phone_formatter(number: int):
"""Phone formatter function.
Format any 10 digit phone number to USA standard.
"""
if type(number) != int:
return None
number = str(number)
if len(number) != 10:
print("Only 10 numbers, please.")
return None
return f'({num... |
41575f6dc9c6de4e8e950f82a8fd3d3b83f5ec57 | EvelynBortoli/Python | /06-Bucles/EjemploTablasMultiplicar.py | 481 | 3.921875 | 4 | ####### Ejemplo tablas de multiplicar
print("\n ############ Ejemplo ##############")
numeroUsuario = input("\nIngresar el número sobre el cual quieres saber la tabla de multiplicar: ")
numeroUsuario = int(numeroUsuario)
if numeroUsuario < 1:
numeroUsuario = 1
print(f"\n\n######## Tabla de Multiplicar d... |
4a96dd58db0c5866f39f5774458ff8fa686f0031 | Eitherling/Python_homework1 | /homework4.11.py | 330 | 3.953125 | 4 | pizzas = ['pizzahut', 'burgerking', 'mcdonald']
for pizza in pizzas:
print(pizza.title())
print('*'*80)
friendPizzas = pizzas[:]
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza.title())
print("My friend's favorite pizzas are:")
for pizza in friendPizzas:
print(pizza.title())
prin... |
09688c50bc90cb7eb21575e963427a3983229e42 | rongfeng-china/CTCI_6th_python | /17-17.py | 1,102 | 4 | 4 | class Trie:
def __init__(self,words):
self.root = {}
self.end = '*'
for word in words:
self.add(word)
def add(self,word):
node = self.root
for letter in word:
if letter not in node:
node[letter] = {}
node = node... |
040738fb2f5efbaa510b3f8445e49d5bd31fd6e4 | gottaegbert/penter | /library/lib_study/187_language_pickletools.py | 458 | 3.5625 | 4 | # 此模块包含与 pickle 模块内部细节有关的多个常量,一些关于具体实现的详细注释,以及一些能够分析封存数据的有用函数。
# 此模块的内容对需要操作 pickle 的 Python 核心开发者来说很有用处;
# https://docs.python.org/zh-cn/3/library/pickletools.html
import pickle
import pickletools
class Foo:
attr = 'A class attribute'
picklestring = pickle.dumps(Foo)
pickletools.dis(picklestring) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.