blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
86c5a1ebea057032290a4bdc32cb4cf60f129c9d | rainfd/leetcode | /python/206.Reverse_Linked_List/link.py | 340 | 3.609375 | 4 | class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
h = ListNode(None)
while head is not None:
node = ListNode(head.val)
node.next = h.next
h.next = node
head = head.next
... |
3d19bb785f3404c120ece04510fed31ef9ef3249 | saranshqm/rosalind | /python-village/ini3.py | 376 | 3.546875 | 4 | def two_inclusive_slices (str, begin1, end1, begin2, end2):
return str[begin1:end1+1] + ' ' + str[begin2:end2+1]
teststr = 'HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.'
print two_inclusive_slices(teststr, 22, 27, 97, 102)
teststr2 = 'CfolD0... |
a618a57898126ae00f8f38eb562b41f23400bb61 | limgeonho/algorithm_study | /2021.07.23/BOJ_4659.py | 1,376 | 3.734375 | 4 | # 비밀번호 발음하기(실5)
# 모음을 체크할 수 있는 함수 만들기
# 글자를 하나씩 받아서 모음 누적수, 모음일 경우 횟수를 누적하기
# 입력받은 현재 글자를 tmp에 저장하고 다음에 나오는 글자와 비교해서 같으면 False
# 최종적으로 check의 T/F에 따라 결과 출력하기
def check_vowel(letter):
vowel = 'aeiou'
if letter in vowel:
return True
else:
return False
while True:
password = input()
... |
4f2b3fc3365bfb08651e8863f31c447d0e8fb5d2 | nakov/Python-Course-SoftUni | /OurTasks/03/07/07.py | 158 | 3.53125 | 4 | a = float (input ())
b = float (input ())
c = float (input ())
print (min (a, b, c))
print (a + b + c - min (a, b, c) - max (a, b, c))
print (max (a, b, c))
|
f13de5485de6b73e5a82a84ab6aabf640ca82621 | quan191/AlgorithmInPython | /SolveCSESProblem/Introduction/CoinPiles.py | 546 | 3.6875 | 4 | t=int(input())
for i in range (0,t):
test_list=input().split(" ")
y=int(test_list[0])
x=int(test_list[1])
if (x+y)%3==0:
if (x==0 and y==0):
print("YES")
elif(x==0 or y==0):
print("NO")
else:
m=((y+x)//3)+y-x
if(m%2==0 ... |
eb23716c85070f6b82a221d87e902ebf44aeac8c | ThanosSkarlatos/AdventOfCode2020 | /Day9.py | 1,226 | 3.65625 | 4 |
def check_preamble(preamble, data):
check = []
for i in range(0, len(preamble)):
if data - preamble[i] in preamble and 2 * preamble[i] != data:
check.append(True)
else:
check.append(False)
if True in check:
return True
else:
return False
def co... |
8f5cbedf9480a53b30bdb99c058d194d6725c4c3 | jahidkhan076/sudoku | /sudoku_Button.py | 1,422 | 3.578125 | 4 | from tkinter import *
import random
w=Tk()
w.title("SUDOKU")
B=[]
n=[]
for i in range(3):
for j in range(3):
frame=Frame(w,bg='powder blue',width=150,height=170)
frame.grid(row=i,column=j,padx=5,pady=5)
#m=[1,2,3,4,5,6,7,8,9]
for k in range(3):
for l... |
7922923dc668638c3dbee213f4aac1754ca8a0e2 | menard-noe/LeetCode | /Average Salary Excluding the Minimum and Maximum Salary.py | 524 | 3.75 | 4 | from typing import List
class Solution:
def average(self, salary: List[int]) -> float:
min_val = float("inf")
max_val = - float("inf")
count = 0
sum = 0
for val in salary:
min_val = min(min_val, val)
max_val = max(max_val, val)
count += ... |
2542bfa588283d7926d20fcd7acef80a42a75868 | Willyb15/Python-Algorithm-Scripts | /hash_tables/hash3.py | 1,373 | 3.671875 | 4 | class MyHashTable:
def __init__(self):
self.buckets = [None] * 26
def my_hash(self, value):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
first_letter = value[0]
return alphabet.index(first_letter.lower())
def insert(self, value):
bucket_index = self.my_hash(value)
... |
9889134ea82f01c261577b055da775b1737ffc5f | larryback/hello | /re1.py | 643 | 3.734375 | 4 | import re
line = "Beautiful is better than ugly."
matches = re.findall("e", line)
# print(matches)
# matches2 = re.findall("beautiful", line, re.IGNORECASE)
# print(matches2)
zen2 = """Although never is often ideaXXX better than * right * now.
If the implementation is hard to explain, it's a bad idea.
If the implemen... |
8ae9852750614e4f6a80fbc668cd90e0b18c8d3c | danigfavero/py14 | /oo/atualizador2.py | 1,349 | 3.625 | 4 | """Exercícios 11.7 - Herança e polimorfismo (opcionais)
"""
from conta_heranca import *
class AtualizadorDeContas:
def __init__(self, selic, saldo_total=0):
self._selic = selic
self._saldo_total = saldo_total
def roda(self, conta):
# checando se a instância passada no argumento 'cont... |
251028490454ec714c287d747f66fb2d024000cc | samyuktahegde/Python | /datastructures/stack/reverse_first_k.py | 310 | 3.6875 | 4 | def reverse(queue, k):
stack = []
for i in range(len(queue)-k):
queue.insert(0, queue.pop())
for i in range(k):
stack.append(queue.pop())
while len(stack)>0:
queue.insert(0, stack.pop())
print(queue)
reverse([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 5) |
7d607417d05d009aef99971f0e5b0cfba43e739a | thalescomp/topcom | /Jardim/gen_in.py | 437 | 3.703125 | 4 | from random import randint
MAX_POINTS = 1000
for i in xrange(0, 500):
N = randint(3, MAX_POINTS)
print N
points = set()
while len(points) < N:
a = randint(0, 2**10)
b = randint(0, 2**10)
points.add((a,b))
for x,y in points:
print x, y
N = MAX_POINTS
print N
points = set()
while len(points)... |
44dd1cc9602cc5c93e7c0895415325b3d1fdea9d | YTLogos/my_python_learning | /max_number.py | 580 | 3.78125 | 4 | #!/home/taoyan/anaconda3/bin/python3
# -*- coding: UTF-8 -*-
# filename:max_number.py
# author by:taoyan
while True:
try:
N=int(input("请输入需要对比大小数字的个数: "))
except ValueError:
print("您输入的不是整数,请重新输入!")
continue
print("请输入需要对比的数字: ")
num=[]
for i in range(1,N+1):
... |
fa2b2c127cb722640157d5583ae592f3108f7f1e | JerryHDev/Functional-Programming | /Chapter 9/9_12.py | 737 | 3.90625 | 4 | #Jerry Huang
#Period 4
from random import *
def main():
printIntro()
n = eval(input("Enter the number of steps to talk in this random walk: "))
x = eval(input("Enter the nunber of times to simulate this random walk: "))
y = 0
for i in range(x):
end = simAWalk(n)
y = y + end
prin... |
97393359b1fa830d9fafc5795439c50ea6475b7f | totoandco/MSProject | /temp_tracker/temp_tracker.py | 1,641 | 3.890625 | 4 | class TempTracker:
max_temp = 110 # type: int max temperature value
min_temp = 0 # type: int min temperature value
def __init__(self):
self.__temperatures = []
def insert(self, new_value):
"""
:param new_value: insert new value into the tab where we save the previous temper... |
a6e2a7911e061ce8bbfeaf2963d1347eb8cd120e | pallavivaswani/Colour-Game | /colourgame.py | 2,217 | 3.8125 | 4 | #import modules
from tkinter import *
import random
from tkinter import messagebox
root = Tk()
root.title("Colour Game")
root.geometry("375x200")
root.configure(background="SpringGreen2")
colours = ['RED', 'PURPLE', 'WHITE', 'ORANGE', 'PINK', 'BROWN', 'GREEN', 'YELLOW', 'BLUE']
score = 0
timeleft = 30 ... |
fb226e7e47553a09ff8ed2f9f6214b5dfb7d3840 | cndracos/spherecrypt | /venv/spherecrypt/Point.py | 463 | 3.578125 | 4 | import math
class Point:
def __init__(self, x: float, y: float, z: float):
self.x = x
self.y = y
self.z = z
def scale(self, scale):
return Point(self.x * scale, self.y * scale, self.z * scale)
@property
def normalize(self):
magnitude = math.sqrt(self.x * self.... |
a851be9543a49371d4889840c86bba5a46106b9e | rishikant42/algorithms | /dp/unbound_knapsack/count_coin_change_ways.py | 345 | 3.609375 | 4 | coins = [1, 2, 3]
target = 5
n = len(coins)
def count_ways(target, coins, n):
if target == 0:
return 1
if n == 0:
return 0
if coins[n-1] > target:
return count_ways(target, coins, n-1)
return count_ways(target, coins, n-1) + count_ways(target-coins[n-1], coins, n)
print(count... |
27a92606dca3171ec954b9a6a45389fef74fadf4 | Mandroide/Test_Traffic_Anomaly_Detector | /performance.py | 2,968 | 3.5625 | 4 | from typing import Union, Sequence
import numpy as np
from sklearn.metrics import mean_squared_error
# TODO: Implement detection time error.
def measure_detection_time_error(y_true: Sequence[int], y_pred: Sequence[int]) -> float:
"""Calculate detection time error of the traffic anomaly detector of a video.
... |
d4fcfe41699e8f26a1f657beb5b22b051744e75e | janakiraam/Python_Basic_Advance | /2.Sequence and file oprations/File_handling/10.seek_method.py | 268 | 3.765625 | 4 | # .tell() method tells the position of file pointer
fo = open('bye.txt', 'r')
fo.seek(3,0) # moves the file pointer by three positions from the beginning
print(fo.read())
fo.seek(0)
print("--- Going to read the content from beginning--")
print(fo.read())
fo.close() |
91e87241019d9da243c171e155dddfb926cc43cc | yash-0501/python-poc | /concepts/exceptionHandling.py | 442 | 3.890625 | 4 | a = 5
b = 2
try:
print("Resource Opened")
print(a/b)
k=int(input("Enter a number"))
print(k)
# except Exception as err:
# print("Cannot divide a Number by Zero:", err)
except ZeroDivisionError as err:
print("Cannot divide a Number by Zero:", err)
except ValueError as err:
print("Invalid ... |
59f11ddfef6c28d1ba8c2b251029bb2fbb92e82f | tjredfern/N-body-numerical-simulation | /orbits_formation_example.py | 7,163 | 3.796875 | 4 | import numpy as np
import sympy as sp
# Define a Vector2D class
class Vec2:
def __init__(self, x, y):
self.x = x
self.y = y
# Used for debugging. This method is called when you print an instance
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
... |
16cc6ebb99861b9f733463cf2bb9b86b8a922b42 | childxr/lintleetcode | /NumberOfIsLandsII/solution.py | 2,599 | 3.578125 | 4 | class UnionFind:
def __init__(self, n, m):
self.m = m
self.n = n
self.ids = [-1 for i in xrange(m * n)]
self.sz = [0 for i in xrange(m * n)]
self.count = 0
def indexOf(self, point):
return point.x * self.m + point.y
def add(self, point):
... |
74e6d2eb7921c0cc31056f56003f95305a70d6ac | kikimor2009/Python-Practice | /stepik_task1.py | 302 | 3.5 | 4 | #!/bin/env python3
inf = open("/Users/macserebro/Downloads/file.txt")
s = inf.readline().strip()
num = ''
for i in range(len(s)):
if s[i].isalpha():
ch = s[i]
else:
num += s[i]
if i == len(s) - 1 or s[i + 1].isalpha():
print(ch * int(num), end='')
num = ''
|
30a3557586c7f94dccf0e174ae98ad77ffd68e14 | SaretMagnoslove/learn_programming-Derek | /Python/video20/addEven.py | 528 | 3.765625 | 4 | from tkinter import *
from tkinter import ttk
def get_sum(event):
num1 = int(num1Entry.get())
num2 = int(num2Entry.get())
sum = num1 + num2
sumEntry.delete(0, 'end')
sumEntry.insert(0, sum)
root = Tk()
num1Entry = Entry()
num1Entry.pack(side=LEFT)
Label(root, text = '+').pack(side=LEFT)
num2En... |
22ba764bbc6c6c690419dd2974e2fc23f3691749 | DeagaDH/LearningFromData_HW | /HW2/hw2_func.py | 12,751 | 4.3125 | 4 | import random
import numpy as np
def random_point(xlim=[-1,1],ylim=[-1,1]):
"""
Creates a random point with coordinates(x,y)
Random values will be bounded by xlim and ylim
"""
x = random.uniform(xlim[0],xlim[1])
y = random.uniform(ylim[0],ylim[1])
return (x,y)
def create_dataset(y_func,... |
1f2fd0dd778bfbcbd92760472f686b76947a7ed8 | chenran1/leetcode | /note/120_三角形最小路径和.py | 1,293 | 3.9375 | 4 | """
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
说明:
如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:... |
ff8f99cf5ebe4a2bd68ede84d9d1de185dc72a95 | michi201/gitrepo | /python/ciag_rek.py | 331 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# a1 = 2
# an = an-1 * n^2+1
def ciag(n):
if n == 1:
return 2
return ciag(n - 1) * ciag(n * n) + 1
def main(args):
n = int(input('podaj wyraz ciągu: '))
print(ciag(n))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(s... |
97e8e28a400700bbc5d54d35a3a71603057ee5ba | kkkingim/leetcode | /e_976.py | 748 | 3.984375 | 4 | """
https://leetcode.com/problems/largest-perimeter-triangle/
Given an array A of positive lengths,
return the largest perimeter of a triangle with non-zero area,
formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
Example 1:
Input: [2,1,2]
Output: 5
Example 2:
Inpu... |
35fa2e0ff4b8784a0b8a73b092d24e797b7928bf | parantapa/pypb | /pypb/abs.py | 1,055 | 3.515625 | 4 | """
Misc abstract classes and functions.
"""
import abc
from functools import wraps
class Close(object):
"""
Runs close() on context exiting and garbage collection.
If close() method should be run only once
make sure to use the `runonce` decorator.
This class doesn't check if close has previously... |
1cb91753ff8fd19ffae26e6b540f2f5b9253d7b5 | albertfougy/leetcode | /leetpy/easy/test_add_two_numbers.py | 1,979 | 4.09375 | 4 | class ListNode:
"""Definition for a singly-linked list."""
def __init__(self, x):
self.val = x
self.next = None
def to_int(node):
"""Create an integer from a linked list with the head representing
the smallest digit."""
placeholder = ""
while node is not None:
placehol... |
dfa362c71ad2018b9c9f36136c11bab8d52b9fa0 | Litao439420999/LeetCodeAlgorithm | /Python/maxProfitChance2.py | 1,101 | 3.6875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: maxProfitChance2.py
@Function: 买卖股票的最佳时机 IV 动态规划
@Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-16
"""
class Solution:
def maxProfit(self, k: int, prices) -> int:
if not... |
40cce5c94dbac54e6e27bce20ad659c085b1cf13 | Him98/DB_Assignment2 | /linearHash.py | 4,038 | 3.609375 | 4 | import sys
bucket_cnt = 2
#
b = 2
#New hash function, it get updated as the original hash function gets updated
bNext = 4
total_block_cnt = 2
block_cnt = {}
p = 0
# Total number of records.
totalNumbers = 0
#hashTable stores buckets, that are collection of blocks, blocks having size B
hashTable = {}
block_cnt[0] ... |
b63138322725f9545ecef5a3c567b8aa754a5310 | jianhui-ben/leetcode_python | /739. Daily Temperatures.py | 837 | 4.09375 | 4 | #739. Daily Temperatures
#Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
#Ex... |
a5d63c3dae94af52801d5ba6f1f06e6f9e513ff0 | cthulhu1988/RandomPython | /write.py | 330 | 3.6875 | 4 | def write():
file = open("write.txt","w")
for num in range(1,100,6):
num = str(num)
file.write(num+"\n")
file.close()
print("Done")
def read():
file = open("write.txt","r")
new_file = file.readlines()
for ch in new_file:
print(ch)
file.close()
#write... |
e5ad5843a26a3301736910f43ac6d282cb56d84a | dangspin/Do_for_fun | /Useful_code/Python_key_words.py | 497 | 4.09375 | 4 | ## 1. Yield, which turns a function to a generator:
## Ex1: Square of a number of input
def square(x_input):
while True:
t = x_input**2
x_input = x_input + 1
yield t
for num in square(10):
if num > 500:
break
print(num)
## Ex2: Generate a set of numbers g... |
1ea2cf8cd6d0210a18e818ddccc124171a155b0e | mdaughtrey/personal-projects | /projector/scripts/interval_gen.py | 787 | 3.71875 | 4 | #!/usr/bin/env python3
import pdb
int0 = 50
int1 = 292
val0 = '42'
val1 = '43'
#pdb.set_trace()
def run0():
vv = 0
intervals = []
for ii in range(int0 + int1 + 1):
# print('ii {} vv {}'.format(ii,vv))
if vv > 1:
vv -= 1
intervals.append(val0)
else:
... |
c0b87d14b1f58eb8c88fed63c0dc179171c6a0e5 | qmnguyenw/python_py4e | /geeksforgeeks/python/basic/4_19.py | 2,732 | 4.8125 | 5 | Draw Clock Design using Turtle in Python
Turtle is an inbuilt module in Python. It provides drawing using a screen
(cardboard) and turtle (pen). To draw something on the screen, we need to move
the turtle (pen). To move turtle, there are some functions i.e forward(),
backward(), etc.
#### To draw Clock Des... |
29d59bbbaa57b1ee9f78d8acd59341c3695bba7d | banana-galaxy/challenges | /challenge17(backOnTime)/solutions/Atlas.py | 392 | 3.640625 | 4 | def solution(directions):
if len(directions) > 10:
return False
lat = 0
long = 0
for direction in directions:
if direction == "n":
lat += 1
elif direction == "s":
lat -= 1
elif direction == "e":
long += 1
else:
long ... |
f069cef80da23befb88518dbd3f917bc26e19753 | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#58/main.py | 1,326 | 3.984375 | 4 | """
An sorted array of integers was rotated an unknown number of times.
Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null.
For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in... |
3a93e7e6e8bb092bd7a47e38c8517b6b9db3c0e5 | gabrielmbob/AulaMaua | /Ex4_string1.py | 170 | 3.734375 | 4 | def inverte():
palavra = raw_input('Digite uma palavra: ')
print ('Sua palavra invertida eh: {0}'.format (palavra[::-1]))
inverte()
# Nota: 1.0
# Comentario: *
|
6b8becfa8f9845a9c6fdb7b6b79541990f06005a | Eneight/Minigames | /bank.py | 345 | 3.5625 | 4 | import csv
class Bank():
def __init__(self):
with open("records.csv", "w+") as records:
reader = csv.reader(records)
# Plan: Create a bank object that records the csv as an array to be interacted with by the other programs.
# Only necessary functions are read and write, and reading should be... |
2fd380fd92bdacc922da7d10c70229692429dc00 | aibolTungatarov/Algorithms | /ProblemSet6/Task3.py | 1,026 | 3.765625 | 4 | def findOptimal(weight, calories, foodItems):
originCal = calories
if weight > sum(foodItems):
return sum(originCal)
calories = minimize(calories , foodItems)
res = 0
arr = findMaxCalorie(calories,foodItems)
maxC = arr[0]
foodMax = arr[1]
calories.remove(maxC)
foodItems.remov... |
db18908f020568d3bfc89b074eb18129c370ae50 | Bovey0809/CarND-Advanced-Lane-Lines | /radius_curve.py | 1,863 | 3.65625 | 4 | import numpy as np
def generate_data(ploty, leftx, rightx, ym_per_pix, xm_per_pix):
'''
Generates fake data to use for calculating lane curvature.
In your own project, you'll ignore this function and instead
feed in the output of your lane detection algorithm to
the lane curvature calculation.
... |
44e84c354e9eac7f8b805549adb565c47f6c3d51 | brooot/Python_Base_Codes | /pbase/day15/yield1.py | 931 | 3.640625 | 4 |
# def event(begin,end):
# start=begin
# while start<end:
# if start%2==0:
# yield start
# start+=1
# return '不能再生产偶数了'
# # l=[x for x in event(10,20)]
# # print(l)
# gen=event(5,10)
# print(next(gen))
# print(next(gen))
# print(next(gen))
# gen=(x**2 for x in range(1,5))
# it=... |
b731ecb7930744fa896ed4ed4f506020f1d14b47 | Ace-0/MyLeetCode | /src/572-subtree-of-another-tree.py | 1,661 | 3.921875 | 4 | # 572. Subtree of Another Tree
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
s_str = self.get_preorder_string(s)
t_str = ... |
3ae488b60fb90f13fe5650b72a5b510a5caadbdf | Air-Zhuang/Test35 | /High_Level_Coding_python3/3/3_6.py | 1,031 | 3.640625 | 4 | '''
在一个for语句中迭代多个可迭代对象
'''
from random import randint
from itertools import chain
#并行
chinese=[randint(60,100) for _ in range(10)]
math=[randint(60,100) for _ in range(10)]
english=[randint(60,100) for _ in range(10)]
print(chinese);print(math);print(english)
total=[]
for c,m,e in zip(chinese,math,english):
total... |
f97bfea93b7a5e21e2a491adb98dcd0484235b19 | gaibo/Python | /workshop/guesser2.py | 301 | 3.84375 | 4 | #Set 7 as the secret number
number = 7
#Prepare a while loop with flag variable
done_guessing = 0
while done_guessing == 0:
guess = int(raw_input("Guess my number! "))
if guess == number:
print "You got it right!"
done_guessing = 1
elif guess > number:
print "Lower!"
else:
print "Higher!" |
b27479ec1c0e739f3d089cce414b9e8bd789ac74 | echibe/Projects | /Python/Project Euler/Untitled.py | 143 | 3.796875 | 4 | sum = 0;
for num in range(1,1000):
if ((num % 3==0) | (num % 5==0)):
sum += num
# print num
# print sum
print sum
|
a3baf995e78aa852bca1162d096f19349f4f5974 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mblbuh001/question4.py | 1,965 | 4.125 | 4 | # question4.py
# Name: Buhlebezwe
# Student Number: MBLBUH001
# Date: 07 May 2014
import question1
import math
import sys
sys.setrecursionlimit (30000)
start = eval(input("Enter the starting point N:\n")) #get input (starting number) from user
end = eval(input("Enter the ending point M:\n"))... |
7842fda7bc1d2e82f77ecf4a7455962662264304 | galya-study/ji | /py/6. while/ex 8 seq_max.py | 470 | 4.03125 | 4 | # Максимум последовательности
# Последовательность состоит из натуральных чисел
# и завершается числом 0. Определите значение
# наибольшего элемента последовательности.
max = 0
n = 0
while True:
n = int(input())
if n == 0:
break
if max == 0:
max = n
elif max < n:
max = n
pr... |
979fee4e938d048efc47f7a4f51a9c2aa05c130b | daniel-reich/ubiquitous-fiesta | /vKPepKYAvx2Rao3zt_12.py | 180 | 3.5 | 4 |
def car_timer(n):
hours = int(n / 60)
minutes = n - hours * 60
res = 0
for ch in str(hours):
res += int(ch)
for ch in str(minutes):
res += int(ch)
return res
|
de2d79eb78d82ad63f5baff423235b7a33797c24 | Touchfl0w/python_practices | /advanced_grammer/practice1-10/practice7/p2.py | 254 | 3.578125 | 4 | a = 3
b = 4
t = [100,200]
q = []
#从下面可以知道,lambda函数可以使用非本地变量!
f = lambda x: q.append(x+a+b+t[1])
'''
上面相当于:
def f(x):
return q.append(x+a+b+t[1])
'''
#q.append的调用会返回None
print(f(1))
print(q) |
4702fd89db2556bafb6bb8eaefe68b3bd71d56b2 | PilarNew/pybasic | /05-condicionales/main.py | 3,016 | 4.4375 | 4 | # Estructura de control que permite controlar el flujo del programa
"""
# IF
SI se_cumple_esta_condicion:
Ejecutar grupo de instrucciones
SI NO:
Se ejecutan otro grupo de instrucciones
if condicion:
instrucciones
else:
otras instrucciones
# Operadores de Comparación
== igual
!= diferente
< men... |
f15676e2436456d8fca9282e3461e51c6099bf1c | Crisescode/leetcode | /Python/Search/704. binary_search.py | 1,216 | 4.1875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# author: Crise
# date: 25/07/2021
"""
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(... |
7fb8a8ea66b402e2329e9cefba4b331515ccb974 | pmerritt2003/pyautogui_PM | /List.py | 642 | 4.0625 | 4 | name = "Preston"
subjects = ["Math", "History", "Science"]
print ("My name is " + name)
for i in subjects:
print ("I take " + i +" as one of my classes.")
goodfootballplayers = ["tom bradey", "Nick foles", "Crooks", "rob growkoski"]
for i in goodfootballplayers:
if i == "tom bradey":
... |
9c4ef4b4a169153bf4d69c2c0b72bc1afc23f9ed | sagarnikam123/learnNPractice | /hackerRank/tracks/coreCS/algorithms/implementation/theGridSearch.py | 4,407 | 4.03125 | 4 | # The Grid Search
#######################################################################################################################
#
# Given a 2D array of digits, try to find the occurrence of a given 2D pattern of digits. For example, consider the
# following 2D matrix:
# 1234567890
# 0987654321
# 11... |
dfaf561f70367b6bedb7d888c25b0749c652b079 | srimani-programmer/Image-processing | /Basics/ImageRepresentation.py | 1,095 | 3.53125 | 4 | # Importing the modules
import cv2
image = cv2.imread('/Users/srimanikanta/Desktop/Image-processing/Basics/Images/ImageSet-2/lena_color_512.tif')
# showing the color images in a number format.
print(image)
# getting the type of an object.
print(type(image))
# getting the datatype of an object.
print(image.dtype)
# ... |
6ea43e292a35d3acd1cf10a291bb85307f315cad | aaronchu415/LeetCode | /completed/leetcode-Searcha2DMatrix.py | 814 | 3.96875 | 4 | # // _NAME: Search a 2D Matrix
# // _LINK: https://leetcode.com/problems/search-a-2d-matrix/
# // _CATEGORY: 2d Array
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
i = 0
j = 0
def inThisRow():
if i == len(matrix)-1:
retu... |
607ae1c429196b9db90acb6b555114e5478eeff0 | kuroroblog/atcoder221 | /B.py | 701 | 3.546875 | 4 | # 標準入力を受け付ける。
S = input()
T = input()
# Sを操作することなく、S = Tになる場合は、即座にYesを出力する。
if S == T:
print('Yes')
exit()
S = list(S)
for i in range(len(S) - 1):
# S[0]とS[1]を入れ替え、S[1]とS[2]を入れ替え、S[2]とS[3]を入れ替え、、、の場合を検証する。
tmp = S[i + 1]
S[i + 1] = S[i]
S[i] = tmp
# 入れ替えた場合にS = Tになるか検証する。
if ''.join(S... |
8647ab652b10f07ef1954b437c1d75f675b1d750 | XiaoxiaoMa95/Basic-Python | /3. 基本数据类型/3-9. 天天向上续.py | 659 | 3.53125 | 4 | '''天天向上续。尽管每天坚持,人的能力发展不是无限的,它符合特定的模型。
假设能力增长符合如下带有平台期的模型:
以7天为周期,连续学习3天能力值不变,从第4天开始至第7天每天能力值增长为前一天的1%。
如果7天中有1天间断学习,则周期从头计算。
编程回答,如果初始能力值为1,连续学习365天后能力值是多少'''
dayfactor = 0.01
dayUp = 1.0
for i in range(366):
if i % 7 in [1, 2, 3]:
dayUp = dayUp
else:
dayUp = dayUp * (1 + dayfacto... |
879ee57eace50dbd1134ff4758cfb6de19862a39 | asaf19-meet/YL1-201718 | /lab6/lab6.py | 733 | 3.90625 | 4 | from turtle import *
import random
import math
class Ball(Turtle):
def __init__(self,radius,color,speed):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
self.color(color)
self.speed(speed)
def check_collision(ball1,... |
412ed77d5d4df1767983c17f804fadbcf9fa6ad6 | jamespolley/linear-data-structures | /queue/example.py | 881 | 4.03125 | 4 | from CustomerOrders import CustomerOrders
# Create an empty CustomerOrders. Set to increment by 7 (for more
# unique sounding order numbers).
co = CustomerOrders(number_increment=7)
# Add new orders.
co.new_order('Burgers, Fries, Chocolate Shake')
co.new_order('Cheese Pizza')
co.new_order('Hot Dog, Fries')
co.new_or... |
134deb13b5700958af71598b702492867a3858cf | julianoaureliano/julianoaureliano | /Python/29.py | 199 | 3.75 | 4 | velo = int(input('qual a velocidade do veículo em km/h:'))
if velo > 80:
print('VOCE FOI MULTADO !!!')
print('Multa no valor de R${}'.format((velo-80)*7))
else:
print('Situaçao normal') |
64b2e5e56d0444cda9f3cad985a339791f24ebda | individuals2/Python-Parallel-Programming | /chapter3/6_1-queue.py | 1,451 | 3.734375 | 4 | # encoding: utf-8
"""
@ author: wangmingrui
@ time: 2021/3/12 17:49
@ desc: 使用队列在进程间通信
"""
import multiprocessing
import time
class Producer(multiprocessing.Process):
def __init__(self, queue: multiprocessing.Queue):
multiprocessing.Process.__init__(self)
self.queue = queue
def run(self):
... |
9bcf01fc5eff03de21b8746fd9125bfc7393cf6d | Erick-Paulino/exercicios-de-cursos | /Python/Curso em video/ex054.py | 493 | 4.0625 | 4 | '''Crie um programa que leia o ano de nascimento de sete pessoas.
No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.'''
from datetime import date
maior = 0
menor = 0
for c in range(1, 8):
nasc = int(input(f'qual o {c}° ano de nascimento? '))
idade = date.today().year - ... |
f92365149e4c3721873acfbf3ef1e3de8d91223f | Pelhans/leetcode | /jianzhi/11.py | 668 | 3.765625 | 4 | #!/usr/bin/env python
# coding=utf-8
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray) == 0:
return 0
elif len(rotateArray) == 1:
return rotateArray[0]
elif len(rotateArray) == 2:
... |
877e63b27c652be82f8902cb480c8a446d03429a | Raii-Azevedo/Python-Exercicios | /EX 012.py | 301 | 3.6875 | 4 | print ('EX 012. Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto')
produto = float (input ('Digite o valor do produto: '))
desconto = produto - (produto * 5)/100
print (f'Um produto de R${produto:.2f} com 5% de desconto passa a custar R${desconto:.2f}') |
de6a7fcccde0ae48f5a49b29e6c32d4130804ec6 | CateGitau/Python_programming | /LeetCode/code_night/diagonal_traverse.py | 320 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 8 00:22:10 2020
@author: aims
"""
nums = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
def diagonal_traverse(nums):
for i in range(len(nums)):
for j in nums[i]:
print(nums[i], nums[-1])
print(diagonal_traverse(nums))
|
b5b7f1d558ae4603950011bff517a7600a57f244 | DanteASC4/cs_sem_1_hw | /hw12_hexa_input.py | 362 | 4.5 | 4 | #Name: Dante Rivera
#Date: August 28th, 2018
#This program takes a user given hexadecimal and prints a turtle the given color
#importing turtle
import turtle
# Creating turtle
dat_t = turtle.Turtle()
# Turtle shape
dat_t.shape('turtle')
# Get hexadecimal color value
hex = input('Enter a hexadecimal color: ... |
844988a9177f113f8316b5edb13921e0e8394fd8 | hatFolk/BigOQuiz | /Quiz.py | 5,297 | 3.734375 | 4 | import random
import csv
class Question:
def __init__(self, qID, question, answer, correct = 0, asked = 0, battingAvg = 1):
self.qID = qID # Question's ID
self.question = question
self.answer = answer
self.asked = asked
self.correct = correct
self.battingAvg = battin... |
4ebe498a97188083a5b4cf66ffc017b2292f0d89 | smartronx/PythonBrasil-exercicios | /01_estrutura_sequencial/06_raio_circulo.py | 643 | 4.375 | 4 | #Usei a versão do Python 3.6.7 para fazer o exercício.
#Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
#Resposta:
print(' * Resposta exercício 6:')
#formula Matemática para cálculo da Área do raio = A = π . r2 | Área é igual a pi vezes raio ao quadrado.
# Para pegar o Pi optei por usar a... |
eff0b592983c26b250a6f9da3e16aeea9813c500 | AnnaShilova/structured-programming | /lub 1/6.py | 279 | 4.125 | 4 | from math import pi, sqrt
R = int(input("радиус нижнего основания = "))
r = int(input("радиус верхнего основания = "))
h = int(input("высота = "))
S1 = pi*R**2
S2 = pi*r**2
V = (h*(S1 + sqrt(S1*S2) + S2))/3
print ("V = ",V)
|
57a6a8518865eed5b2fcda467b5acfd2b366ccbb | nnakhoa2310/100days_python | /day27/main.py | 596 | 3.71875 | 4 | # import tkinter as tk
#
# window = tk.Tk()
# window.title("GUI Python")
# window.minsize(width=500, height=300)
#
# my_label = tk.Label(text="Im a label", font=("Arial", 24, "bold"))
# my_label.pack()
#
# window.mainloop()
# method unlimited agruments
#
# def add(*args):
# sum = 0
# for n in ar... |
fb4a8c319f0f5f54c2d0b86a75086533984ef580 | evaldojr100/Python_Lista_2 | /03_positivo_ou_negativo.py | 314 | 3.953125 | 4 | '''3) (Python.org.br) Faça um Programa que peça um valor e mostre na tela se o valor é positivo
ou negativo. Salve o programa com o nome “ 03_positivo_ou_negativo.py ”.'''
num=int(input("Digite um numero:"))
if num>0:
print("Positivo")
elif num==0:
print("zero")
else:
print("Negativo") |
6a190c7dd617219c02b741fd7b8ff8b444508fc8 | SophiaAr/BallerinaClassifier | /plot_history.py | 987 | 3.515625 | 4 | from matplotlib import pyplot as plt
def plot(history, from_epoch = 0):
try:
acc = history.history['acc'][from_epoch:]
val_acc = history.history['val_acc'][from_epoch:]
# summarize history for accuracy
plt.plot(acc)
plt.plot(val_acc)
plt.title('model accura... |
b68747b7fdfa0523c79d358e24308c6de023a936 | MyMiDiII/bmstu-python | /sem_02/lab_03/lab_03.py | 16,405 | 3.875 | 4 | ''' Лабораторная работа №3
"Исследование методов сортировки."
Назначение:
1) сортировка списка методом пирамидальной сортировки;
2) замер времени сортировки списков разных размерностей;
3) построение графика зависимости времени сортировки от размерности
списка.
'''
from tkinter im... |
a57695d012e0595c0a2b750006f0d5ee68b18788 | geogao/test_git | /ex19.py | 425 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 02 13:15:56 2018
@author: George
"""
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print "You have %d cheeses" % cheese_count
print "you have %d boxes of crackers," % boxes_of_crackers
cheese_and_crackers(5,6)
am = 5
am2= 7
che... |
ce7f9d08ae7b567610b60816908a764fe98a0b13 | sukantamajhi/Computer_graphics_Lab | /csa.py | 3,464 | 3.53125 | 4 | # Python program to implement Cohen Sutherland algorithm
# for line clipping.
import matplotlib.pyplot as plt
# Defining region codes
INSIDE = 0 #0000
LEFT = 1 #0001
RIGHT = 2 #0010
BOTTOM = 4 #0100
TOP = 8 #1000
# Defining x_max,y_max and x_min,y_min for rectangle
# Since diagonal points are enough to def... |
e8880c843a0b269876596de31f7c4f06644c93ff | MonishaCode/Intro-to-Python-Programming | /PSet 2/EvenOdd.py | 135 | 3.90625 | 4 | # Print 1 to 100 even numbers
i=1
while i <= 100:
#check for number being zero
if i%2==0:
print(i)
i+=1
|
5c525e82f9fb8cf6bc18e0fc4fe8c61adda90d5d | ToniJhon24/ToniJhon24 | /Modulo 1/Ejercicios 1.py | 2,849 | 4 | 4 | #Pregunta 1
nombre = input('Coloque su nombre:')
print ('Hola {}!' . format(nombre))
#Pregunta 2
shows = int(input('¿Cuantos shows musicales logro ver en el año? :'))
if(shows >= 3):
print('El usuario a visto mas de 3 shows : True')
else:
print('El usuario no a visto mas de 3 shows : False')
#Pre... |
2c9778e39071ae052d6e6bd7d4c8cb3afb223f6b | arlandism/tic_tac_toe | /game/test/test_board_generator.py | 2,267 | 3.578125 | 4 | import unittest
from game.board_generator import BoardStringGenerator
class BoardStringGeneratorTests(unittest.TestCase):
def test_board_string_with_rows(self):
state = {1:"A"}
generator = BoardStringGenerator(2,state)
expected_layout = {"1":"A","2":"","3":"","4":""}
self.assertEqu... |
10bf49813c9bfe2e74acac2a44b25bc9bc00f5eb | cairoas99/Projetos | /PythonGuanabara/exers/listaEx/Mundo2/ex041.py | 196 | 3.8125 | 4 | idd = int(input('Idade: '))
if idd <= 9:
print('MIRIM')
elif idd <= 14:
print('INFANTIL')
elif idd <= 19:
print('JUNIOR')
elif idd <= 20:
print('SENIOR')
else:
print('MASTER') |
56b0f6108928c050926785a0795bc2f0e759c65e | Chad-Lister/ITEC_3001_Python_Programming | /DS Chapter # 3 Projects 1, 3, 5, 8/DS Chapter # 3 Project # 5/selection.py | 819 | 4.1875 | 4 | """
Program: selection.py
Author: Chad Lister
Date: 01/21/2021
This program is the selection sort given in the book for
DS Chpter # 3 Project # 5:
Modify the selection sort function discussed so the user can choose
ascending or decending order.
"""
def swap(lyst, i , j):
temp = lyst[i]
lyst[... |
07eb93699a9a51ffa18c1b83f94ed91fab5148dc | HaminKo/codingbat | /warmup-2/string_bits.py | 322 | 4.1875 | 4 | def string_bits(str):
"""
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
"""
return_str = ''
for i in range(0, len(str), 2):
return_str += str[i]
return return_str
print(string_bits('Hello'))
print(string_bits('Hi'))
print(string_bits('Heeololeo')... |
f51349474f58aa33803f697b2f34fa227075663c | Manas1820/Red-Object-Identifier | /RedObjectIdentifier.py | 1,168 | 3.5 | 4 | import cv2
import numpy as np
'''
Author Name: Manas Gupta
Date : 4:35 AM 2/7/2020
Description : This code will just identify all the red objects nearby seen through camera
'''
cap=cv2.VideoCapture(1)
#cap=cv2.VideoCapture(0)
''' if you are using your webcam change your camera to 0
I used my mobile camera to test t... |
8a114c8a70324c482969eae900fce0c43e891245 | JayaYeruva/python-ibm-hyd-15-18-june-2015 | /day2/OOPS/pspropertyclass.py | 404 | 3.640625 | 4 | __author__ = 'ravi'
class Property(object):
def __init__(self):
self.container = {}
def __setitem__(self, key, value):
self.container[key] = value
def __getitem__(self, item):
return self.container[item]
if __name__ == '__main__':
p = Property()
p['name'] = 'ibm'
p['c... |
5bd3981651de2af0e0394e83e20a7d3e48231e87 | erickanski0402/Digit-Classifier | /script.py | 2,475 | 3.96875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import dataset as ds
import neural_network as network
# Define the number of nodes for each layer
input_nodes = 784
hidden_nodes = 100
output_nodes = 10
# Define the learning rate for the network
learning_rate = 0.3
# Initialize the neural network
nn = network.neural_... |
eae3f6cc3991d341eefbed3bda6038d5de6c16a4 | malhotra-sidharth/py-data-structures | /data_structures/linked_list/two_way_list.py | 488 | 4.0625 | 4 | from data_structures.linked_list.two_way_node import TwoWayNode
class TwoWayList:
"""
Creates a linked list that can be traversed in both directions
"""
def __init__(self):
self.__head = None
self.__size = 0
def add(self, data):
"""
Adds a new node to the list
Complexity => O(1)
... |
6fb20970a7e1049d2f1f09ddddc60500e4f0a214 | Cosprs/cvrp-genetic-algorithm | /cvrp/src/utilities.py | 1,401 | 3.984375 | 4 | import random
# This function generates a random coordinates array, number wide and with values between minimum and maximum
def get_coordinates(number, minimum, maximum):
coordinates = [[None for i in range(2)] for i in range(number)]
for i in range(0, number):
coordinates[i][0] = random.randint(minim... |
5cae749e1cbd199516c61662d3b9d83eba14dda6 | CedricKen/Python-GUI | /Menu Bar/Tabs and menubar.py | 1,479 | 3.703125 | 4 | from tkinter import *
from tkinter import Menu
from tkinter import ttk
import time
import tkinter.messagebox as tm
root = Tk()
# Exit GUI cleanly
def _quit():
root.quit()
root.destroy()
exit()
def exit():
tm.showinfo('This is a Title', 'A Python GUI created using tkinter:\nThe year is ... |
a0bd68df8ba8b2e797c57d2d4593e16221decc51 | wojtekidd/Python101 | /ls.py | 158 | 3.890625 | 4 | add_ls_to = input("I will add 'ls' to: ")
while True:
if add_ls_to == "ls":
print(add_ls_to)
else:
print(add_ls_to + "ls")
break
|
68525df58cc3d0f585d8fcbef39b027bfac2d496 | joshmalek/leetcode-solutions | /Arrays/bestTimeToBuyAndSellStock.py | 1,369 | 3.796875 | 4 | # Say you have an array prices for which the ith element is the price of a given stock on day i.
# Design an algorithm to find the maximum profit. You may complete as many transactions as you
# like (i.e., buy one and sell one share of the stock multiple times).
# You may not engage in multiple transactions at the sa... |
02f2d4b697d3bdc2ddffe0e17a008dfaa0de10c8 | hammerdrucken65/t1 | /madlib1.py | 502 | 4.1875 | 4 | story=("there once was a [TO]"
" who [TO] on a [TO]"
" then it [TO] like the [TO] thing that it was")
noun=input("please enter noun: ")
verb=input("please enter verb: ")
noun2=input("please enter noun: ")
verb2=input("please enter verb: ")
adjective=input("please enter adjective: ")
story=story.replace("[... |
12f877a33d38525f480874945986d34d6c537560 | lidongze6/leetcode- | /744. 寻找比目标字母大的最小字母.py | 322 | 3.609375 | 4 | def nextGreatestLetter(letters, target):
l,r=0,len(letters)-1
while l<r:
mid=(l+r)//2
if letters[mid]>target:r=mid
else:l=mid+1
if l>=r:
return letters[l] if letters[l]>target else letters[0]
letters = ["c", "f", "j"]
target = "g"
print(nextGreatestLetter(letters,target))... |
7b43af4029227d7f4edbaddad4ab3988ee44c012 | vsviroje/assign9 | /Assignment9_4.py | 480 | 3.8125 | 4 | import os
def main():
file1=input("Enter File1 Name:")
file2= input("Enter File2 Name:")
if os.path.isfile(file1) and os.path.isfile(file2):
f1=open(file1,'r')
f2=open(file2,'r')
rf1=f1.readlines()
rf2=f2.readlines()
if rf1==rf2:
print("both file are same... |
252151e0111c8fb40a5fbffe981c800e20e620ac | GitEasonXu/Python-Algorithm | /设计模式/builder_factory.py | 1,628 | 3.734375 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Author: Len-xu
Date: 2021-02-21 14:22:53
LastEditTime: 2021-02-21 14:36:38
LastEditors: Do not edit
FilePath: \Python-Algorithm\设计模式\builder_factory.py
Description: 建造者模式
'''
from abc import ABCMeta, abstractmethod
# 产品
class Player:
def __init__(self, face=None, body=None,... |
dd5549b9b148054335a4f58e71f86747b61458dd | ManullangJihan/Linear_Algebra_Courses | /CH 4/CH 4 Sec 3 Part 2/part141.py | 257 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 23:23:05 2020
@author: hanjiya
"""
from sympy import Matrix
A = Matrix([[2,3,1,2],
[1,3,2,4],
[3,3,3,3],
[2,1,3,4]])
det_A = A.det()
print(det_A) |
2883ce87f127e1e5858258d6708284ae50611e97 | DavidYi/Intro-to-Computer-Science-Trimester-1 | /Python/Interest Calculator.py | 1,038 | 4.28125 | 4 | #Unit 1- Interest Calculater
#David Yi
print("In order to help you finding the amount of money in a number of years, I ask of \
you to give me your bank info.")
#This prints out what a welcome and what will be required in general
p= float(input("What is your principal?"))
r= float(input("What is your annual interest ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.