blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cee60e6eecbeccae9418b46fbc2da768592f62b4 | alexayalamcs/advent | /day3/main.py | 925 | 3.8125 | 4 |
def main(is_part_one=False):
with open('data.txt') as data:
trees = data.read().splitlines()
if is_part_one:
count_num_trees(3, 1, trees)
else:
value = 1
value *= count_num_trees(1, 1, trees)
value *= count_num_trees(3, 1, trees)
value *= count_num_trees(5,... |
94e573e4ace6dec653ee7a5ebeac19252c212af0 | snailQQ/lxf_python | /6_2returnFuntion.py | 2,545 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
# 我们来实现一个可变参数的求和。通常情况下,求和的函数是这样定义的:
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
# 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def sum():
ax = 0
... |
2ffb7ba5e16d3cd40805f7d6ca26e653d9efee87 | Laurens117/programming1 | /Les 9/pe 9_5.py | 566 | 3.59375 | 4 | def namen():
namenlijst = {}
count = 0
naam = input("Geef een naam: ")
while naam!='':
if namenlijst.get(naam):
namenlijst[naam] = namenlijst[naam] + 1
else:
namenlijst[naam] = 1
count = count + 1
naam = input("Volgende naam: ")
for name in n... |
d16e986d47fe22276828285ff0e867c1dfb349ac | furutuki/LeetCodeSolution | /剑指offer系列/剑指 Offer 22. 链表中倒数第k个节点/solution_recursive.py | 804 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def __init__(self):
self.ans = None
def search(self, node: ListNode, k: int) -> int:
if not node:
return 0
val = 1 + ... |
891ab6282c8600c282b5ae8641e86f565a6ed8c8 | teovoinea/First-Year-Assignments | /1MD3/Tutorial 10/Q1_voineat.py | 476 | 4.0625 | 4 | from turtle import *
Screen()
def tree(length, angle, factor, degree):
if degree > 0:
degree = degree - 1
left(angle)
forward(length*factor)
#print(degree)
tree(length * factor, angle, factor, degree)
backward(length*factor)
right(angle * 2)
f... |
1392dcd8ff4c3b9a4c856d6dcaf9c48da7dc5dfc | liuhuipy/Algorithm-python | /search/find-first-and-last-position-of-element-in-sorted-array.py | 1,236 | 3.671875 | 4 | """
在排序数组中查找元素的第一个和最后一个位置:
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
"""
from typing import List
class Solution:
... |
5a4c845bbb0c5f5fa47e602542cf50d77ea955cf | MinneStephanie2/1NMCT4-LaboBasicProgramming-stephanieminne14 | /week2 selectiestructuren/oefening 1.py | 227 | 3.65625 | 4 | getal1 = int(input("geef een geheel getal"))
getal2 = int(input("geef nog een geheel getal: "))
if (getal1 == getal2):
print("getal {0} is gelijk als {1}".format(getal1,getal2))
else: print("de getallen zijn verschillend") |
52c3014111af1f2f63e767543ff570b4bacc1b08 | bose0003/py_files | /closest_number.py | 2,284 | 3.546875 | 4 |
# test_cases = int(input("Enter the number of test cases: "))
# end_result_list = []
# for _ in range(test_cases):
# inputs = input("Enter the 2 numbers to test: ").split(" ")
# diff = abs(int(inputs[0])) - abs(int(inputs[1]))
# quotient = (abs(diff) // abs(int(inputs[1]))) + 1
# if (quotient == 0):
#... |
a5748e806fc0775f7b46af9216be4603e616a003 | affo/ilps-sqpp | /graph.py | 3,131 | 4.0625 | 4 | '''
Generating random Graphs basing on Erdos-Renyi model
https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model
'''
import random
class Graph(object):
def __init__(self, n, p, w=1):
'''
Creates a new `DataStructure` representing a graph
with `n` vertices (labeled... |
295747455091a5d327f2a5cfc6058fc2eb2ea1bc | LuisPatino92/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-load_from_json_file.py | 318 | 3.609375 | 4 | #!/usr/bin/python3
"""This module has the load_from_json_file function"""
import json
def load_from_json_file(filename):
"""Charges the json of and object and returns it"""
jason_str = ""
with open(filename, 'r', encoding='utf-8') as f:
jason_str = f.read()
return json.loads(jason_str)
|
18668aa951cc7fbe3c0d5ee3fe5e193dcd585cdc | Meowmycks/catpass | /catpass.py | 16,377 | 3.71875 | 4 | #! /usr/bin/python3
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from pathlib import Path #to use Linux/OS X's "touch" function on Windows
import json #to hold our passwords
import getpass #to hide user input for entering passwords
import string #to generate new passwords
import random #also to generat... |
b8fc620acc497ca7efea706ea5aaad33118e73f1 | zhangfuli/leetcode | /多进程多线程/多线程打印1~100.py | 660 | 3.578125 | 4 | import threading
import time
def worker():
global count
while True:
lock.acquire() # 加锁
count += 1
print(threading.current_thread(), count)
lock.release() # 操作完成后释放锁
if count >= 99:
break
time.sleep(1)
print(1)
def main():
threads = []
... |
6c55696ee34f816ef75b0990ba7d99cb4e7ba554 | claviering/python-room | /leetcode/841-850/844 比较含退格的字符串.py | 1,293 | 3.734375 | 4 | class Solution:
def backspaceCompare(self, S, T):
string1 = []
string2 = []
for c in S:
if c == "#" and len(string1) > 0:
string1.pop()
elif c != "#":
string1.append(c)
for c in T:
if c == "#" and len(string2) > 0:
string2.pop()
elif c != "#":
st... |
f7f54a72eb680b0aacf404b788ac92d36484563f | JosephThomasOldfield/Python-Challenges | /1passwordcheck.py | 398 | 4.09375 | 4 | '''Create a variable called password.
Check how many letters are in the password,
if there are less than 8 log to the console
that the password is too short. Otherwise log
the password to the console.'''
password = "password"
def passwordChecker(passCheck):
if len(passCheck) >= 8:
print(passCheck)
... |
ddaab9e73804961a4d35ed2a72063b9647d0c387 | dakshinap/Classification-without-regularisation | /utils.py | 581 | 3.53125 | 4 | '''
Created on Sep 22, 2017
@author: dakshina
'''
import os
import os.path
def get_corpus(dir, filetype=".wav"):
"""get_corpus(dir, filetype=".wav"
Traverse a directory's subtree picking up all files of correct type
"""
files = []
# Standard traversal with os... |
da9fb83594cef858912c7bf21fbdd67cd2f9740b | owlove/StructureProgramming | /Lab1/lb1Numb2.py | 223 | 3.515625 | 4 | import math
y = float(input("Write number (y): "))
r = float(input("Write number (r): "))
t = float(input("Write number (t): "))
w = (4 * math.pow(t,3) + math.log1p(r))/(math.pow(math.e,y + r) + 7.2 * math.sin(r))
print(w) |
e5a7fc842a1b0cddceda001f9f394b82aaba4e97 | usman-tahir/python-automation | /chapter-3/magic-eight-ball/magic_eight_ball.py | 593 | 3.671875 | 4 |
import random
def get_answer(answer_number):
if answer_number == 1:
return 'It is certain'
elif answer_number == 2:
return 'It is decidedly so'
elif answer_number == 3:
return 'Yes'
elif answer_number == 4:
return 'Reply hazy - try again'
elif answer_number == 5:
return 'Ask again later'
elif answer_n... |
52704306c661e8f1eff945010f3e0424a4c258f0 | reashiny/python. | /python_beginner/vowel or consonant.py | 541 | 3.671875 | 4 | #-------------------------------------------------------------------------------
# Name: module5
# Purpose:
#
# Author: 16CSE024
#
# Created: 27/02/2018
# Copyright: (c) 16CSE024 2018
# Licence: <your licence>
#------------------------------------------------------------------------------... |
8f0aff11a1e2c88bdf4e64ec1b2fbd5195b423dd | gulcanTeacher/pythonDersMateryalleri | /oo15matrisOrnegi.py | 822 | 3.609375 | 4 | """
ekrana 3x4 matrisi için aşağıdaki gibi bir çıktı verilecek
Çıktı
* * * *
* * * *
* * * *
"""
# i,j=0,0
# deger=""
# while i<3:
# i+=1
# while j<4:
# j += 1
# deger += "* "
# print(deger)
# deger=""
# j=0
"""
ekrana 4x3 matrisi için aşağıdaki gibi bir çık... |
4e24ca94a69d3ffd0e5fd33b35d99e3c83ad3e2c | harshal-jain/Python_Core | /3E3-Swap2NumbersWithOut3rdVariable.py | 208 | 3.875 | 4 | a=input("Enter the first number");
b=input("Enter the second number");
a=int(a)
b=int(b)
print("before swapping a="+str(a)+",b="+str(b) )
a=a+b
b=a-b
a=a-b
print("after swapping a="+str(a)+",b="+str(b) )
|
da3b6e9a49ec2ee0cbac5a6b38d7c881b2d605c7 | benlinhuo/algorithmpy | /sort/mergeSortRecursion.py | 2,027 | 4.09375 | 4 | #!/user/bin/python3
'''
归并排序:
归并排序我们采用递归去实现(也可采用迭代的方式去实现)
一般都是将2个已有序的子序列,合并成一个大的有序序列
https://www.cnblogs.com/chengxiao/p/6194356.html
https://www.cnblogs.com/skywang12345/p/3602369.html
'''
import math;
# 将2个已有序的子序列,合并成一个大的有序序列。需要利用一个和合并后一样大小空间的temp
# leftArr 和 rightArr 必须是有序的才可以
def mergeTwoOrderedArr(leftArr, ... |
aa2c9a2a646356d06671282ed280cafe992dedb7 | DIVYA-BHARATHI/HackerRank | /Python/Basic Data Types/Finding the Percentage/Solution.py | 523 | 3.5 | 4 | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for name in student_marks.keys():
if name == query_name:
marks... |
39c40683770d1e9a45a53cd0e375b62b78345444 | ysmintor/leetcode | /python/0189.rotate-array/rotate-array.py | 709 | 3.6875 | 4 | class Solution:
# 解法有很多,从空间 O(n)开始采用同一思路做到 O(1)的话,需要额外设置变量保存,会变得更加复杂,另外这题有比较多的解法,掌握的话非常不错
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(start:int, end:int, s:List[int]):
while start < end:
... |
c277576ecb8055cae51c8a7828030d971c0ea595 | justinm0rgan/python_work | /chp8/sandwhices.py | 732 | 4.3125 | 4 | # Write a function that accepts a list of items a person wants on a sandwhich.
# The function should have one parameter that collects as many items as the function call provides,
# and it should print a summary of the sandwhich that's being ordered.
# Call the function three times, using a different number of agruments... |
ec7d3469b319ba9d1170aa79ff07f49124224d5e | hamidehsaadatmanesh/ML-Udemy | /simpleLinearRegression.py | 1,135 | 4.03125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
x_train, x_test, y_train, y_test = train_... |
c6bcc5e3ba8ec253d49eebb31bbda92a871792fc | lixiang2017/leetcode | /leetcode-cn/0104.0_Maximum_Depth_of_Binary_Tree.py | 1,244 | 3.84375 | 4 | '''
DFS
执行用时:48 ms, 在所有 Python3 提交中击败了45.03% 的用户
内存消耗:17.3 MB, 在所有 Python3 提交中击败了31.22% 的用户
通过测试用例:39 / 39
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
... |
0816042a2b15d384acf104892f05b837b0ce7907 | vijayjag-repo/LeetCode | /Python/LC_Vertical_Order_Traversal.py | 946 | 3.765625 | 4 | # 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 verticalTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
0b06ccd5e4a798a50535e578bcc42fba255a1aef | kimmyoo/python_leetcode | /ROLLING_SUM/134_gas_station/solution.py | 603 | 3.546875 | 4 | class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
#totalLeft is used to see if we have used up all gas
gasLeft, startIndex, totalLeft = 0, 0, 0
for i in ra... |
e2b4d8b5905a2bca62376db1d4350f51b7dd7290 | poorjanos/Tip-Game | /Utils/data_manipulation.py | 863 | 3.75 | 4 | def score_match(player_tip, match_result):
'''
Compare two tuples and derive scores
'''
player_tip_diff = player_tip[0] - player_tip[1]
match_result_diff = match_result[0] - match_result[1]
# Exact tip
if player_tip == match_result:
score = 3
# Not exact tip ... |
c9bbe4c5436db17e2912ca63fd0f7e65ae48c741 | larmc20/exercicios | /exercicio20.py | 345 | 3.96875 | 4 | """O mesmo professor do desafio 019 quer sortear a ordem de apresentação
de trabalhos dos alunos. Faça um programa que leia o nome dos quatro
alunos e mostre a ordem sorteada."""
#imports
import random
lista = []
for i in range(1,5):
lista.append(str(input(f"Coloque o nome do {i}° aluno: ")))
random.shuffle(... |
57142dd03ef476a273ea480380ae3987db222e25 | zhangqiang1003/python_collect | /LeetCode/two_sum.py | 1,881 | 3.6875 | 4 | # 1. 两数之和
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,
并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
"""
# def two_sum(nums, target):
# # 判断奇偶性
# for data in nums:
# try:
# ret_a = nums.index(data)
# ret_b = nums.index(target - data, ret_a + 1)
# exce... |
64f4160f7cd4a608d9e9347bcbb58c267163a551 | cami-la/python_curso_em_video | /Mundo02:estruturas-de-controle/exercicio-python#043-indice-de-massa-corporal.py | 1,318 | 3.984375 | 4 | from termcolor import colored, cprint
'''
Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:
- IMC abaixo de 18,5: Abaixo do Peso
- Entre 18,5 e 25: Peso Ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Aci... |
b62dcf95286f845fb86aad11b79f9d7c52fdbf48 | moxixmx533/RL_for_logistics | /gym_warehouse/envs/warehouse_objects.py | 4,252 | 3.828125 | 4 | """
Classes for objects in the warehouse, i.e. agents, bins, and staging areas.
"""
import copy
import random
NO_ITEM = 0
class WarehouseObject:
"""
Base class for warehouse object: has position and status.
Agents, bins and staging areas are warehouse objects.
Parameters
----------
data : d... |
ddc4b472bd15fe35ff66dc496403e78c599d36fc | bomor/cracking_the_coding_interview-python_sol | /chapter1/q1_8.py | 351 | 4.09375 | 4 | # 1.8 (A method called "is_substring" is given)
def is_rotation(s1, s2):
if len(s1) == len(s2):
con_s2 = s2 + s2
return is_substring(s1, con_s2)
return False
def is_substring(s1, s2):
return s1 in s2
# Tests
def test_is_rotation():
assert is_rotation("apple", "pleap")
assert not... |
0be3cef2db05f49d3c7ba5472238432d3fcb2fbc | lilyandcy/python3 | /leetcode/findSecondMinimumValue.py | 1,626 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root.left == ... |
01b6cb59c36a70cdc64c67d2cbf1b11a32b801cf | ShashwatVv/Ciphers | /simpleSubEditor.py | 4,832 | 4.28125 | 4 | # Simple Substitution Cipher Editor, http://inventwithpython.com/hacking (BSD Licensed)
import textwrap, string, pyperclip
myMessage = ''
SYMBOLS = ''
def main(useText=None, useMapping=None):
print('Simple Substitution Cipher Editor')
while True:
# Get the text to start editing:
if useText ... |
9da2b9371e601608cb869d9f53d5530b69473be0 | greenfox-zerda-lasers/SzaboRichard | /week-07-home-alone/gyak/exam1.py | 602 | 4.3125 | 4 | # Create a function that takes a list as a parameter,
# and returns a new list with every second element from the orignal list
# It should raise an error if the parameter is not a list
# example: [1, 2, 3, 4, 5] should produce [2, 4]
def evry_second_item_from_alist(data_list):
try:
new_returned_list = []
... |
b4c170e55d456ff8247100a9dc520f2edebd03a0 | n-wbrown/psbeam | /psbeam/contouring.py | 5,603 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Low to mid level functions and classes that mostly involve contouring. For more
info on how they work, visit OpenCV's documentation on contours:
http://docs.opencv.org/trunk/d3/d05/tutorial_py_table_of_contents_contours.html
"""
############
# Standard #
############
i... |
876ee3a679787d6fa10d306e31a9067245e71d71 | rongqingpin/RSI_python | /Lecture3_5_stack.py | 485 | 3.90625 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(s... |
8c4520d00ff071ec73c19d18e84ce275ef7ffeca | coda-nsit/languages | /python/mapFilterReduce.py | 191 | 3.859375 | 4 | # map(function, iterable): returns a
def incrementer(elem):
return elem + 1
x = [2, 3, 4, 5, 6]
print(x)
y = map(incrementer, x)
print(list(y))
z = map(lambda i: i + 1, x)
print(list(z)) |
34077ebdb52af7e601c11993309c547e37f57060 | wbq9224/Leetcode_Python | /Leetcode/21_MergeTwoLists.py | 1,533 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from Leetcode.OtherAlgorithm.ListNode import *
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
... |
f1c30ffe64721a6ff221ef8a7bd7183eb5200220 | lemy12/python_shorts | /guessing_game_one.py | 515 | 4.09375 | 4 | import random
number = random.randint(1,9)
number_of_guesses = 0
while True:
number_of_guesses += 1
guess = int(input("Enter your guess: "))
if(guess > number):
print ("Your guess was too high")
elif(guess < number):
print ("Your guess was too low")
else:
print ("You have gu... |
ec71dfe4ef34c5af61f3ca4bf16391d438bec57e | ZY1N/Pythonforinfomatics | /ch2/2_3.py | 282 | 4.0625 | 4 | #Exercise 2.3 Write a program to prompt the user for hours and rate per hour to
#compute gross pay.
#Enter Hours: 35
#Enter Rate: 2.75
#Pay: 96.25
hours = raw_input('Enter Hours:')
rate = raw_input('Enter Rate:')
hours = float (hours)
rate = float(rate)
print 'Pay:', hours * rate
|
d3d084c470918b9000dc1ac6b6fc81c5e0ec7aa3 | saifeemustafaq/alaTest | /test.py | 3,598 | 3.875 | 4 | dict_A = {}
dict_B = {}
the_Numbers, the_Pure_Num = [],[]
def inputs():
print("How many prefix do you want to give for |OPERATOR A| :")
count_A = int(input())
print("Please input a total of ",count_A," prefix and prices separated by space")
for x in range(0, count_A):
data = input().split(' ')
... |
5745b4a76b259708f09930cdd16daaecb75c1a4a | notfounnd/robot-framework-reportportal | /robot/hello/hello.py | 440 | 3.953125 | 4 | #
# Exemplo de comando para executar o código Python:
#
# Por arquivo: python app.py
#
# Comando 'def' utilizado para criar um método em Python
def welcome(name):
return "Olá " + name + ", bem vindo ao projeto exemplo de Robot Framework!"
# Atribuir retorno do metodo welcome() à variável 'result'
result = we... |
85eda8ec23e734ae2a1cd57bb126e9b7fd66fb96 | jesus-rod/algorithms-python | /trees/path_with_given_sequence.py | 1,459 | 4.0625 | 4 | # Path With Given Sequence (medium)
# Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.
# Sequence: [1, 0, 7] Output: false Explanation: The tree does not have a path 1 -> 0 -> 7.
# Sequence: [1, 1, 6] Output: true Explanation: The tree has a path 1 -> ... |
6aebbba24a473058099622a53f35032e600a1ec7 | 2018hsridhar/Leetcode_Solutions | /leetcode_2451.py | 1,311 | 3.828125 | 4 | '''
URL = https://leetcode.com/problems/odd-string-difference/
2451. Odd String Difference
Complexity
Let W := # words in words
Let K := len(max_word)
Time = O(WK)
Space = O(1) ( IMP ) O() ( EXP )
'''
# TBH, we could make concatenate strings instead ( simplifies problem massively)
# well . . . do append a "-" to help... |
d5eba27bd4afc5f3bd66a566b5a480ba09ed6528 | chenlanlan/leetcode | /Sudoku Solver2 .py | 1,336 | 3.546875 | 4 | class Solution:
# @param {character[][]} board
# @return {void} Do not return anything, modify board in-place instead.
def solveSudoku(self, board):
def isValid(x,y):
tmp=board[x][y]; board[x]= board[x][:y] + 'D' + board[x][y + 1:]
for i in range(9):
if board[... |
fad7292248291f0c8e727c6e4c7328dc0268ce7d | daidai21/read_source_code | /curio/hello2.py | 1,415 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# #############################################################################
# File Name : hello2.py
# Author : DaiDai
# Mail : daidai4269@aliyun.com
# Created Time: 一 3/29 23:46:33 2021
# ##################################################################... |
a7de96249deb0c0831469f119df44104d6d376a0 | dane-piper/ELements-of-Computing-Projects | /CircularList.py | 2,886 | 3.96875 | 4 | import os
class Link(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class CircularList(object):
# Constructor
def __init__(self):
self.first = None
# Insert an element (value) in the list
def insert(self, data):
ne... |
1721273ee26acd5efc5b6e084f073f876eb7691c | kevicao/python | /146. LRU Cache 138 Copy List with Random Pointer.py | 2,681 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[25]:
#https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237
# HashMap will hold the keys and address of the Nodes of Doubly LinkedList .
#And Doubly LinkedList will hold the values of keys.
# In[ ]: in this solution, head and tail is always dummy so... |
d8cea2541557ef2e14d3da306e067fe5ddaefc54 | rsokl/plymi_mod6 | /plymi_mod6/homography.py | 3,850 | 3.546875 | 4 | from typing import Tuple
import numpy as np
__all__ = ["transform_corners"]
def _get_cartesian_to_homogeneous_transform(
p1: Tuple[float, float],
p2: Tuple[float, float],
p3: Tuple[float, float],
p4: Tuple[float, float],
) -> np.ndarray:
"""
Given a set of four 2D cartesian coordinates, prod... |
24daeb37ad5207617e8ee7c88a88087bf279365e | qollomcbizzy/pythonintroduction | /functions.py | 987 | 3.765625 | 4 | def greet_user():
print("Hi User")
print("welcome")
print("start")
greet_user()
print("finish")
# with parameters
def greet_user_with_param(name):
print("Hi", name)
print("welcome")
print("start")
greet_user_with_param("John")
print("finish")
# with more parameters and keyword arguments
# keywo... |
eaa5477f12692ef799360faf224ae90bae0b1903 | chanzer/leetcode | /389_findheDifference.py | 956 | 3.671875 | 4 | """
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
Explanation:'e' is t... |
b3fa98cb406627a86f78af84f352472af9dad86c | daisyzl/program-exercise-python | /TwoDimension/xuanzhuanjuzhen.py | 1,597 | 3.921875 | 4 | #-*-coding:utf-8-*-
'''
螺旋矩阵
题目:https://leetcode-cn.com/explore/learn/card/array-and-string/199/introduction-to-2d-array/775/
先定位两个点,分别是左上x1,y1和右下x2,y2
答案:https://github.com/luliyucoordinate/Leetcode/blob/master/src/0054-Spiral-Matrix/0054.py
思想:https://blog.csdn.net/qq_17550379/article/details/83148050
给定一个包含 m x ... |
396728e33c425fe614564cabf57eed74eed4c727 | YQ-369/Learn-Python | /text.py | 1,252 | 3.875 | 4 | #!/usr/bin/env Python
# coding=utf-8
"""
统计考试成绩
"""
from __future__ import division
def average_score(scores):
"""
统计平均分.
"""
score_values = scores.values()
sum_scores = sum(score_values)
average = sum_scores/len(score_values)
return average
def sorted_score(scores):
"... |
f74def97ccce9fc4b900703ca07bc5ca0e7ac235 | Soundarya0/30-Days-of-Code | /Day 25/Running Time and Complexity.py | 501 | 3.9375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
import sys
def isPrime(n):
if n <= 1:
return False
sqrt_n =math.sqrt(n)
if sqrt_n.is_integer():
return False
for i in range(2, int(sqrt_n) + 1):
if n % i == 0:
return False
... |
df05c981f52fc195310f34e4ab8bedfdd48911ef | LahiLuk/pdsnd_github | /bikeshare.py | 7,991 | 4.1875 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
5493f390a298bd865134612dd6645474f533f3fd | iramgee/PracticingPython | /urllinks2.py | 641 | 3.5 | 4 | import urllib
from BeautifulSoup import *
def get_url_string():
count = 0
url = raw_input('Enter - ')
while count < 7:
print 'Successfully retrieved: ',url, '\n\n'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags =... |
40180c9daef0b4aa661f9a5b9db31b411423c6dc | Cristopher-12/POO-1719110585 | /Semana_8/alumnos.py | 1,512 | 3.921875 | 4 | answer="S" #variable para ayudar al ciclo while
datos = [] #arreglo para ayudar a almacenar los datos
class Alumnos: #creamos una clase
def __init__(self): #metodo constrcutor
pass
def datos(self): #creamos un metodo para perdir datos
name=input("Inseta el nombre del alumno: ") #Pide el no... |
2d763717dacf558805d9d11b671c19a547e5652a | theshevon/A1-COMP30024 | /AStar/helperFunctions.py | 553 | 3.65625 | 4 | #Helper functions
def createBoardSet():
ran = range(-3, +3+1)
CoordSet = set()
for qr in [(q,r) for q in ran for r in ran if -q-r in ran]:
CoordSet.add(qr)
return CoordSet
def AdjacentTiles(coord):
adjacent = []
for p in [-1, 1]:
for r in [-1, 1]:
if(withinBoard(coord[0] +p , coord[1]+r)):
adjacent.a... |
3bca47db97c71d3708676ac1feae81597bc9e756 | nathanbeddes/Project-Euler | /Python/Problem4.py | 1,376 | 4.375 | 4 | #! /usr/local/bin/python3.1
def isPalindrome (candidate):
"""
Determines if the number candidate is a "palindrome" or not.
e.g. 808
"""
strCandidate = str(candidate)
left = 0
right = len(strCandidate) - 1
while (left < right):
if (strCandidate[left] != strCandidate[right]):
... |
bb7d1aab4408caa4096a8822d1b8cab5e0aad832 | smartFox-Rohan-Kulkarni/Python_hacker_rank | /Alphabet Rangoli.py | 1,039 | 3.625 | 4 | import string
from collections import defaultdict
def print_rangoli(size):
# your code goes here
dict_default= defaultdict(list)
num = size
alph = list(string.ascii_lowercase)
for i in range(1, (2 * num - 1) + 1):
for j in range(1, (2 * (2 * num - 1) - 1) + 1):
dict_default[i].... |
898c900f3b5a42eb33a75395ff4dd5b459a3ca65 | CianOSull/Group_Project_2019-2020 | /MediAI/Heart/HeartDiseaseDLN.py | 906 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 12:29:08 2019
@author: Cian
"""
# first neural network with keras tutorial
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
# load the dataset
dataset = loadtxt('heartDataset.csv', delimiter=',')
# split into input (X) and ou... |
c772003df01a1d5ae30cd5eaeac4a3f1348a3339 | R3mmurd/fractals | /game_of_life.py | 1,837 | 3.75 | 4 | """
This module contains an implemetation of the Conway's Game of Life.
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
"""
import sys
import time
import random
from tkinter import Tk, Canvas
GRID_SIZE = 5
SCREEN_SIZE = 1000
NUM_CELLS = SCREEN_SIZE // GRID_SIZE
root = Tk()
canvas = Canvas(root, width=SCREEN_SI... |
6cbde17028ff5f43c411686f35264d7b69a555dd | sanjibm/PyDS | /unique-chars.py | 614 | 4.125 | 4 | # Check if a String is composed of all unique characters
# OPTION 4: Array/list way
# Time: O(n) Space: O(1) but influenced by the list of length 96
def unique_characters_list(input_string):
if len(input_string)>96: # 96 = number of printable chars
return False
chars_list = [False] * 96
for char ... |
14835d7c36fb17113d2ab81505a215cc8e5ac684 | mohanrajanr/CodePrep | /we227/5673.py | 808 | 3.84375 | 4 | def maximumScore(a: int, b: int, c: int) -> int:
turns = 0
while not (((a == 0) and (b == 0)) or ((b == 0) and (c == 0)) or ((a == 0) and (c == 0))):
print(a, b, c, turns)
if a % b == 0:
a -= b
b = 0
turns += a
elif a % b == 0:
b -= a
... |
5a8c9067842ce46ce5ba79bcc97c0c52f2e72438 | riceb53/data-analysis | /prac.py | 781 | 3.734375 | 4 | # with open("/Users/Apprentice/documents/new-york-city-current-job-postings/nyc-jobs.csv") as f:
# # print(f.size())
# index = 0
# for line in f:
# print()
# print(line)
# index += 1
# print(index)
import csv
with open('/Users/Apprentice/documents/new-york-city-current-job-postings/... |
2594ed8e24e50fe68fe651bb2e512cc64bca2643 | BenRauzi/159.172 | /Exam/4.py | 326 | 3.71875 | 4 | count = 0
def sequential_search(the_list, item):
global count
count += 1
if the_list == []:
return False
elif the_list[0] == item:
return True
else:
return sequential_search(the_list[1:], item)
test = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
sequential_search(test, 16)
print(... |
9de9245080c2cca7ada777d567d4e723d197e595 | jay6413682/Leetcode | /Palindrome_Linked_List_234.py | 4,449 | 4 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x, nxt=None):
self.val = x
self.next = nxt
class Solution1:
def isPalindrome(self, head: ListNode) -> bool:
""" 双指针,快慢指针,链表反转 similar to https://leetcode-cn.com/problems/palindrome-linked-list/solution/wo-de-kuai-m... |
6b4eb254466310dcc279694ba6757de1ed0ebb4e | ash1215/ANPR | /Code/VehicleInfo.py | 1,145 | 3.59375 | 4 | import pandas as pd
# vehicle class
class Vehicle:
# constructor
def __init__(self, number):
self.VehicleNumber = number
self.Manufacturer = "Unknown"
self.Owner = "Unknown"
self.Model = "Unknown"
def setManufacturer(self, companyName):
self.Manufacturer = company... |
3cd10ed2ed1362b321e7680a619001e458734d9c | erichrathkamp/BusProblem | /NP Files/output_combiner.py | 1,469 | 3.5 | 4 | import os
import pickle
import sys
class InputError(Exception):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, message):
self.message = message
def ... |
fc2b63ec948254d4c66e08ac634cd12e93da7432 | Joost-Robat/PythonAchievements | /test2.py | 175 | 3.734375 | 4 | #A = input("Wat wil je bij elkaar optellen?\n")
#print(A.format)
#B = input("+\n")
#print(A, "+\n")
#A += B
#print("Het antwoord is:", A)
x = 100
y = 100
x += y
print(x) |
c7739593536ff819851c58af470968eb4bec5ad5 | mcsquared2/peopleSorting | /quickSort.py | 2,154 | 4.15625 | 4 | import random
from debug import *
def quickSort(lst):
# call the recursive quicksort function passing in the the first and last indecies in the list
quickSortR(lst,0,len(lst))
def quickSortR(lst, startIndex, stopIndex):
# if you are only looking at one item in the list, return
if stopIndex-startIndex... |
7573f70f8e0b0145a5f7fce60baa63654751a4df | FireAmpersand/231PythonProjects | /doublesum.py | 230 | 4.03125 | 4 | a = int(input("Enter a number: "))
b = int(input("Enter a second number: "))
if a==b:
sum = 2 * (a+b)
print("The numbers Are the same so here is 2 * the sum: " + str(sum))
else:
sum = a + b
print("The sum is: " + str(sum))
|
33c75df14e8e5469608b04c64dacc77e1a7a8eaa | Hellofafar/Leetcode | /Medium/368.py | 1,879 | 3.921875 | 4 | # ------------------------------
# 368. Largest Divisible Subset
#
# Description:
# Given a set of distinct positive integers, find the largest subset such that every pair
# (Si, Sj) of elements in this subset satisfies:
#
# Si % Sj = 0 or Sj % Si = 0.
#
# If there are multiple solutions, return any subset is fine.... |
9869dfb4a98bfbc7fde79ef045dc21c0fae75738 | mandonuno/phonebook-widget | /frontend.py | 5,427 | 3.953125 | 4 | """
A program that creates a Desktop Application widget
that stores contact information inside database
"""
import tkinter as tk
from backend import Database
database = Database("contacts.db")
class Window:
"""Window class that creates the PhoneBook Widget, formats the display
and calls the instance methods ... |
4a1523769eb5231e2ca84a56f739682ec2266fa5 | kurumiwj/PAT-Advanced-Python | /1136.py | 549 | 3.8125 | 4 | def isPalindromic(s,start,end):
while start<=end:
if s[start]!=s[end]:
return False
start+=1
end-=1
return True
n=input()
cnt=0
flag=True
while not isPalindromic(n,0,len(n)-1):
cnt+=1
n=list(n)
n_reverse=reversed(n)
num1=int(''.join(n))
nu... |
93813a8e5c6a2551fdebf2804b5232045f5529e7 | AnupSrujan/git-github | /sort.py | 599 | 3.859375 | 4 | ex_array = [1,2,4,9,14,81,100]
integer = 5
def insertion_integer(ex_array, integer):
array = []
if integer < ex_array[0]:
array.append(integer)
array += ex_array
elif integer > ex_array[-1]:
array += ex_array
array.append(integer)
else:
for i in range(len(ex_ar... |
090030a7fdb2498e2355a6c8088b0325ed15f850 | juanfdg/JuanFreireCES22 | /Aula3/Problem14_11_1_a.py | 577 | 4.125 | 4 | def merge(xs, ys):
""" merge common elements of sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
# If one of the lists is finished, merge is over
if xi >= len(xs) or yi >= len(ys):
return result
# Both lists still have ite... |
f6841b23defb2b28da299d3a3a1f8f0422a6e1ef | tinkle1129/Leetcode_Solution | /Greedy/435. Non-overlapping Intervals.py | 1,619 | 4.21875 | 4 | # - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Non-overlapping Intervals.py
# Creation Time: 2017/10/12
###########################################
'''
Given a collection of intervals, find the minimum number of intervals you need to rem... |
b3e2f8494a038a8dc9d77f480bbd7416bd6e4c9b | sammitjain/GUI_python | /Tkinter3.py | 336 | 4.0625 | 4 | # Part 3: Basics with Tkinter GUI in Python
# Working with Labels and organizing them
from tkinter import *
root = Tk()
l1 = Label(root,text='L1',bg='red',fg='white')
l1.pack()
l2 = Label(root,text='L2',bg='green',fg='black')
l2.pack(fill=X)
l3 = Label(root,text='L3',bg='white',fg='blue')
l3.pack(side=LEFT,fill=Y)
... |
5fa8e392ba492595db568221c6f5573f312742ac | asdrewq123/learning | /hungry.py | 326 | 4.09375 | 4 | hungry=input("are you hugry")
if hungry=="yes":
print("eat samosa")
print("eat pizza")
print("burger")
print("fries")
else:
<<<<<<< HEAD
print("do your homework")
=======
thirsty=input("are you thirsty")
if thirsty=="yes":
print("drink water")
print("or drik soda")
>>>>>>> th... |
24dae625ac9031a8e56138dc510ad132febccfc1 | VadimSadriev/PythonLearning | /Webapp/files.py | 1,068 | 4.25 | 4 |
# 'r' = opens file for reading, also 'r' is default value so u allowed not to pass it
# 'r' doesnt create file with given name if not exists, other modes create if file with given name dont exist
# 'w' open file for writing, if file have data then data is deleted
# 'a' opens file to append data, does not delete existi... |
49d22768a25992e2608ca9378587f85d9756754e | liuxiang0/turtle_tutorial | /Lesson-6 Speed Change.py | 1,195 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Lesson 6 : 给定速度画螺线图
"""
import turtle
wn = turtle.Screen()
monkey = turtle.Pen() # 初始化乌龟程序,调出图形框,准备好画笔
'''
monkey.shape("turtle") # 改变画笔形状为一只乌龟,缺省是箭头arrow,
# 还可以为 'circle'-圆, 'square'-正方形, 'triangle'-三角形, 'classic'.
wn.bgcolor("red") # lightgreen
monkey.pensize(3) # 改变画笔线宽... |
1e42186eaee5b3c7c64e38bea9896114fe4b6712 | tomviner/raspy-lego | /car.py | 1,897 | 3.625 | 4 | import time
import contextlib
from pin import Pin, ExclusivePin
from utils import sleep
class Car(object):
"""
Control of our lego buggy via left, right and gas pins
"""
def __init__(self):
self.left = ExclusivePin(17, None)
self.right = ExclusivePin(14, self.left)
self.ga... |
f048b50b6474b03be18b6559c753badd081f6cfd | JoshFlack/Tees | /Week_1/wk1 pt2 q1.py | 321 | 4.0625 | 4 | #josh flack 8/7/2020
#which is bigger
#collect to numbers form user
x = int, input("enter first number: ")
y = int, input("enter second number:")
#compare/else if statements
if x > y:
print (x, "is bigger than", y)
elif y > x:
print (y, "is bigger than", x)
else:
print ("both are equi... |
54427709cfa28ab3ddeb9daf9e02dbcab99612b3 | aciorra83/CCBC_Python | /python_practice/Lesson9_Error_Handling.py/How_to_Raise_Exceptions.py | 1,101 | 4.25 | 4 | # as a programmer you can raise errors with the 'raise' keyword
def raise_an_error(error):
raise error
raise_an_error(ValueError)
# import error
import nonexistentmodule
# key error
person = {
'name': 'Rich Brown',
'age': 56
}
print(person["gender"]) # a non-existent key in our dictionary
# type error:... |
90c78a28c6aa2afa3a0389141528408d0cc9acda | SoniaChevli/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py~ | 1,501 | 3.609375 | 4 | #!/usr/bin/python3
from models.rectangle import Rectangle
class Square(Rectangle):
""" Square Class """
def __init__(self, size, x=0, y=0, id=None):
"""
initation of square class
Args:
size (int): size of square
x (int): x number of spaces
y (int): y number of ... |
85f1635d0b5696babef6eac4cc567eebeb365c12 | kylem314/p3-web-error-project | /python/battleshipMain.py | 2,369 | 3.90625 | 4 | from random import randint
import os
#Ship Class
class Ship:
def __init__(self, size, orientation, location):
self.size = size
if orientation == 'horizontal' or orientation == 'vertical':
self.orientation = orientation
else:
raise ValueError("Value must be 'horizont... |
fa6f53497e15c48a7316867d6a2c0b3b5a56dc06 | zuobing1995/tiantianguoyuan | /第一阶段/day11/day10_exercise/pow_sum.py | 282 | 3.921875 | 4 | # 2. 给出一个数n,写一个函数计算:
# 1 + 2**2 + 3**3 + 4**4 + .... n**n的和
def f(n):
# 方法2
return sum(map(lambda x: x ** x, range(1, n + 1)))
# 方法1
# s = 0
# for i in range(1, n + 1):
# s += i ** i
# return s
print(f(3))
|
56b7bd9ef1c9e09f93d083377c5a1b4255d4221a | Vivi-yd/Python-Codes | /Intro_CS_MIT/problem_set_1/problem_set_1.py | 2,036 | 4.40625 | 4 | # Problem Set 1 [Paying off Credit Card Debt] from MIT Intro to CS 6.00
# Name:Vivian D
# Time Spent: 45 mins
#Problem 1, Paying the Minimum
"""
Use raw_input() to ask for the following three floating point numbers:
1.
the outstanding balance on the credit card
2.
annual interest rate
3.
minimum monthly payment rate
... |
2433fe4f8c6fedfbc7a7c2798d1ae6e63da76ddf | kotsky/programming-exercises | /Math/Numbers Of Length N And Value Less Than K.py | 1,359 | 3.84375 | 4 | '''
Given a set of digits (A) in sorted order, find how many numbers of length B are possible whose value is less than number C.
NOTE: All numbers can only have digits from the given set.
Examples:
Input:
0 1 5
1
2
Output:
2 (0 and 1 are possible)
Input:
0 1 2 5
2
21
Output... |
4aff92d60d79203a62c26cd19be53d552cb1551e | gabempayne/file-folder-organizer | /testmkdirv2.py | 1,272 | 4.0625 | 4 | # this program asks which type of files you will be moving #
# it then checks if a directory with that respective name exists #
# if directory does not exist, it then creates said directory #
# and moves all files of that type to that directory #
import os
from os import listdir
from os.path import isfile, join... |
e469a4d428f14279bdba1874876582b420a5e137 | AnanduR32/PythonProgrammingBasics | /union of lists.py | 623 | 3.796875 | 4 | list1,list2,dup=[],[],[]
Nlist1=int(input("Enter the total number of items in list 1"))
Nlist2=int(input("Enter the total number of items in list 2"))
print("Enter the elements of list 1")
for i in range(0,Nlist1):
item=input()
list1.append(item)
print("Enter the elements of list 2")
for i in range(0,Nl... |
a4b7009ca7fe2924e915fed84979af08bd52529e | Emanuelvss13/ifpi-ads-algoritimos2020 | /fabio_2a/Q5_Fa_ordem_crescente.py | 779 | 3.984375 | 4 | def main():
n1 = int(input('Digite o 1º número: '))
n2 = int(input('Digite o 2º número: '))
n3 = int(input('Digite o 3º número: '))
resultado = crescente(n1, n2, n3)
print(resultado)
def crescente(n1, n2, n3):
if n1 < n2 < n3:
return f'A ordem crescente é {n1}, {n2}... |
9a95d95b90b7986be0fd2b1880f83f91bbb69aa1 | clui951/cs168_student | /projects/proj1_chat/basic_client.py | 710 | 3.71875 | 4 | import socket
import sys
from utils import *
ip_arg = sys.argv[1]
port_arg = sys.argv[2]
client_socket = socket.socket()
client_socket.connect((ip_arg, int(port_arg)))
data = raw_input('--> ')
client_socket.send(data)
client_socket.close()
class BasicClient(object):
def __init__(self, address, port):
... |
a59ac6a3e8ce06b5e42f7625adf8e7f730111300 | ConnorMattson/Misc-Scripts-and-Challenge-Solutions | /challengeSolutions/NZPC/2010/nzpc2010h.py | 664 | 3.625 | 4 | # Problem H 2010 - Connor Mattson
n = int(input("Enter the number of pairs: "))
scenario = 1
while n != 0:
people = []
groups = []
for i in range(n):
pair = input("Enter pair {}: ".format(i+1)).split(' ')
people.extend([person for person in pair if person not in people])
groups.append(pair)
for person in pe... |
cbe5f99c9a95a4e3c2ed8ef05b7fbfff8a52380a | Yuhsuant1994/leetcode_history | /solutions/1_linkedlist.py | 2,252 | 3.5625 | 4 | class ListNode(object):
def __init__(self, val=0, next=None):
self.val=val
self.next=next
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
level, current_max=0,0
check_later=list()
if root:
... |
397d1bb2766ce470ca59c9e131a151ddbdb17099 | anjaligr05/TechInterviews | /review/trees/inOSucc.py | 635 | 3.53125 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inOSucc(root, node):
if root==None:
return
print 'root = ', root.val, 'node = ', node.val
if node.right != None:
mn = node.right
while mn:
mnv = mn.val
mn = mn.left
return mnv
else:
succ = None
w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.