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 |
|---|---|---|---|---|---|---|
7b3dd348845cf172c6c0c2334022c37c88380f04 | kondrashov-do/hackerrank | /algorithms/warmup/birthday_cake_candles.py | 624 | 3.65625 | 4 | #!/bin/python3
import os
import sys
#
# Complete the birthdayCakeCandles function below.
#
def birthdayCakeCandles(n, ar):
max_height = ar[0]
count_max_height = 0
for candle in ar:
if candle > max_height:
max_height = candle
count_max_height = 0
if candle == max_hei... |
6f7b92cd4ad501c4ff87dd213869da8f382ee87c | kondrashov-do/hackerrank | /data_structures/array/2d_arr.py | 766 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def calculate_sum(arr, r, c):
result = 0
for i in range(3):
result += arr[r][c+i]
result += arr[r+2][c+i]
result += arr[r+1][c+1]
return result
# Complete the array2D function below.
def array2D(arr):
length =... |
801e795a5095aa8eab08f2b3146750123877bda9 | kondrashov-do/hackerrank | /python/Itertools/compress_string.py | 126 | 3.703125 | 4 | from itertools import groupby
s = input()
for item, grouper in groupby(s):
print((len(list(grouper)), int(item)), end=' ') |
ee28231e0edcc87ad4254746aa3628c9240332fd | kondrashov-do/hackerrank | /python/Itertools/ordereddict.py | 292 | 3.78125 | 4 | from collections import OrderedDict
product_dict = OrderedDict()
for i in range(int(input())):
name, space, price = input().rpartition(" ")
product_dict[name] = product_dict.get(name, 0) + int(price)
#print(product_dict)
for item, price in product_dict.items():
print(item, price) |
6ba6176c13121443a781646914751b1430766e51 | RaHuL342319/Integration-of-sqlite-with-python3 | /query.py | 813 | 4.375 | 4 | import sqlite3
# to connect to an existing database.
# If the database does not exist,
# then it will be created and finally a database object will be returned.
conn = sqlite3.connect('test.db')
print("Opened database successfully")
# SELECTING WHOLE TABLE
cursor = conn.execute(
"SELECT * from Movies")
... |
6e4ec4b5c9261af127d1c60d1c5955a9590d4519 | holbertra/Python-fundamentals | /challenges_weekend_1/komodo_insurance/komo_ui.py | 3,270 | 3.703125 | 4 | import komo_manager
while True:
prompt = """
What would like to do?
----------------------
1) Add a new badge
2) Edit a badge
3) List all Badges
4) Delete a Badge
5) Quit
> """
header = """
---------------------------------
--- All current active badges ---
----... |
568cb7746930d013b840e06a2f45d44e11442572 | holbertra/Python-fundamentals | /console_apps/repo/my_data.py | 1,622 | 3.96875 | 4 | from datetime import datetime
class Vehicle:
def __init__(self, make, model, year, vin, list_price):
print("Vehicle::__init__(self, ...)")
self.make = make
self.model = model
self.year = year
self.vin = vin
self.list_price = list_price
self.date_added = date... |
ae3dfe81639e3c295061a8b173dde8303632fd41 | holbertra/Python-fundamentals | /dictionary.py | 1,201 | 4.3125 | 4 | # Dictionaries
# dict
my_dictionary = {
"key" : "value",
"key2" : 78
}
product = {
"id" : 2345872425,
"description": "A yellow submarone",
"price" : 9.99,
"weight" : 9001,
"depart" : "grocery",
"aisle" : 3,
"shelf" : "B"
}
#print(product["price"... |
0fb22986e023c9c74ae0a784723452ba86e8814a | suanthuy/DataScience_Project | /Unit7/Unit7.5.py | 2,577 | 3.875 | 4 | #read file
with open("clean_data.csv", encoding="utf8") as file:
data = file.read().split("\n")
header = data[0]
students = data[1:]
total_students = len(students)
#split header
header = header.split(",")
subject = header[5:]
#split each student in list
for i in range(len(students)):
students[i] = students[i... |
f227aaf736bc879272cf67f49746afad5ae5c90b | suanthuy/DataScience_Project | /Unit6/Unit6.2.py | 2,472 | 3.703125 | 4 | #read file
with open("clean_data.csv",encoding="utf8") as file:
data = file.read().split("\n")
header = data[0]
students = data[1:]
total_student = len(students)
#split header
header = header.split(',')
subject = header[5:]
#split each students in list
for i in range(len(students)):
students[i] = students... |
efe66229677c251320a505aa2b7a06021da85269 | iampriyavarshney/lpthw_exercise | /ex15.py | 279 | 3.953125 | 4 | from sys import argv
script,filename=argv
txt=open(filename)
print"here's your file %r:"% filename
print txt.read()
# search for python open
#"eval(txt.read())
'''print"type the filename again:"
file_again=raw_input(">")
txt_again=open(file_again)
print txt_again.read()''' |
d2cef625d07812bbc3f2334254b64be82e6feb32 | Sugal-3003/Placement | /alpha.py | 76 | 3.8125 | 4 |
b=input()
if(b>='a' and b<='z'):
print("Alphabet")
else:
print("No")
|
3c875cba3d6ad4f83cfd8aafbf2874ec1a3fe261 | nicodft/FIJ_Robotique | /00_algorithmique/01_python/liste_dico.py | 479 | 3.5625 | 4 | maListe= []
texte = "une petite phrase"
print(maListe)
maListe.append (8)
maListe.append(5.6)
maListe.append(2)
print(maListe)
maListe.sort()
print (maListe)
texte = texte.replace("a", "i")
print(texte)
for element in texte:
texte = texte.replace(element, "*")
print(texte)
phrase = "une/autre/phrase"
carac... |
19eb0fa9812193dd188f93adfdc0ac4159cc9a91 | Deaseyy/algorithm | /HJ/OJ259 画X.py | 1,737 | 4.0625 | 4 | """
n = 1: 3**0
x
n = 2: 3**1
x x
x
x x
n = 3: 3**(n-1) * 3**(n-1)
x x x x
x x
x x x x
x x
x
x x
x x x x
x x
x x x x
"""
def func(n):
# n = int(input().strip())
print('...n:', n)
matrix = [] # 用一个二维列表来表示结果。3^(n-1)阶矩阵
# 初始化map,根据题意得到的是一个3^(n-1)x3^(n-1)字符矩阵
length = po... |
b9d6fd88380bdf496ffa2646001008952dde79f0 | Deaseyy/algorithm | /数组系列/有序数组中绝对值最小的数.py | 1,262 | 3.8125 | 4 | class Solution:
"""
Desc: 找出有序数组中绝对值最小的值
eg1: [-10, -7, -4, -2, 0, 7, 9]
eg2: [-8, -3, -1, 2, 3, 5, 9, 10, 11] len: 9
eg3: [-8, -3, 0, 2, 3, 5, 9, 10]
"""
def minAbs_traversing(self, nums: list) -> int:
""" 遍历法 """
return 0
def minAbs_dichotomy(self, nums: list) -> i... |
25a105bf966f103e7d2dc665dcd0ea4141cd4b77 | Deaseyy/algorithm | /链表/链表操作-单链表反转.py | 2,602 | 3.71875 | 4 | from PyVbord.apps.AAAtest.APy.链表.common import get_linked_list, read_linked_list, ListNode
class Solution:
def __init__(self):
self.successor = None
def reverse_recursive(self, head: ListNode) -> ListNode:
""" 递归法
反转单链表
:param head: 反转前的头节点
:return: 反转后的头节点
"""... |
cf976505943b1358e7aa2ba2af71cd7d937be009 | Deaseyy/algorithm | /BFS-DFS/leetcolde542_01矩阵.py | 970 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
@Author: wangzhongmin
@Date: 2021/3/23
@Desc:
给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:
[[0,0,0],
[0,1,0],
[0,0,0]]
输出:
[[0,0,0],
[0,1,0],
[0,0,0]]
示例 2:
输入:
[[0,0,0],
[0,1,0],
[1,1,1]]
输出:
[[0,0,0],
[0,1,0],
[1,2,1]]
提示:
给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩... |
acac21039b66a8beceab5dfc2d05c380827572e6 | hoggmania/emscripten | /tools/python_selector.py | 1,338 | 3.5 | 4 | '''
Provides a way to run a script on the preferred Python version
'''
import os
import sys
'''
Imports the target script by filename and calls run()
'''
def run_by_import(filename, main):
import importlib
return getattr(importlib.import_module(os.path.basename(filename)), main)()
'''
Opens Python 2 subprocess t... |
8d7da5a9325b59e2fe4d7e43d44e76abd4ae0294 | g-quest/machine_learning_3 | /perceptron_learning.py | 2,041 | 3.953125 | 4 | # written in Python 3
import sys
import csv
def main():
# check that proper arguments were entered in command line
if len(sys.argv) != 3:
print('ERROR: two arguments required')
print('usage: python3 perceptron_learning.py perceptron_learning_input.csv <output_csv>')
sys.exit()
... |
b75fb74359df69e6ebb383c9ec3f72c3615b58c7 | iodbh/adventofcode | /aoc/Y2019/D10/solutions.py | 3,469 | 3.53125 | 4 | from ...classes import Solution
from collections import namedtuple
from itertools import combinations
Point = namedtuple("Point", "x y")
class AsteroidsMap:
GRID_SCALE_FACTOR = 21
GRID_SCALE_OFFSET = (GRID_SCALE_FACTOR - 1) // 2
def __init__(self, data):
self.data = data
self.asteroid... |
d6e7c99158b58f3497da841fbb0ed8c6039383c2 | iodbh/adventofcode | /aoc/Y2017/D13/solutions.py | 736 | 3.515625 | 4 | """
This solution is from https://www.reddit.com/r/adventofcode/comments/7jgyrt/2017_day_13_solutions/
"""
from ...classes import Solution
import itertools
def parse_input(data):
return {int(pos): int(height) for pos, height in (line.split(': ') for line in data)}
def scanner(height, time):
offset = time %... |
7fbcc12c175eb5460efc654123eeb05288eb810d | athenian-ct-projects/Robinson-Crusoe-Day-IR | /Robinson-Crusoe-Day-IR.py | 10,968 | 4.125 | 4 | import time
#defining load function
def threeTwoOne():
load=3
for x in range(3):
print(load)
time.sleep(1)
load-=1
def waitThree():
time.sleep(3)
print("Hello player! Welcome to the choose your own adventure of Robinson Crusoe day!")
print("Here are the rules:")
print("Words will appear on the... |
68e1bdacf6b561e3492299d8a2f7b1afcba6f1f1 | Wwaahhyyuu/Algo- | /tugas2.py | 600 | 3.859375 | 4 | masukkan_kata = input("Enter a Setence: ")
jadikan_list = masukkan_kata.split()
hitung_kata = len(jadikan_list)
huruf_besar = 0
huruf_kecil= 0
jumlah_angka= 0
for kar in masukkan_kata :
if kar.isupper():
huruf_besar += 1
if kar.islower():
huruf_kecil += 1
if kar.isdecimal():
... |
1844197942a8f5f0742f03516056963099329175 | fresko678/security | /RSA.py | 3,367 | 4.21875 | 4 | import random
from collections import namedtuple
def get_primes(start, stop):
if start >= stop:
return []
primes = [2]
for n in range(3, stop + 1, 2):
for p in primes:
if n % p == 0:
break
else:
primes.append(n)
while primes and primes... |
d2a50d3ae89854c39e800e5e935fcfabb51831cb | anupamdialpad/khichdi | /decorators.py | 990 | 3.6875 | 4 | # import functools
# Python class decorator with arguments
class SimpleRetry: # class: name of the decorator
def __init__(self, tries=0): # tries: arguments of the decorator
# functools.update_wrapper(self, func) # dont' know why functools is required
self.func = None # func: function which is decor... |
54834f8a7ab237efa8a2dbc6d740974112411f22 | qamarilyas/LeetCode | /2Sum.py | 665 | 3.625 | 4 | '''
def twosum(nums,target):
# Brute Force
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j
return False
lst = [2, 7, 9, 11]
print(twosum(lst, 19))
'''
###Better Solution###
## On each index save the target-val and index in ... |
b78040ed148801f0cbe3c0664ce845fd3db84c96 | dparito/LeetCode_HackerRank_Practice | /LC_linkedListCycle.py | 653 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
pass
if __name__ == "__main__":
mysol = Solution()
linked_list_val = [3, 2, 0, -4]
link... |
bbb619f3551e37172f76cc15ccd576895b82ecb5 | dparito/LeetCode_HackerRank_Practice | /HR_countingValleys.py | 650 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
num_valleys = 0
trajectory = 0
for direction in s:
if direction == 'U':
trajectory += 1
else:
if traje... |
7b3ce07462d404b952ca7f243d91b25cc7822469 | D4N00/jozefbot | /motor_control_pwm.py | 1,725 | 3.5625 | 4 | from machine import PWM, Pin
class Motor:
def __init__(self, pin_forward, pin_backward):
self.forward_pin = PWM(Pin(pin_forward))
self.backward_pin = PWM(Pin(pin_backward))
pass
#can input speed in percents from -100 to 100 or input_tipe=1 then in u16 from -65000 to 65000
def mot... |
79557c701b3f3d439b1d05f5f0f89467c42c7207 | AndrewFendrich/Mandelbrot | /Gulliver3000/mandelPixel.py | 1,281 | 3.515625 | 4 | """
mandelbrot pixel class
"""
#import math
class grid():
def __init__(self,CoordTL,CoordBR,HSize,VSize):
self.CoordTL = CoordTL
self.CoordBR = CoordBR
self.HSize = HSize
self.VSize = VSize
xa = self.CoordTL.real
xb = self.CoordBR.real
ya = self.CoordTL.ima... |
5a0c7efb081b9ef535ac2707bf838b9df171ba3a | Giruvagen/TextAdv | /Character.py | 1,764 | 3.84375 | 4 | #Init character with initial values
import random
import time
import Moves
class Character(object):
def __init__(self,name):
self.name = name
def startGame(self):
print("Let the games begin!")
exec(self.name + ' = Moves.motion(self.name)')
def startRoll(self):
print("Please se... |
27c43829d72a2e43b5ca4f1d6d54031bfdd10138 | axayjha/algorithms | /diagonal_traverse.py | 886 | 4.21875 | 4 | """
https://leetcode.com/problems/diagonal-traverse/
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal
order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total... |
46d23ad06c0751a5112a972aad8518aa4aff8d12 | axayjha/algorithms | /linked_list/2_1_remove_dups.py | 1,377 | 3.734375 | 4 | """
Q2.1: Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve the problem if a temporary buffer is not allowed?
"""
class Node:
def __init__(self, val):
self.val = val
self.next = None
def display(head):
temp = head
whil... |
487c4c14d50c7a81a5ff0069db7204880fe10a3a | axayjha/algorithms | /hamming_distance.py | 325 | 3.765625 | 4 | """
https://leetcode.com/problems/hamming-distance/
"""
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
cnt = 0
for i in range(32):
cnt += (x&1) ^ (y&1)
x = x>>1
y = y>>1
return cnt
... |
d754d7c77c75e67170be0be7a018b4a58a2d8404 | chrahum/CIS30A-Python-Fundamentals-Final-Project | /Final Project/app.py | 6,709 | 3.78125 | 4 | '''Program that asks users what day and time they want
their doctors appointment set'''
import stringsVar as main #imports functions module
import classesModule as classes #imports classes module
from tkinter import * #lets us use a GUI
from tkinter import messagebox #imports the message box
fro... |
edff4979701065d3a63aa5b1c7312a8389989d0b | shaduk/MOOCs | /UdacityCS101/app/days.py | 1,144 | 4.34375 | 4 | def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < 30:
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def daysBetweenDates(year1, month1, day1... |
2aa27e73539e9ef7766fcf5ee480679d7b4fe2e2 | shaduk/MOOCs | /edx-CS101/myLog.py | 1,063 | 4.375 | 4 | '''Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b. For example, if x = 16 and b = 2, then the result is 4 - because 24=16. If x = 15 and b = 3, then the result is 2 - because 32 is the largest power of 3 less than 15.
In other words, myLog should return the larges... |
78e68b6ce0e1f1bfc02192ec6ad369c10cb2cfdb | oshou/procon | /AC/ABC/ABC111A.py | 151 | 3.734375 | 4 | N = str(input())
ans = ""
for n in N:
if n == "1":
ans += "9"
elif n == "9":
ans += "1"
else:
ans += n
print(ans)
|
311b68353045a0ca3878a58ef109ec2579b00e84 | oshou/procon | /AC/ABS/ABC049C.py | 342 | 3.71875 | 4 | S = str(input())
given = ['dream', 'dreamer', 'erase', 'eraser']
while len(S) > 0:
judge = [S.endswith(i) for i in given]
if any(judge):
target = given[judge.index(True)]
S = S[:-len(target)]
if len(S) == 0:
print("Yes")
break
else:
print(... |
afd7e7f9060e1a1bf1c3064a10d0c18385426a36 | oshou/procon | /AC/ABC-TDD/126/b.py | 298 | 3.53125 | 4 | s = input()
s1i = int(s[0:2])
s2i = int(s[2:4])
isYYMM = False
isMMYY = False
if 1 <= s1i and s1i <= 12:
isMMYY = True
if 1 <= s2i and s2i <= 12:
isYYMM = True
if isYYMM and isMMYY:
print("AMBIGUOUS")
elif isYYMM:
print("YYMM")
elif isMMYY:
print("MMYY")
else:
print("NA")
|
2a5a788ef6e1797087dc381d532ef8fdc1a532e9 | oshou/procon | /AC/ACL/acl001c.py | 955 | 3.75 | 4 | class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1]*n
for i in range(n):
self.parents[i] = i
# 要素xが所属するグループの根を返す
def root(self, x) -> int:
if self.parents[x] == x:
return x
else:
self.parents[x] = self.root(sel... |
08323bc56515dee2fd71cc9b39e60197da5cffe5 | oshou/procon | /AC/ABC/ABC109B_kuso.py | 262 | 3.53125 | 4 | N = int(input())
ans = "Yes"
arr = []
for i in range(N):
arr.append(input())
if not i == 0:
if arr[i-1][-1] == arr[i][0] and not arr[i] in arr[:-2]:
pass
else:
ans = "No"
break
print(ans)
|
3fe4a9e97420c4e012d1fc40e36da81230d81014 | Intro-Course-AI-ML/Youyi-Ding | /Task 1.py | 382 | 4 | 4 | n = int(input("Please put in a positive number: "))
def number(n):
counter = 0
for i in range (1, n + 1):
result = getPowerOfTen(i)
print(i, result)
counter += result
return counter
def getPowerOfTen(n):
number = 0
while n > 0:
n = int(n / 10)
... |
55f2ed22948b375c40b45ffef78b509122a4effd | sashokbg/python-exercises | /coordinate_system/turtle_drawer.py | 1,620 | 3.828125 | 4 | import turtle
from drawer import Drawer
class TurtleDrawer(Drawer):
scale = 40
def __init__(self):
Drawer.__init__(self)
turtle.speed(10)
def draw(self):
turtle.home()
turtle.clear()
for vector in self.system.vectors:
print(vector.is_primary)
... |
60e15158f325425c2e78a9674e92388f7aecfe24 | sashokbg/python-exercises | /bubbleSort/bubble-sort.py | 587 | 3.875 | 4 | from randomArray.randomArray import RandomArray
from tools.swap import swap
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("numberOfElements", type=int, help="The number of random elements to generate")
args= parser.parse_args()
numbers = RandomArray(args.numberOfElements)
print(numbers)
is... |
e1b9ba8875c43b15ba0e68c7f9e1d4842af94de8 | sashokbg/python-exercises | /fibonacci/fibonacci.py | 516 | 4.125 | 4 | import argparse
def main():
args, number = parseArgs()
fibonacci(number)
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument('number', help='Calculate the fibonacci sequence to the n-th element', type = int)
args = parser.parse_args()
return args, args.number
def fibonacci... |
cb40ed620bd5328df526f9b958f762b63bc12671 | sashokbg/python-exercises | /partitionArray/tests/partitionArrayTest.py | 2,175 | 3.78125 | 4 | import unittest
from partitionArray import *
from randomArray.randomArray import RandomArray
class PartitionArrayTest(unittest.TestCase):
def checkArray(self, arr, pivot):
pivotValue = arr[pivot]
for i in range(0, pivot):
if(arr[i] > pivotValue):
self.fail('There are va... |
72eefbfe269d33ad570ddd46bbde8c0567196077 | MarionMcG/Python-Project-2018 | /hist.py | 2,357 | 3.515625 | 4 | #Marion McGowan, 18/04/2017
#Distribution of four data sets: Sepal Length, Sepal Width, Petal Length and Petal Width
import numpy as np
import matplotlib.pyplot as pl
data = np.genfromtxt('data/iris-data.csv', delimiter=',')
firstcol = data[:,0]
seccol = data[:,1]
thirdcol= data[:,2]
fourcol= data[:,3]
#Graphing e... |
b710dbe4d4e1e5a10c2af43d7b08bb70cf0912a9 | ebuitragod/ZINOBE | /database.py | 830 | 3.859375 | 4 | import sqlite3
from sqlite3 import Error
def sql_connection():
try:
con = sqlite3.connect('test.db')
print("Connection is established")
except Error:
print(Error)
return con
def create_country_table(con):
cursorObj = con.cursor()
try:
cursorObj.execute("CREATE ... |
1750285b28bdad1b234b5c63616eba924266fbfb | MaggieYear/PyProject | /utilspack/regex_utils.py | 2,758 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'mocha_kiki'
import re
def re_demo():
# 解析价格
txt = 'If you purchase more than 100 sets,the price of product A is $9.90.'
# 解析数量和价格:
m = re.search(r'(\d+).*\$(\d+\.?\d*)', txt)
print(m.groups())
# re匹配方法使用示例
def re_method():
# search vs... |
fc942141f0ef5e466523559061508ba5e23c898e | MaggieYear/PyProject | /oopack/simple_duck.py | 679 | 3.71875 | 4 | #!/usr/bin/env python
#coding:utf-8
class A:
def foo(self):
print "duck A"
class B(A):
def foo(self):
print "duck B"
class C(A):
def foo(self):
print "duck C"
class D(A):
pass
class E:
def foo(self):
print "like a duck"
def test(obj):
obj.foo()
a = A()
b =... |
360af9f306a042355ac9a639c7fe903983b72ee7 | MaggieYear/PyProject | /design_pattern/observer_demo.py | 1,421 | 3.515625 | 4 | #!/usr/bin/env python
#coding:utf-8
# observer pattern
class subject():
def __init__(self, dat):
self.listobj = list() # 主题中的列表变量用来存储观察者
self.dat = dat # 主题中的数据变化时,需要通知观察者
def registerObject(self, obj):
self.listobj.append(obj) # 实现订阅主题的函数
def removeObject(self, obj):
... |
69e0dd90a8cb90dab50b81eb9949364244187e45 | Luncode/Python-Learn | /dict.py | 489 | 4.40625 | 4 | print('学习:Python-dict')
#定义字典列表
d = {'Bob':95,'Lisa':96,'Luncode':100}
#修改key的值
d['Bob'] = 99
#检查key是否在列表中
print('Lisa' in d)
#输出对应key的value
print(d['Bob'])
#删除列表中的key和value
d.pop('Lisa')
#输出列表
print(d)
#小结
d = {'Michael': 95,'Bob': 75,'Tracy': 85}
print('d[\'Michael\'] =', d['Michael'])
print('d[\'Bob\'] =', d['Bob'... |
dd791a15d8834eb7841ba3007b7c59d5034cab39 | Luncode/Python-Learn | /if.py | 793 | 4.0625 | 4 | #定义height的输入
height = input('输入身高,如1.50m:')
#定义weight的输入
weight = input('输入体重,如50kg:')
#定义age的输入
age = input('你的年龄:')
#定义name的输入
name = input('输入你的名字:')
#定义height为float类型
height = float(height)
#定义weight为float类型
weight = float(weight)
#定义age为int类型
age = int(age)
bmi = weight/(height*2)
bmi = int(bmi)
#输出
print('你的名字:',... |
41411ad71ab27f75e0771dbadac75de58b9bb3dc | sol83/python-simple_programs_7 | /Lists/get_first.py | 467 | 4.34375 | 4 | """
Get first element
Fill out the function get_first_element(lst) which takes in a list lst as a parameter and prints the first element in the list. The list is guaranteed to be non-empty.
You can change the items in the SAMPLE_LIST list to test your code!
"""
SAMPLE_LIST = [1, 2, 3, 'a', 'b', 'c']
def get_first_e... |
0bed91b6da6b75ca360119fe10bd8c6507c16080 | patricia-faustino/AprofundandoEmPython | /manipulandoStrings02.py | 676 | 4.125 | 4 | #TUDO EM MAIÚSCULO
print("acarajé com camarão".upper())
#tudo em minúsculo
print("acarajé com camarão".lower())
#Inicial maiúscula
print("acarajé com camarão".capitalize())
#Quantas vezes o parametro aparece, count(parametro)
print("acarajé com camarão".count("é"))
#Troca um item por outro, replace(old, new)
p... |
8c523d7be14a7ae369d204d5885cf3a293bb9a00 | patricia-faustino/AprofundandoEmPython | /if01.py | 120 | 3.65625 | 4 | velocidade = float(input("Informe a velocidade: "))
if(velocidade > 70):
print("Você será multado")
print("FIM") |
a43dd38f65da37082923954573c1494d8fdd1265 | Averiandith/fit2004-pass | /Floyd_Warshall/Floyd_Warshall.py | 859 | 3.734375 | 4 | import math
def floyd_warshall(list_vertices: list, list_edges: list) -> list:
"""
Psuedocode for Floyd Warshall algorithm
"""
inf = math.inf
# Create distance array
num_vertices = len(list_vertices)
dist_arr = [[inf for i in range(num_vertices)] for j in range(num_vertices)]
for v i... |
8a6bdc4171286a320dd4b4847082ce7c2a989556 | supersayavic/astar_kbs | /intro.py | 8,474 | 3.625 | 4 | import csv
import argparse
# globale Variablen
fieldType = []
costs = []
# creates the field
# file is the input file that the user provides
def fieldcreation(file):
return list(list(item for item in line.rstrip("\n\r").split(";")) for line in file)
# node class
class Node():
"""A node class for A* Pathfind... |
4c6d92f4bd1dc500db6bc5952421923675f1b05a | tjeaneric/A-simple-flight-system | /ATM.py | 1,319 | 3.75 | 4 | from datetime import datetime
from auth import *
name = input("what is your name?\n")
allowedUsers = ['Seyi', 'Mike', 'Love']
allowedPassword = ['passwordSeyi', 'passwordMike', 'passwordLove']
if (name in allowedUsers):
password = input("your password? \n")
userId = allowedUsers.index(name)
if(password =... |
5298e43d2497174ebf8477e9adede2f9c008fc67 | TSG405/SOLO_LEARN | /PYTHON-3 (CORE)/Fibonacci.py | 659 | 4.21875 | 4 | '''
@Coded by TSG, 2021
Problem:
The Fibonacci sequence is one of the most famous formulas in mathematics.
Each number in the sequence is the sum of the two numbers that precede it.
For example, here is the Fibonacci sequence for 10 numbers, starting from 0: 0,1,1,2,3,5,8,13,21,34.
Write a program to take N (variab... |
6dd541d14a70d5d0654da10db9074c0999507725 | kumarritik87/Python-Codes | /factorial.py | 217 | 4.21875 | 4 | #program to find factorial of given number using while loop:-
n = int(input("Enter the no to find factorial\n"))
temp = n
f = 1
while(temp>0):
f = f*temp
temp = temp-1
print('factorial of ',n,'is', f)
|
7b55e3cd2f0d045fa07bf42bfeaadb09b50cc87d | luowensheng/RL_Temporal-Difference-Learning | /utils.py | 920 | 3.953125 | 4 | """
Description:
Some helper functions are implemented here.
You can implement your own plotting function if you want to show extra results :).
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def plot(sum_reward, label,ylabel):
"""
Function to plot the results.
Inpu... |
d56ff68d5bdb85f5c8d354f91ce5a2d147879471 | memory90915yoyo/myNote | /lang/ds/leecode/86-partition-list.py | 1,541 | 4 | 4 | """
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
"""
# Definition for s... |
eaa8ad18e751fff2bcfe3ee40e38686fe0de4291 | waldo7/sql | /sqlf.py | 393 | 3.8125 | 4 | import sqlite3
with sqlite3.connect("new.db") as conn:
cur = conn.cursor()
cur.execute("""UPDATE population SET population = 4000000 WHERE city = "New York City" """)
cur.execute("""DELETE FROM population WHERE city="Boston" """)
print("\nNEW DATA: \n")
cur.execute("SELECT * FROM population")
... |
ce700ea57b761bdf9cffd998a02054a604fa0b66 | waldo7/sql | /sql-joins cleanup.py | 494 | 4.03125 | 4 | import sqlite3
with sqlite3.connect("new.db") as conn:
cur = conn.cursor()
cur.execute("""SELECT DISTINCT population.city, population.population, regions.region
FROM population, regions
WHERE population.city = regions.city
ORDER BY population.city ASC... |
8d4823bd2a2185888f0c82264846e7318e2eeb05 | markdegroat/euler_problems_in_python | /eulerProblem11.py | 13,990 | 3.625 | 4 | __author__ = 'Hal'
Matrix = {} #using dict as matrix
consecutive_numbers = 4
with open("number_array.txt") as file:
first_line = file.readline()
file.seek(0)
y_count = sum(1 for line in file)
x_count = first_line.count(' ') + 1
file.seek(0)
list_of_lists = []
for i in range(0, y_co... |
fedddf7cf98697a20c3554171377e9057d2b48bf | moshekaplan/matasano_crypto_challenge | /set1/Matasano_05.py | 1,251 | 3.859375 | 4 | #!/usr/bin/env python
"""5. Repeating-key XOR Cipher
Write the code to encrypt the string:
Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal
Under the key "ICE", using repeating-key XOR. It should come out to:
0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a2622632427276527... |
6fb5b5f5e10673c061144cdc1679310fb9ac4b7a | nikolata/LeetCodeTasks | /reverse_integer.py | 545 | 3.703125 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = str(x)
is_negative = False
if x.count('-') == 1:
is_negative = True
x = x.replace('-', '')
x = x[::-1]
if len(x) != 1:
while ... |
de6c458f37b0512d53d4f87baa84115af4cc235c | infinitumodu/CPU-temps | /tableMaker.py | 1,787 | 4.21875 | 4 | #! /usr/bin/env python3
def makeXtable(data):
"""
Notes:
This function takes the data set and returns a list of times
Args:
data: a list with each element containing a time and a list of the core tempatures at that time
Yields:
a list of times
"""
xTable = []
... |
a62faad5d6830320f5a4ee8cd0053595ff30120e | Jebadeiah/coffee_machine | /Coffee Machine/Problems/Right triangle/main.py | 469 | 3.609375 | 4 | class RightTriangle:
def __init__(self, hyp, leg_1, leg_2):
self.c = hyp
self.a = leg_1
self.b = leg_2
self.t_area = .5 * leg_1 * leg_2
def print_info(self):
print(self.t_area)
input_c, input_a, input_b = [int(x) for x in input().split()]
if not input_c * input_c == i... |
56ca6177c714916b0dc757fe8fe774e5f1b441c9 | 9R/pgpy | /adduser.py | 823 | 3.53125 | 4 | from werkzeug import generate_password_hash
import getpass
from sys import exit
userfile = 'users.txt'
username = raw_input('Enter username:')
f = open(userfile, "a+")
for line in f.readlines():
if line.split(' ')[0] == username:
f.close()
exit( 'Username already exists')
pw1= getpass.getpass('Enter passw... |
f5bccf5c3b76298ff177097713e1c29dcc3db3dd | nam11993/Nam-C4E28-Fundamentals | /session 5/freaking_math.py | 754 | 3.8125 | 4 | from random import randint
from random import choice
# from calc import eval
import calc
while True:
x = randint(0,10)
y = randint(0,10)
op = choice(["+","-","*","/"])
errors = randint(-1,1)
real_result = calc.eval(x, y, op)
display_result = errors + real_result
... |
c061d93b0ce389511a9f803ecb5ada86f0b9a3bc | nam11993/Nam-C4E28-Fundamentals | /Homework_ss3/exercise3.py | 1,306 | 3.796875 | 4 | #3.a
import random
# char = ["c","h","a","m","p","i","o","n"]
# i = random.shuffle(char)
# word = "champion"
# print(*char)
# while True:
# g = input("Your answer: ")
# if g != word:
# print(":(")
# else:
# print("Hura")
# break
#3.b
list1 = ["m","e","t","i","c","u","... |
46311338ba945909430099a999ee9a0276aeae92 | nam11993/Nam-C4E28-Fundamentals | /Nam/Homework_ss3/turtle_exercise_1.py | 413 | 3.921875 | 4 | from turtle import *
color("red")
for i in range(3):
left(120)
forward(100)
color("brown")
for j in range(4):
left(72)
forward(100)
color("yellow")
left(72)
forward(100)
for a in range(5):
left(60)
forward(100)
left(150)
color("blue")
for b in range(3):
forward(100)
... |
541eb7c921b7e90a7881e80f908b7ac0e5ec5091 | nam11993/Nam-C4E28-Fundamentals | /Homework_ss3/exercise_1.py | 752 | 3.875 | 4 | quanao = ["T_Shirt", "Sweater"]
while True:
R = input("Welcome to our Shop, what do you want (C, R, U, D)? ")
if R == "R":
print("Our items: ", end="")
print(*quanao, sep=", ")
elif R == "C":
creat = input("New item? ")
quanao.append(creat)
print("Our it... |
f9e7b9f34a6456884c149fca05ae63188b08ac7e | EliseevaIN/python_lesson_3 | /text_L3.py | 1,584 | 4.1875 | 4 | #Считать текст из файла и выполнить последовательность действий:
print('1) методами строк очистить текст от знаков препинания;')
print()
f = open('text.txt', encoding='utf-8')
text = f.read()
str = text
symbol_list = [' ','.',',','?','!','-','–','—',"'",'"','«','»',':',';','(',')','\n']
for a in range(len(symbol_list... |
b784cd158787ce5c0cd90cc269672383e3a7ffc6 | corvus-rex/OFSE_OOPConcepts | /encapsulation_by_convention.py | 642 | 4.03125 | 4 | class Person:
def __init__(self):
self.first_name = 'Adrian' # this is a public attribute
self.__last_name = 'Riadi' # this is a private attribute
def printname(self): # public method
return self.first_name + " " + self.__last_name
def __greetings(self):
return "Hel... |
d57182b2410b49d9e3ae2b763a91e11dd92877df | projeto-de-algoritmos/Grafos1_Labirintite | /maze_generator.py | 1,753 | 3.625 | 4 | import random
import pygame
from Constantes import size, cols, rows, width, GREY
from Cell import Cell, removeWalls
import Theme
def generate():
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Maze Generator")
done = False
clock = pygame.time.Cl... |
f572c38ad5055371dc32b1adf5c59f2941ee15b3 | biwenKey/Python_study01 | /list/转换list.py | 257 | 3.546875 | 4 | s1 = "李露"
li = list(s1)
print(li)
t2 = ("jinbiwen01","jinbiwen02","jinbiwen03")
l2 = list(t2)
print(l2)
t3 = {"k1":"alex",
"k2":"seven"
}
#l3 = list(t3)
#print(l3)
l3 = list(dict.values(t3))
print(l3)
l4 = list(dict.items(t3))
print(l4)
|
b43daa8e2ef7063752e72e0f9911d8d3b903a53d | biwenKey/Python_study01 | /函数学习/函数普通参数/函数的动态参数.py | 534 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
""""
def f1(**a):
print(a,type(a))
f1(k1=123,k2=456)
def f1(*a, **aa):
print(a,type(a))
print(aa,type(aa))
f1(11,22,33, k1=123, k2=456)
def f1(p, *a, **aa):
print(p,type(p))
print(a, type(a))
print(aa,type(aa))
f1(11,22,33,k1=123,k2=345)
def f1... |
d47ae271199c81cac5b6501e2466cb0a631b58a0 | biwenKey/Python_study01 | /模块/字符串格式化/format格式化/format01.py | 525 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
tp01 = "i am {}, age {}, {}".format("seven", 18, 'alex')
print(tp01)
tp02 = "i am {}, age {}, {}".format(*["seven",18,'alex'])
print(tp02)
tp03 = "i am {0}, age {1}, really {0}".format("seven", 18, "hehe")
print(tp03)
tp04 = "i am {0}, age {1}, really {0}".format(*["seven", ... |
007a0ba3ce9485ebe01ac9772357afecb200220e | biwenKey/Python_study01 | /python课后作业01/三级联动04.py | 1,003 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
dic = {
"河北":{
"石家庄":["鹿泉","藁城", "元氏"],
"邯郸": ["永年", "涉县", "磁县"],
},
"河南": {
"郑州": ["中原", "金水", "惠济"],
"开封": ["龙亭", "鼓楼", "顺河回族"],
},
"山西": {
"太原": ["小店", "晋源", "尖草坪"],
"运城": ["盐氏", "盐邑", "苦城"],
},
}... |
822ce5d15879dc71f60f05b888770b71aabfe1c1 | biwenKey/Python_study01 | /函数学习/函数作业02.py | 517 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def fun01(p):
num = 0
letter = 0
space = 0
qita = 0
for i in p:
if i.isdigit():
num += 1
elif i.isalpha():
letter += 1
elif i.isspace():
space += 1
... |
cfe6477f9f845360f1e7eb7e24963e13a4046912 | kszhao552/Linear-Regression | /LinearRegression/regression.py | 2,136 | 3.859375 | 4 | from vector import Vector
class Regression(object):
def __init__(self, size):
#initalization of the class with most of the variables set to 0
self.size = size
self.SSxx = 0
self.SSxy = 0
self.SSyy = 0
self.bhat0 = 0
self.bhat1 =0
self.SSE =0
se... |
76b323412e8931a5ecf982e60c76d4378d6cbbf7 | jack-alexander-ie/data-structures-algos | /Projects/Project_3/problem_3.py | 4,143 | 4.34375 | 4 | from typing import List
def test_list(list_ints: List[int]) -> bool:
""" Checks all elements in a list to ensure they're all integers """
for element in list_ints: # O(n) traversal afforded -> will not add significantly to time complexity
if type(element) is not int:
print('Warnin... |
d8275b0bbc9be8dbf86bd2657ab2a7c4e3768c02 | jack-alexander-ie/data-structures-algos | /Topics/3. Basic Algorithms/1. Basic Algorithms/binary_search_first_last_indexes.py | 2,635 | 4.125 | 4 | def recursive_binary_search(target, source, left=0):
if len(source) == 0:
return None
center = (len(source)-1) // 2
if source[center] == target:
return center + left
elif source[center] < target:
return recursive_binary_search(target, source[center+1:], left+center+1)
el... |
9f669d3fed3e65a0bda3030b5da74f47fb4b594a | jack-alexander-ie/data-structures-algos | /Topics/2. Data Structures/Recursion/recursion_string_reverse.py | 235 | 4.0625 | 4 | def reverse_string(input):
# Base Case - when string is empty
if len(input) == 0:
return ""
# Recursive Case - last char + input char
return reverse_string(input[1:]) + input[0]
print(reverse_string('cba'))
|
0979d7715494d42c76a0118f9ca312a8b7a191cb | jack-alexander-ie/data-structures-algos | /Topics/2. Data Structures/Maps_and_Hashing/string_key_hash_table.py | 1,588 | 3.859375 | 4 | """Write a HashTable class that stores strings
in a hash table, where keys are calculated
using the first two letters of the string."""
class HashTable(object):
def __init__(self):
self.table = [None]*10000
def store(self, string):
"""TODO: Input a string that's stored in the table."""
... |
d2fdddb9967037869d65f92edf0a93c4a1717c6f | jack-alexander-ie/data-structures-algos | /Topics/2. Data Structures/Recursion/recursion.py | 2,728 | 4.6875 | 5 |
def sum_integers(n):
"""
Each function waits on the function it called to complete.
e.g. sum_integers(5)
The function sum_integers(1) will return 1, then feedback:
sum_integers(2) returns 2 + 1
sum_integers(3) returns 3 + 3
sum_integers(4) returns 4 ... |
7f313355033e08c8418d41e7745f56b58fd912f5 | jack-alexander-ie/data-structures-algos | /Topics/2. Data Structures/Trees/tree_traversal_dfs_recursive.py | 2,519 | 4.0625 | 4 | class Node:
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
def set_left_child(self, left):
self.left = left
def set_right_... |
db8370904ede603abb3a259f59bd038179693095 | mfislam007/Machine_Learning_RaspPi | /Load_Display_Save.py | 389 | 3.625 | 4 | # Load, Display and Save Images
# Import Computer Vision package - cv2
import cv2
# Read the image using imread built-in function
image = cv2.imread('image_1.jpg')
# Display original image using imshow built-in function
cv2.imshow("Original", image)
# Wait until any key is pressed
cv2.waitKey(0)
# Save the image u... |
d2d22be6a271a9a04140e78a57a5e3a171ea88aa | MonteYang/do_leetcode | /code/69.x-的平方根.py | 1,258 | 3.75 | 4 | #
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#
# https://leetcode-cn.com/problems/sqrtx/description/
#
# algorithms
# Easy (37.33%)
# Likes: 292
# Dislikes: 0
# Total Accepted: 88.1K
# Total Submissions: 235.3K
# Testcase Example: '4'
#
# 实现 int sqrt(int x) 函数。
#
# 计算并返回 x 的平方根,其中 x 是非负整数。
#
# 由于... |
8e251926aa0e592e3753e6d37b8ecfc4df8c8a76 | ProBuiltTech/python-projects | /electionCorrect.py | 1,450 | 3.953125 | 4 | students= {
'PYTHON20201':0,
'PYTHON20202':0,
'PYTHON20203':0,
'PYTHON20204':0,
'PYTHON20205':0,
'PYTHON20206':0,
'PYTHON20207':0,
'PYTHON20208':0,
'ADMIN2020':0
}
candidates= {
'MARYAM':0,
'VICTOR':0
}
maryam= candidates['MARYAM']
victor= candidates['VICTOR']
election_time =... |
0c9552a425c4993ca62f59ae78a245a6b30ae725 | msampathkumar/PythonInterviewPrep | /CrackTheCodingInterview/first.py | 2,927 | 3.8125 | 4 |
def first_question(string):
"""Implement an algorithm to determine if a string has all unique characters What if you can not use additional data structures?
"""
hash = dict()
flag = True
for s in string:
if s not in hash:
hash[s] = True
else:
flag = False
... |
908ce76a9a66d84a37cedb0375ef9d6d58675922 | Park-Jongil/Python_M15 | /FindList.py | 1,175 | 3.65625 | 4 | import sqlite3
from sqlite3 import Error
def Search_by_key(conn, key):
try :
cur = conn.cursor()
cur.execute("select * from CameraList where seq=?",(int(key),) )
rows = cur.fetchall()
if (rows==None) : return None
for row in rows : print( row )
except :
... |
92d1e98c5ee646d5d8e9811c609af686208cb983 | abhijitmk/Rock-paper-scissors-spock-lizard-game | /rock paper scissors spock lizard game.py | 2,191 | 4.1875 | 4 | # Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
# helper functions
def name_to_number(name):
if(name==... |
90fbf0c1464d82ef7aa640602beb647e09aaa7d6 | darcamo/python-crash-course | /code/estruturas_de_repeticao_em_python.py | 548 | 3.90625 | 4 |
# sample(for)
palavras = ['gato', 'janela', 'paralelepípedo']
for palavra in palavras:
print (palavra.upper())
# end-sample
# sample(range)
range(5, 10) # 5, 6, 7, 8, 9
range(0, 10, 3) # 0, 3, 6, 9
range(-10, -100, -30) # -10, -40, -70
range(-10, -101, -30) # -10, -40, -70 -100
# end-sample
# samp... |
7904febc4341aa06bb4beeefcaad7dc856296da9 | codpro880/project_euler | /python/problem_9.py | 836 | 4.40625 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import math
def main():
for possible_triple in generate_possible_tripl... |
269a643b2107d2ba2d42943116cb3a56ea133971 | PionDas/reviewPython | /Test2/Course.py | 520 | 3.734375 | 4 | from Student import Student
class Course(Student):
def __init__(self, name, max_students):
self.name = name
self.max_students = max_students
self.students = []
def add_student(self, student):
if len(self.students) < self.max_students:
self.students.append(student)
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.