blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3495c52cf44f431da3762eabfef7c51ee373dd7a | pks3kor/For_GitHub | /Learn_Python/Python_Training/Batch-2/25_Nov_2017/25_Nov/Exercise3.py | 407 | 3.78125 | 4 | database = [
["Name1",1,"class-1"],
["Name2",2,"class-2"],
["Name3",3,"class-3"],
["Name4",4,"class-4"],
["Name5",5,"class-5"],
]
#~ print database
tmp = input("Please enter Student name::\n")
#~ print tmp
#~ print str(tmp)
#~ if tmp in database[0... |
c5027a8a2e7c599a5e1943111357f9a210adc116 | NilayNaik/CS440-Projects | /AIMazeProject/Strategies/Strategy2.py | 5,678 | 3.625 | 4 | # code implementation of strategy 2
# recalculating A* at each step
from Preliminaries import mazeGenerator, DFS, AStar
def doStrategyTwo(maze,flammabilityRate):
# initialize random starting point for fire
mazeGenerator.initializeFire(maze)
currPosition=(0,0)
maze[0][0]=2
while True:
#first spot ... |
9cde4f3fa3305a4f3cf5181231bfd70d4b08b9ae | abuczynska/informatyka | /python2.py | 618 | 3.5 | 4 | """
Przedmiot: Informatyka
Kierunek studiów: Inżynieria Transportu
Semestr: zimowy
Rok akademicki: 2020/2021
Data (dzień-miesiąc-rok): 08.01.21.
Imię: Aleksandra
Nazwisko: Buczyńska
Numer albumu ZUT: 50409
print (' input x1, y1, x2, y2, x3, y3, xp, yp: ')
x1, y2, x2, y2, x3, y3 xp, yp = map (float, ... |
51f6c37c67219a16f277c920aa353ef7e0a0896a | ribird/Calculator | /calc.pyw | 3,704 | 3.5 | 4 | import tkinter
def clear():
global result
entry.delete(0, len(entry.get()))
result = ''
def backspace():
global result
entry.delete(0, len(entry.get()))
result = result[0: len(result) - 1]
entry.insert(len(entry.get()), result)
def eq():
global result
entry.delet... |
cfc8240ecf12b16aedeaa600258169d63c2b652d | DVampire/offer | /offer_04_01.py | 1,603 | 4.03125 | 4 | # -*- coding:utf-8 -*-
'''
题目:二维数组中的查找
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
'''
class Solution(object):
def func1(self,*args,**kwargs):
'''
思路一:二层遍历,时间并不是最优
'''
nums=args[0]
target=args[1]
for row in nums:
... |
c21cf3cf7d3bb966af688dc837892bbce98f8854 | KevinStoneCode/CS50_2018 | /2018/pset6/vigenere/vigenere.py | 673 | 3.953125 | 4 | from cs50 import get_string
import sys
if len(sys.argv) > 2:
sys.exit(1)
key = sys.argv[1]
if key.isalpha():
key = key.upper()
else:
print("has non-alphabetical character")
sys.exit(1)
pt = get_string("plaintext: ")
print("ciphertext: ", end='')
#print(key)
i = 0
for c in pt:
if c.isalpha():
... |
29fb93d5f423797731b3b9ce324d65a2b1ad7338 | donno/warehouse51 | /breakout/pygamebreakout.py | 2,928 | 3.625 | 4 | """Provides a usage of a game engine for a breakout clone with PyGame."""
import engine
import pygame
import pygame.locals
class PyGameEngine(engine.Engine):
"""Implemnets a frontend for the Breakout engine using pygame."""
def __init__(self, display):
self.display = display
super(PyGameEngin... |
0a7a754fbce22abda893c19648421a39bfddb729 | mehdi-ahmed/using_python_with_databases | /week2/assignments/assignment2.py | 2,579 | 3.6875 | 4 | # https://www.py4e.com/tools/sql-intro/?PHPSESSID=a7e41b5fd19edc948add6b96bb6f28f4
# This application will read the mailbox data (mbox.txt) and count the number of email messages per organization
# (i.e. domain name of the email address) using a database with the following schema to maintain the counts.
# CREATE TAB... |
5fae06b380a0a409dd5278a5c17b05d8dceb8054 | gaeun0516/python_projects | /card_game.py | 689 | 3.921875 | 4 |
class cardChoice:
def choice(self, board, num_list):
while True:
#board는 공백 리스트 num_list는 숫자 리스트
card_1 = int(input())
card_2 = int(input())
#같을 경우
if num_list[card_1] == num_list[card_2]:
board[card_1], board[card_2] = num_list[... |
491a1ad9051ffba9c4b6441d8c47dfcd0b69e425 | xionghhcs/leetcode | /problem_python/p501.py | 845 | 3.515625 | 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 findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
table = dict()
... |
eaf030e59d9b9117dcd739d633b19f69c71c2868 | Easoncer/swordoffer | /leetcode_python/leetcode_39_CombinationSum.py | 846 | 3.71875 | 4 | # encoding: utf-8
'''
@author: liangchi
@contact: bnu_llc@163.com
@software: pycharm
@file: leetcode_39_CombinationSum.py
@time: 2018/4/18 上午11:37
'''
def back(canlist,target, rightlist, res, step):
if sum(rightlist) == target:
#print rightlist
res.append(rightlist[:])
return
for... |
8a3a407c000852b4f62708d0bb5252b57d93ce0b | lydian/craftmanship | /codingFriday/topic2.4-dictionary.py | 4,729 | 3.546875 | 4 | import unittest
class TrieNode:
def __init__(self ):
self.children = {}
def add_child(self, character):
if character not in self.children:
self.children[character] = TrieNode()
def find(self, c):
if self.children == None or c not in self.children:
retur... |
541310fb08f4a638de2f089679fd477bffa76478 | Zahidsqldba07/competitive-programming-1 | /Leetcode/Contests/weekly_194_unique_file_names.py | 3,039 | 3.875 | 4 | # 5441. Making File Names Unique
'''
Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].
Since two files cannot have the same name, if you enter a folder name which is previously used, the system will h... |
0879ca6181237e1072e861d3a6b3b29f3c72d50c | dannyshafer/Dive-Into-Python-Examples | /chapter_2/simple_multiply.py | 196 | 3.75 | 4 | def multiply(num1, num2):
"""multiplies two numbers and returns the product"""
return num1 * num2
if __name__=="__main__":
#write tests here
print multiply(23, 43)
print multiply.__doc__
|
ec39875ac1615210a3877302b11b5484d6e75dcd | AdamZhouSE/pythonHomework | /Code/CodeRecords/2764/60761/260299.py | 209 | 3.859375 | 4 | def maxdiv(num):
if(num<12):
return num
else:
return max(num,maxdiv(num//4)+maxdiv(num//3)+maxdiv(num//2))
t=int(input())
for i in range(t):
n=int(input())
print(maxdiv(n))
|
d3ef776a0ee3e44dbed4c32377f214038e71871d | Eric-Canas/BabyRobot | /VisionEngine/FlattenEmbedding.py | 642 | 3.65625 | 4 | from cv2 import resize, cvtColor, COLOR_BGR2GRAY
INPUT_SIZE = (64, 64)
class FlattenEmbedding:
def __init__(self):
"""
Simple embedding that only transforms the image to grayscale and flattens it.
"""
self.network = None
def predict(self, face):
"""
Returns a f... |
b3d57264a45f82c4fea0d1ce69cb26c8c7180309 | MattDawson2020/Python-basics | /loops/while_loops.py | 306 | 3.75 | 4 | a = 0
#runs as long as a condition is true
while a < 10:
print(a)
a += 1
username = ''
while username != "pypy":
username = input("Enter username:")
#break and continue
while True:
username = input("Enter Username:")
if username == 'pypy':
break
else:
continue |
fbe604a69da2f09a500cc2949c7cccdea440be31 | 2226171237/Algorithmpractice | /字节/子集.py | 975 | 4.25 | 4 | '''
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[ [3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def subsets(self, nums):
"""
... |
c31ce9e20ee76c95e8e8c6b5f7114c1bc588b2f7 | zsh1232/zsh-algrithm | /base/tree/BinaryTreeTargetPath.py | 435 | 3.53125 | 4 | # -*- encoding: utf-8 -*-
# 二叉树的路径
#
def path(root, target):
if root.val == target.val:
return [root]
if not root:
return []
leftPath = [] if not root.left else path(root.left, target)
rightPath = [] if not root.right else path(root.right, target)
finalPath = leftPath if len(left... |
7b18c20081dffccd8ce579e4c400e36e498b8154 | enkumamoto/exercicios-python | /Exercícios - Python.org.br/EstruturaDeRepetição/exercicio 47.py | 1,951 | 3.84375 | 4 | '''
Em uma competição de ginástica, cada atleta recebe votos de sete jurados. A melhor e a pior nota são eliminadas. A sua
nota fica sendo a média dos votos restantes. Você deve fazer um programa que receba o nome do ginasta e as notas dos
sete jurados alcançadas pelo atleta em sua apresentação e depois informe a sua m... |
64e45c997c4d69fae5c8c774bca2bbb1f302fddd | NYCGithub/LC | /wallsAndGates.py | 2,338 | 4.15625 | 4 | from collections import deque
class Solution:
def wallsAndGates(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: void Do not return anything, modify rooms in-place instead.
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an o... |
2a8af839b5fc2f56ae1fe7e75d54b9964c80d145 | Mukesh170293/Python-practice | /combinationsum.py | 465 | 3.625 | 4 | def combinationSum(arr, sum):
ans = []
temp = []
arr = sorted(list(set(arr)))
findNumbers(ans, arr, temp, sum, 0)
return ans
def findNumbers(ans, arr, temp, sum, index):
if(sum == 0):
ans.append(list(temp))
return
for i in range(index, len(arr)):
if(sum - arr[i]) >= 0:
temp.append(arr[i... |
2d13501b7109fbe0823f9521012984be2af6dd6c | dyngq/summary-notebooks-of-postgraduate | /统计学习方法/作业示例代码/Chap2 感知机/Perceptron.py | 1,709 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
class MyPerceptron:
def __init__(self):
self.w=None
self.b=0
self.l_rate=1
def fit(self,X_train,y_train):
#用样本点的特征数更新初始w,如x1=(3,3)T,有两个特征,则self.w=[0,0]
self.w=np.zeros(X_train.shape[1])
i=0
... |
98d72eb6526a841da1692fae0bbdaa1f125ea4cc | wheejuni/algorithm_bootcamp | /연습문제/codility/distinct.py | 245 | 3.671875 | 4 | def solution(array):
if len(array) == 0:
return 0
count = 1
array.sort()
for i in range(len(array) - 1):
if array[i] != array[i + 1]:
count += 1
return count
print(solution([2, 1, 1, 2, 3, 1])) |
67bd60a9b321e6b7ce60dc645a770def80ecf8b4 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/146_rhombus_generator/save4_nopass.py | 601 | 3.78125 | 4 | STAR = '*'
def gen_rhombus(width):
"""Create a generator that yields the rows of a rhombus row
by row. So if width = 5 it should generate the following
rows one by one:
gen = gen_rhombus(5)
for row in gen:
print(row)
output:
*
***
*****
... |
f43da9d3ba827012d0ffe110ea6f0868233cdc09 | misaka-10032/leetcode | /coding/00430-flatten-a-multilevel-doubly-linked-list/solution_bfs.py | 1,172 | 4 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""This is not the solution for this problem.
Hypothetically, the interviewer can ask me to flatten the list in a layered
manner. It seems BFS, but would not require a queue for the optimal solution.
"""
from typing import Optional
class Node:
def __init__(self, val, pr... |
a143028702047dd458a07d988383a3528e1b7bc3 | jberardini/Interview-Cake-Problems | /make_change.py | 1,440 | 3.984375 | 4 | """Reflection: ok, so the main problem is that it's not clear what the underlying
principle is
If you're given 1, then with [1,2,3], there is 1 way to make change: 1
If you're given 2, then there are 2 ways to make change, (1,1) and (2)
If you're given 3, then there are 3 ways to make change, (1, 1, 1), (1, 2... |
2750950ec98f0b9681eda0819ead3de41ed9c52f | laughouw10/LeetCode | /160. Intersection of Two Linked Lists.py | 926 | 3.609375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
curr = headA
a = 0
while curr:
a += 1
cu... |
d2c7a1ae3833dceed8c92c0f583bbb0b046e01fa | rafaelperazzo/programacao-web | /moodledata/vpl_data/14/usersdata/85/4713/submittedfiles/tomadas.py | 205 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CODIGO AQUI
t1= int(input('Digite o valor de t1: '))
t2= int(input('Digite o valor de t2: '))
t3= int(input('Digite o valor |
0a38fa24dcb6ddb50c5052d3aa1c8fbbb11c695e | JaySurplus/online_code | /leetcode/python/168_Excel_Sheet_Column_Title.py | 603 | 3.65625 | 4 | """
168. Excel Sheet Column Title
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
class Solution(object):
def convertToTitle(sel... |
1f823ec6e098cb5f2d12dc0ec2c1fabf2c7cad11 | VitamintK/AlgorithmProblems | /codeforces/edu_round123/a.py | 316 | 3.734375 | 4 | from collections import defaultdict
n = int(input())
for i in range(n):
s = input()
keys = defaultdict(bool)
for x in s:
if x==x.lower():
keys[x] = True
else:
if not keys[x.lower()]:
print("NO")
break
else:
print("YES")
|
540f2c1a9a89c125974d661e8f2cd5aba2034618 | liangxy8/Wordbrain-Solver | /Finally.py | 6,785 | 3.796875 | 4 | #!/user/bin/python
import numpy as np
from numpy import array
import sys
import copy
from sys import argv
class Trie:
def __init__(self):
"""
Initialize your data structure here
"""
self.root = {}
self.word_end = -1
def insert(self, word):
"""
... |
b346c33db20bc58d5e00f30d6283e312e18a70bd | xh91900/GitHubTest | /SpiderTest/MyPython/MyPython.py | 2,402 | 3.625 | 4 | #The Zen Of Python
#import this
#引用包中某个具体的变量或者函数
#from random import randint
#普通引用
#import requests
#response=requests.get("http://www.jb51.net/article/63711.htm","W")
#import BeautifulSoup
#soup=BeautifulSoup.BeautifulSoup(response.text)
#print(soup.findAll('class'))
#print(soup.Name)
#def digui(x):
# if x<1000:... |
b3f8c7ff63eadd607d3c1c3effac002923d8a043 | Isen-kun/Python-Programming | /Sem_3_Lab/15.09.20/prg1.py | 577 | 3.984375 | 4 | s1 = 0
s2 = 0
n = int(input('enter'))
# for i in range(1,n+1): <- for 1 to n
# for i in range(1,n+1,2): <- for 1 to n with steps
# for i in range(n,0,-1): <- reverse loop
for i in range(n):
print(i)
s1 = s1+1
i = 1
while i <= n:
print(i, end=" ") # To print in a single line
s2 = s2+1
i += 1
print... |
775ea3fe8fc1b6a456749e1798a90d0e00fe5f0e | bhukyavenkatamahesh/Mycaptain-AI-codes | /loops.py | 487 | 4.125 | 4 | # Python program to print positive Numbers in a List
# list of numbers
list1 = [12, -7, 5, 64, -14]
num = 0
# using while loop
while(num < len(list1)):
# checking condition
if list1[num] >= 0:
print(list1[num], end = " ")
# increment num
num += 1
# list of numbers
print("\n")
list2 = [12, 14, -9... |
c5d9cfe8cdda4d4fdc98f77221c15bb23da5e100 | green-fox-academy/Angela93-Shi | /week-01/day-4/data_structures/data_structures/telephone_book.py | 478 | 4.1875 | 4 | #Create a map with the following key-value pairs.
map={'William A. Lathan':'405-709-1865','John K. Miller':'402-247-8568','Hortensia E. Foster':'606-481-6467','Amanda D. Newland':'319-243-5613','Brooke P. Askew':'307-687-2982'}
print(map['John K. Miller'])
#Whose phone number is 307-687-2982?
for key,value in map.item... |
2e3f667454b7827d578d3d308273d2eb9564dbe1 | yannhyu/process_text_files | /slice_a_csv_file_into_smaller_ones_grouped_by_a_field.py | 1,224 | 3.546875 | 4 | __author__ = 'rich'
"""
You could use a regular csv reader and writer,
but the DictReader and DictWriter are nice
because you can reference columns by name.
Always use the 'b' flag when reading or writing .csv
files because on Windows that makes a difference in
how line-endings are handled.
""... |
b442c73b0caf2ba5e7c54669baddb04f03987a6d | ytyaru/Python.ColorSpace.Converter.20210606081641 | /src/lch2lab.py | 724 | 3.53125 | 4 | #!/usr/bin/env python3
# coding: utf8
def lch2lab(lch):
import math
l, c, h = lch
if math.isnan(h): h = 0
h = h * math.pi / 180;
return (l, math.cos(h) * c, math.sin(h) * c)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='色空間を変換する。LCh->Lab', formatte... |
905d7a100ce416ffc759a31c8d582732243e28bb | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/1fae892354e44ddb8b572d5cae5dce97.py | 440 | 3.9375 | 4 | def difference(number):
square_of_the_sum = square_of_sum(number)
sum_of_the_squares = sum_of_squares(number)
return square_of_the_sum - sum_of_the_squares
def square_of_sum(number):
numbers = range(1,number+1)
numbers_sum = sum(numbers)
return numbers_sum**2
def sum_of_squares(number):
numbers = squ... |
947e8a3469ea937752b281f1390807f1735a0017 | francosorbello/Python-Can | /algo1.py | 1,631 | 4.0625 | 4 | # Paquete algo1.py
# jue oct 12 13:26:46 ART 2017
# Algoritmos y Estructuaras de datos I
# Funciones de carga de valores
import copy
def input_int( str ):
try:
ingreso=int(float(input( str )))
except:
ingreso=0
return ingreso
def input_real( str ):
try:
ingreso=float(input( str ))
except:
ingreso=0.0
re... |
1e0cb3bce76ab8af08efb1879eee44be5a5601e9 | alias313/Password_Generator | /random_password.py | 973 | 3.953125 | 4 | import random
from string import ascii_letters, digits, punctuation
def rand_passwd(n, mode):
if 4 <= n <= 256 and 0 <= mode <= 2:
choice = {
0: ascii_letters,
1: ascii_letters + digits,
2: ascii_letters + digits + punctuation
}.get(mode)
return "".join([random.choice(choice) for x in range(n)])
el... |
e8aef8673d7a10a7e04b489d0e9d037fd19b5e0a | Paziwaz/exercism | /python/word-count/word_count.py | 251 | 3.625 | 4 | import re
import collections
def word_count(phrase):
words = re.split("[^0-9a-zA-Z']", phrase.lower())
words = list(filter(lambda word: word, words))
words = map(lambda word: word.strip("''"), words)
return collections.Counter(words)
|
1c1560fa584e5ac412e078d93f44bc230f325103 | christiantriadataro/Crash-Course-On-Python | /Week 4/Strings/Creating New Strings/topic.py | 3,075 | 4.9375 | 5 | # In the last video, we saw how to access certain characters
# inside a string. Now, what if we wanted to change them? Imagine you
# have a string with a character that's wrong and you want to fix it, like
# this one. Taking into account what you learned about string indexing,
# you might be tempted to fix it by access... |
8f9a17879be3d089569475fc8430fb45d1d62fd5 | mattpitkin/samplers-demo | /content/downloads/code/createdata.py | 801 | 4.125 | 4 | """
Setup a model and data
"""
import numpy as np
# set the true values of the model parameters for creating the data
m = 3.5 # gradient of the line
c = 1.2 # y-intercept of the line
# set the "predictor variable"/abscissa
M = 50
xmin = 0.
xmax = 10.
stepsize = (xmax-xmin)/M
x = np.arange(xmin, xmax, stepsize)
# de... |
86f9e23873270ff64f73eab88b5932c242eeec95 | Billoncho/SpiralMyName | /SpiralMyName.py | 1,257 | 4.5625 | 5 | # SpiralMyName.py
# Billy Ridgeway
# Prints a colorful spiral of the user's name.
import turtle # Import turtle graphics.
t = turtle.Pen() # Creates a new turtle called t.
t.speed(0) # Sets the pen's speed to fast.
turtle.bgcolor("black") # Sets the background color... |
5d588aa5ccf78b8852080c1e96c24da6dfe8d5d6 | kbrakke/PowerGridSim | /create_use_resources.py | 4,228 | 3.75 | 4 |
class Resource():
def __init__(self, total_supply, start_allocation, capacity_list):
self.total_supply = total_supply
self.start_allocation = start_allocation
self.capacity_list = capacity_list
def initialize_supply(self):
"""place the initial supply of the resource at the sta... |
e37bde9854ff182f66423545b8f35a0b094f9622 | elmundio87/advent_of_code_2020 | /6/answer.py | 673 | 3.734375 | 4 | #!/usr/bin/env python3
inputFile = "input.txt"
with open(inputFile, 'r') as stream:
lines = stream.read().splitlines()\
lines.append("")
# Part 1
groups = []
group = []
for line in lines:
if(line):
group.append(line)
else:
groups.append(group)
group = []
totalQuestions = 0
for group in groups:... |
d08f188288c185bfad575e2735c714a38345eecf | kalyons11/kevin | /kevin/playground/read.py | 419 | 4.125 | 4 | """Quick script to read inputs.
"""
if __name__ == '__main__':
# Read the number of inputs
num_inputs = int(input("How many inputs? "))
assert num_inputs >= 3, "At least 3 please."
print("Enter your {num_inputs} inputs in the following form: inp1 " +
"inp2 ... inp{num_inputs}".format(num_inputs... |
5ff18f840b09808df76f98aaab9b3b90f9893fee | Switch-vov/leet_code | /leetcode/editor/en/[290]Word Pattern.py | 1,720 | 3.96875 | 4 | # Given a pattern and a string s, find if s follows the same pattern.
#
# Here follow means a full match, such that there is a bijection between a lett
# er in pattern and a non-empty word in s.
#
#
# Example 1:
#
#
# Input: pattern = "abba", s = "dog cat cat dog"
# Output: true
#
#
# Example 2:
#
# ... |
6e018c57683805a3255ffd1de2f45f81ab1481d0 | noveljava/study_leetcode | /completed/215_Kth_largetst_elements_in_an_array.py | 294 | 3.5 | 4 | from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
i = len(nums) - k
return sorted(nums)[i]
assert Solution().findKthLargest([3, 2, 1, 5, 6, 4], 2) == 5
assert Solution().findKthLargest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
|
e73d5f36de2531baf9f23ae5a53581d6a0d6d470 | daniel-reich/ubiquitous-fiesta | /fmQ9QvPBWL7N9hSkq_5.py | 159 | 3.796875 | 4 |
def unstretch(word):
term = word[0]
count = 0
for letter in word:
if term[count] is not letter:
term+=letter
count+=1
return term
|
435024f175dd59cba4740e331dd9e07f6fad2679 | rgederin/python-sandbox | /python-code/src/collections/list.py | 2,541 | 4.53125 | 5 | # Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ([])
_list = ['foo', 'bar', 'baz', 'qux']
print(_list)
# Lists Are Ordered
a = ['foo', 'bar', 'baz', 'qux']
b = ['baz', 'qux', 'bar', 'foo']
print(a is b)
# Lists Can Contain Arbitrary Objects
a = [2, 4, 6, 8]
print(... |
289159d3478ce19c1df49b7d1b0a8f3e495fdbdb | souhardya1/Doubly-Linked-List | /Doubly Linked List skeleton.py | 684 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 12 08:49:55 2020
@author: Souhardya
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new... |
2dc5c0b3f995cebed3d49920c1ae16feac75b055 | Hoon94/Algorithm | /Programmers/여행경로2.py | 1,194 | 3.578125 | 4 | visited = []
def dfs(tickets, start):
global visited
for i in tickets:
if i[0] == start and i not in visited:
visited.append(i)
dfs(tickets, i[1])
def solution(tickets):
answer = []
global visited
tickets.sort()
print(tickets)
for i in tickets:
... |
68aec5f289586a1d069a1618c9f6b1c6e06dcd5c | Yao-Ch/OctPYFunDay1AM | /basic6.py | 277 | 3.859375 | 4 | nb = input("Enter an integral number: ")
nb=int(nb)
# > < >= <= == != and
if nb > 100 and nb < 1000:
print(f"{nb} is in the range ]100,1000[ {nb**2}") # 3.6
print(nb,"is in the range ]100,1000[")
else:
print(nb,"is NOT in the range ]100,1000[") |
d1c90e7a638ca9622d5d97f018422b43879a4b35 | smetanadvorak/programming_problems | /leetcode/recursion/1_swap_list.py | 997 | 3.859375 | 4 | # Given a linked list, swap every two adjacent nodes and return its head.
# Input: head = [1,2,3,4]
# Output: [2,1,4,3]
from ListsAndTrees import LinkedList
class Solution:
def swapPairs(self, head):
if not head:
return head
elif not head.next:
return head
else:
... |
23d13c7d848599e8c359a8f0ce8dade8e1ea4bcf | iCodeIN/data_structures | /binary_trees/check_bst.py | 1,202 | 3.9375 | 4 | from binary_tree import BinaryTree
def IsBST(root, min, max):
# shrinking min and max with each recursive calls
# reached end
if root == None:
return True
# outside of min and max bounds
if root.data <= min or root.data >= max:
return False
# min < root.left < root
... |
38918c5a3465cadbbcfd8a15e04154758db50882 | toaa0422/python_leetcode | /leetcode_daily2/getLeastNumbers.py | 670 | 3.75 | 4 | def gerLeastNumbers(arr,k):
return sorted(arr)[:k]
def getLeastNumbers_(arr,k):
if not arr or not k:
return []
sort_list=sorted(arr)
res=[]
for val in sort_list:
res.append(val)
k-=1
if k==0:
break
return res
"""
if not arr or not k:
... |
d738aec15c6a7e00b0b9c497ca2df3838204a822 | Akash5454/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | /Intermediate/Randomized_Quicksort.py | 833 | 3.65625 | 4 | # Randomized QuickSort
def inPlaceQuickSort(A,start,end):
e = time.clock()
if start<end:
pivot=randint(start,end)
temp=A[end]
A[end]=A[pivot]
A[pivot]=temp
p=inPlacePartition(A,start,end)
inPlaceQuickSort(A,start,p-1)
inPlaceQuickSort(A,p+1,end)
... |
1639ef558558e353e29dd7d44d4c236df7ea670c | loushingba/loushingbaPyRepo | /wordCap.py | 566 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 19:26:58 2020
@author: sanathoi
"""
# capitalization of word
string = input("Enter a string: ")
length = len(string)
a = 0
end = length
string2 = ''
while a < length:
if a == 0:
string2 += string[0].upper()
a+=1
elif (string[a]... |
c89c84b0a69d4f20502b8aa70bbea2a91605516c | RenanSouzadeOliveira/Exercicios_for | /Exercicios_for/ex4.py | 172 | 4 | 4 | num = int(input("Entre com o número que você deseja calcular a taboada:"))
r = 0
for x in range(0, 11):
r = num * x
print("{0} x {1} = {2}".format(num, x, r)) |
45819bc34c03831bebde065d71ba0d64ecbbffa6 | bignamehyp/interview | /python/LintCode/BinaryTreeSerializationDeserializatoin.py | 1,788 | 3.984375 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
'''
@param root: An object of TreeNode, denote the root of the binary tree.
This method will be invoked first, you should design your own algorithm
... |
ff6037f73b01d4c7cf2faf862b10f96c31ad98dc | Conorrific/DC-python-2 | /review.py | 548 | 4.03125 | 4 |
#solution 1
number = int(input("Enter a number: "))
#
#def factorial(number):
# count = 1
# while number >= 1:
# count = count * number
# number -= 1
# print(count)
#factorial(number)
result = 1
#solution two
#this solution prints the answer from 15 down to zero
for number in range(number,0,... |
7c66745966652a593b2dbf557c1d2ffa334c581f | kho903/python_algorithms | /Baekjoon/12. 정렬/1181.py | 152 | 3.515625 | 4 | n = int(input())
res = []
for _ in range(n):
res.append(input())
res = list(set(res))
res.sort(key=lambda x: (len(x), x))
for a in res:
print(a) |
be7c6586f081afd77dcc025fff3a7aafc1534dd7 | Yegeun/python-puzzles | /problem2.py | 608 | 3.828125 | 4 | '''
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.'''
n = 0 # start
n1 = 1 # start 1
n3= 0 # end number
exceed= 4000000 # ecxeeds four million change this number for the exceed
num_list = [] #list of all the numbers
while (n3<exceed)... |
55f8447ebe588594495b791e75e3c80b7e7012ec | hoymkot/leetcode | /implement-trie-prefix-tree.py | 1,402 | 4.0625 | 4 | # Leetcode 208. Implement Trie (Prefix Tree)
# https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.next = {};
self.isInserted = False;
def insert(self, word):
"""
... |
0cf02719300a1167bc251b0617b1e9e076bd4887 | npandey15/CatenationPython_Assignments | /Task5_Python/Q3.py | 333 | 3.890625 | 4 | while True:
try:
n =input("Please enter a Number: ")
if len(n)>4 or len(n)<4:
raise ValueError
except:
print("Please length is too short/long!!! Please provide only four digits")
else:
if n==4:
print("Great The Number is acceptable")
... |
4516e68ee66b6605d84c73e0dd137549689213e7 | chadheyne/project-euler | /problem129.py | 469 | 3.703125 | 4 | #!/usr/bin/env python
def divisible_repunit(n, k=1, x=1):
while x:
x = (x * 10 + 1) % n
k += 1
return k
def generate_repunits(limit=1000000):
ns = [limit + 1, limit + 3, limit + 7, limit + 9]
while True:
for n in ns:
if divisible_repunit(n) > limit:
... |
5ff62c12bf3a9d8ec4fd92332e637c779e387ad9 | JanhaviMhatre01/pythonprojects | /paranthesis.py | 1,796 | 4.15625 | 4 | '''
/**********************************************************************************
* Purpose: Ensure parentheses must appear in a balanced fashion.
* @author : Janhavi Mhatre
* @python version 3.7
* @platform : PyCharm
* @since 28-12-2018
*
*************************************************************************... |
154b22b51c170eb12bb2e5ab184c41fbb4e788ab | vsamanullah/hcl_test_exersize | /hcl_portal/CoreLibraries/FileManger.py | 379 | 3.765625 | 4 | '''
system imports
'''
import sys
import os
'''
creates a directory at the given path
'''
def create_directory(directory_path_and_name):
if not os.path.exists(directory_path_and_name):
os.mkdir(directory_path_and_name)
print("Directory ", directory_path_and_name, " Created ")
else:
prin... |
b9c6379723307d7b00f5669c0fdaa688e44331b6 | HannaKulba/AdaptiveTraining_English | /tasks/part_2/simple_list_processing.py | 171 | 3.75 | 4 | array = [int(i) for i in input().split()]
min = array[0]
max = array[0]
for i in array:
if i > max:
max = i
if i < min:
min = i
print(max, min)
|
6906852f1e88c4963718f84d1a0f60c022d8fd46 | vchim/datacleaning_sql | /find.py | 4,875 | 3.5 | 4 | #-*-coding:utf-8-*-
'''
to find duplicated questions
'''
import pandas as pd
def find_question(aset,dataframe):
for know in aset:
# 提取指定知识点的dataframe
df = dataframe[dataframe['how_details_id']== know]
index = df.index
# 寻找重复的题目,return True or False
df_1 = df.duplicated([... |
0a005ccd6de92246d33e474e322bb827561fbdc7 | piri07/PythonPractice | /DSA/binaryQue.py | 4,487 | 3.625 | 4 | #check if the given array can represent preorder traversal of bst
int_min=-99999
def canRepresentBST(pre):
s=[]
root=int_min
for i in pre:
if i<root:
return False
while len(s)>0 and s[-1]<i:
root=s.pop()
s.append(i)
return True
pre1 =... |
785cfce5d36b3f86d4e58ea86b43141120fdd2af | sapnashetty123/python-ws | /labquest/q_1.py | 197 | 4.0625 | 4 | principle = int(input("Enter the amount:"))
rate_of_interest = float(input("Enter the interest:"))
time = float(input("Enter the time in year:"))
print((principle * rate_of_interest * time) / 100 ) |
408e6654d77506281d87e48c51568ab4f30428fb | anicattu7/lesson_1 | /main.py | 675 | 3.859375 | 4 | from smartninja_sql.sqlite import SQLiteDatabase
db = SQLiteDatabase("Student.sqlite")
db.execute("CREATE TABLE IF NOT EXISTS Student (id integer primary key autoincrement, name text, grade text);")
#db.execute("INSERT INTO Student(name, grade) VALUES ('TEENA', 'A');")
#db.execute("INSERT INTO Student(name, grade) VA... |
75f5154f0b1a856636f9927d0873e9e732514e84 | KaustuvBasak26/Python | /functions/reference.py | 260 | 3.84375 | 4 | #!/usr/bin/python
def changeme(mylist):
"This changes a passed list into this function"
mylist.append([1, 2, 3, 4])
print("Values inside the function: ", mylist)
return
mylist = [10, 20, 30]
changeme(mylist)
print("Value outside the function: ", mylist)
|
fd9b4f2254756449af5753826032fc9c8aad3739 | Sahilsingh0808/Project-CUOG | /script.py | 5,569 | 3.546875 | 4 | import pandas as pd
import re
def removeSpaces(str):
return str.strip()
def StringManipulate(str,master,check):
# print(str)
if(check==0): #string starts with number
c1=master[0:2]
c2=master[3:6]
c3=str[0:2]
c4=str[3:6]
c5 = "N/A"
c5No=-1... |
dca485961481b489f4ecf78ebe700458e220b3bc | dltbwoddl/Algorithmuslearning | /동적계획법/make1.py | 468 | 3.578125 | 4 | n=int(input(""))
result=[n]
def make1(n,r):
global result
if r>result[0]:
pass
else:
if n==1:
result.append(r)
if result:
if result[0]>r:
result[0]=r
else:
if n%3==0:
make1(n/3,r... |
6cb2172766882e1e0fd69872824c18d983308a7b | pmazgaj/tuition_advanced | /biblioteki/1 - numpy/zadania_szkolenie/NUMPY_1.py | 2,033 | 4.1875 | 4 | """
ZADANIE:
Narysuj wykres funkcji kwadratowej, przedział <-100, 100> (najlepiej zadany)
Pobierz od użytkownika przedział, w którym ma zostać narysowana funkcja.
Stwórz funkcję, formatującą, zwracającą postać f(x): ax^2 + bx + c
Wyrysuj legendę na ekranie.
"""
from matplotlib import pyplot as plt
def create_funct... |
6dde61d633619608460da552713493d57198b324 | ricardosmotta/python_faculdade | /aula6-exercicio2.py | 1,545 | 3.65625 | 4 | #Jogo Jokenpo (Pedra, Papel e Tesoura)
from random import randint
def valida_int(pergunta, min, max):
x = int(input(pergunta))
while((x < min) or (x > max)):
x = int(input(pergunta))
return x
def vencedor(j1, j2):
global empate, v1, v2
if j1 == 1: # Pedra
if j2 == 1: #... |
e8944f0bc387dac161d88a9bed5e596c608b80dc | miguelzeph/Python_Git | /2019/01_Curso_Geek_basico_avancado/sec 10 - lambda e func integradas/aula11_zip.py | 1,173 | 4.4375 | 4 | """
Zip - cria um interável (zip object)
"""
lista1 = [1,2,3,4,5]
lista2 = [6,7,8,9,10]
zip1 = zip(lista1,lista2)
print(type(zip1))
print(zip1)
print(list(zip1))
zip2 = zip(lista1,lista2,"abcde")
print(tuple(zip2))
# ele mistura os elementos.
#obs: Tem um problema, se você passar os vetores com tamanhos diferente... |
1715e6ddb5ae4fd4f1ab87194e2ef8a286217d7e | JCGSoto/Python | /Parentesis_balanceados.py | 655 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Parentesis balanceados
Los paréntesis están equilibrados, si todos los paréntesis de apertura tienen
sus correspondientes paréntesis de cierre. Este programa devuelve "True", si los
paréntesis en la expresión dada están equilibrados, y False si no.
@author: JCGS
"""
def balanced(... |
3efa3e7158c279b3f92e97118e46ce8ba5d4933f | Soupupup/2018Exam | /python_language_1/rainfall.py | 3,647 | 3.5 | 4 | import numpy as np
import csv
import json
from matplotlib import pyplot as plt
# import csv file
rain_csvFile = 'python_language_1_data.csv'
rain_jsonFile = 'rainfall.json'
# question a.)
# extract and convert daily rainfall depth
# into a dictionary
def read_csv(filename):
# create dictionary
dict = {}
w... |
1792a22a36e4bd8d1cb6db838d16210897dcb871 | Parkyes90/algo | /yg/t3.py | 2,176 | 3.5 | 4 | import random
import time
def timeit(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.6f} seconds")
return result
return wrapper
def remov... |
6bf54865a28d8b7db4658f73e78bc849a03a1bef | MLopezJ/PROYECTO_PROGRAMADO | /PROYECTO PROGRAMADO.py | 1,193 | 3.625 | 4 | diccionario = [["print","imprimir"],["input","Entrada"]]
#the list of the condintionals
conditional=["if","elif","else"]
newConditional=["si","eventualmente","sino"]
#the list of the word reserved
wordReserved=["and","as","assert","break","class","continue","def","del","except","exec","finally","for","from","global"
... |
716a49e260e69a61f581213e629fd5c4cc6b6470 | rlan/LeetCode | /P118-PascalsTriangle/main.py | 1,002 | 3.5 | 4 | #
# LeetCode
# Algorithm 118 Pascal's triangle
#
# Rick Lan, May 5, 2017.
# See LICENSE
#
# Your runtime beats 66.75 % of python submissions.
#
class Solution(object):
def nextRow(self, prev):
"""
:type prev: List[int]
:rtype: List[int]
difference equation: y(n) = x(n)... |
4cd41745f9a5df24bab1ec9e53917233f529f12f | madeibao/PythonAlgorithm | /PartC/Py一个数组中的两个数字等于给定的值.py | 466 | 3.546875 | 4 |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(len(nums)):
x = nums[i]
if target-x in dict:
return (dict[target-x],i)
... |
e9b1f5b8bbeb9068d97bcb24a38b256976cea3c2 | abinofbrooklyn/algos_in_python | /next_permutation.py | 805 | 3.5 | 4 | from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
i = len(nums)-2
while i >= 0 and nums[i+1] <= nums[i]:
i -= 1
if i >= 0:
j = len(nums)-1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
sel... |
0cec2a0c196987be8c835c89e512115ea3037d38 | marlonpodd/assignment5-py-guessing-game | /guessing game.py | 670 | 4.0625 | 4 | #Assignment #5
#Marlon
#Guessing Game.py
import random
number = random.randint(1, 99)
guesses = 0
print("You have 5 guesses to find the number")
while guesses < 5:
guess = int(input("Enter an integer from 1 to 99: "))
guesses +=1
print("You have ", 5 - guesses, " guesses left.")
if ... |
f35fb00170eae113ecfb5c2067e76eab4e418194 | sebastianagomez/Programming-Building-Blocks | /Week 13/prepMaterial_13.py | 611 | 3.90625 | 4 | from datetime import datetime
def printTime(taskName):
print(taskName)
print(datetime.now())
print()
printTime('Sebastian')
# I can use a function, but this time my function returns a value
def getInitial(name, forceUppercase):
if forceUppercase:
initial = name[0:1].upper()
else:
... |
90157468218c41cc620d590730f184fe53b80e8f | RobinSrimal/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/buddymove_holidayiq.py | 1,660 | 3.578125 | 4 | import pandas as pd
import sqlite3
df = pd.read_csv("buddymove_holidayiq.csv")
conn = sqlite3.connect("buddymove_holidayiq.sqlite3")
curs = conn.cursor()
df.to_sql('review', conn, if_exists = "replace")
conn.commit()
curs.close()
curs = conn.cursor()
# counting the rows in review:
query = "SELECT COUNT(*) from... |
d898348a8f52aa55f35613b035ec6ce947bf7d80 | harshildarji/Python-HackerRank | /Collections/Piling Up!.py | 677 | 3.546875 | 4 | # Piling Up!
# https://www.hackerrank.com/challenges/piling-up/problem
r = []
for _ in range(int(input().strip())):
n = int(input().strip())
l = list(map(int, input().split()))[:n]
left, right = 0, n - 1
top = -1
failed = False
while right - left > 0 and failed == False:
if l[left... |
e018af4c561c6031d1432b98675ad7185dd2c2e1 | bingyihua/bing | /help/py/share_safe.py | 456 | 3.640625 | 4 | from threading import Thread, Lock, enumerate
import time
num = 0
mutex = Lock()
def add_num():
global num
for i in range(100000):
mutex.acquire()
num += 1
mutex.release()
if __name__ == '__main__':
t1 = Thread(target=add_num)
t2 = Thread(target=add_num)
t3 = Thre... |
a4afcfd4da068258a8e23af633b0b14191ad3461 | pitero92/Calculator | /calculator_final.py | 3,316 | 3.953125 | 4 | # Simple calculator
from tkinter import *
master = Tk()
display = Entry(master, width=21, justify="right", bg="lightgrey")
master.title("Calculator")
class Calculator:
def __init__(self):
self.var1 = ""
self.var2 = ""
self.result = 0
self.current = 0
self.operator = 0
... |
a00b2392469e27271d097f3a90a64a4105f8bee4 | TFernandezsh/Practica-2-python-tfernandez | /P2/P2-E2.py | 148 | 3.859375 | 4 | print ("Dame los grados en Centígrados")
c = int (input("Grados C: "))
f = int (c * (9/5) + 32)
print ("Estos son los grados en Fahrenheit: ",f) |
e0a3fc041e590ba27539326f86b162b111d1c108 | aasupak/Intro_Data_Sci_Python | /midterm1_python_dev236.py | 336 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 7 20:35:08 2018
@author: aasup
"""
input_test=input("enter some things eaten in the last 24 hours: ")
x=("nuts" in input_test.lower())
y=("seafood" in input_test.lower())
z=("chocolate" in input_test.lower())
print('It is', x,'that', input_test.lower(),'contains "nuts... |
629acd8ac5b9517b02ac38b4bd30861ac46e249d | Gackle/leetcode_practice | /1104.py | 1,355 | 3.6875 | 4 | # coding: utf-8
""" 1104. 二叉树寻路
在一棵无限的二叉树上,每个节点都有两个子节点,树中的节点 逐行 依次按 “之” 字形进行标记。
如下图所示,在奇数行(即,第一行、第三行、第五行……)中,按从左到右的顺序进行标记;
而偶数行(即,第二行、第四行、第六行……)中,按从右到左的顺序进行标记。
给你树上某一个节点的标号 label,请你返回从根节点到该标号为 label 节点的路径,该路径是由途经的节点标号所组成的。
示例 1:
输入:label = 14
输出:[1,3,4,14]
示例 2:
输入:label = 26
输出:[1,2,6,10,26]
"""
class Solutio... |
65b49530b487a99efe2661cde22f4fd71ff6eaaf | kkjeer/infinite-groups | /conditions.py | 11,180 | 4.0625 | 4 | from functions import *
from constants import *
# Represents an expression of type boolean
class Condition:
def __init__(self):
self.wrapParens = True
def __str__(self):
return "Condition"
def wrap(self):
if self.wrapParens:
return "(" + str(self) + ")"
else:
... |
77d38c50a028cb6dc99fe1dfa2760ae973568b1b | jbfddddlbvssssbjdvssssssssssssssssss/Public | /task1.py | 668 | 3.9375 | 4 | import re
str = input("\nInput the string with numbers and words: ")
word = ''.join([i for i in str if not i.isdigit()])
nums = re.findall(r'\d+', str)
nums = [int(i) for i in nums]
print("\nYour string without numbers:", word)
print("\nYour string without words:", nums)
WithLarge = ' '.join(word[0].upper(... |
c26ccbac6c6552bea14e2d6263b294ec360d07af | atom015/py_boj | /14000번/14624_전북대학교.py | 270 | 3.71875 | 4 | n = int(input())
if n % 2 == 0:
print("I LOVE CBNU")
else:
mid_s = 1
front_s = n//2
print("*"*n)
print(" "*front_s+"*")
front_s -= 1
while mid_s+2 <= n:
print((" "*front_s)+"*"+(" "*mid_s)+"*")
mid_s += 2
front_s -= 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.