blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c727aa9bfd09cbb68e1132994a48eab4a74e2cd4 | jp-tran/dsa | /problems/top_k_elements/rearange_string.py | 1,506 | 3.953125 | 4 | import heapq
"""
Given a string, find if its letters can be rearranged
in such a way that no two same characters come next to each other.
Time complexity: O(N * log(N))
Space complexity: O(N)
"""
def rearrange_string(str):
charFrequencyMap = {}
for char in str:
charFrequencyMap[char] = charFrequencyMap.get(... |
510a6747e279df236f68b08edc67d6fd976b4767 | ibinibenny/Sample1 | /ass2_listbims.py | 887 | 4.0625 | 4 | #Write a program to implement all built-in methods of list.
tup=[1,2,3,4,5,6,6,7,7,8,8,9]
print(tup[0])
print(tup[:5])
print(tup[5]+tup[6])
tupl=['hello','HAAI',' spect ']
print(tupl*3)
print('hello'in tupl)
print(len(tup))
print(tupl[1].lower())
print(tupl[0].upper())
print(tupl[0].title())
print(tupl[0... |
f58e32f5773c3231139212a3123691792c0eab5f | DyogoBendo/URI-Python | /iniciante/2779.py | 174 | 3.5 | 4 | if __name__ == "__main__":
n = int (input())
m = int(input())
lista = set()
for i in range(m):
lista.add(int(input()))
print(n - len(lista))
|
3ca377d237c2244084ba29847e790ee2b5deba0e | apuya/python_crash_course | /Part_2_Projects/Project_1_Alien_Invasion/Chapter_13_Aliens/exercise13_2.py | 513 | 3.625 | 4 | # Python Crash Course: A Hands-On, Project-Based Introduction To Programming
#
# Name: Mark Lester Apuya
# Date:
#
# Chapter 13: ALiens!
#
# Exercise 13.2 Better Stars:
# You can make a more realistic star pattern by introducing randomness when you place each star. Recall that you can get a random
# num- ber like this... |
1c12807e0e6e49c24c6212b6c6a9c5d698e5c895 | takayg/algorithm | /Python/Data Structure/Union Find/Union find(class).py | 725 | 3.546875 | 4 | class UnionFind:
def __init__(self,N):
self.parent = [i for i in range(N)]
self.rank = [0] * N
self.count = 0
def root(self,a):
if self.parent[a] == a:
return a
else:
self.parent[a] = self.root(self.parent[a])
return self.pare... |
ef9b6475662f307c1f5fbf24f0f7f8104f9be4e3 | Linuxea/hello_python | /src/basic/bigLoop.py | 66 | 3.53125 | 4 | sum = 0
for x in range(101):
sum += x
print("sum = %s" % sum)
|
cc294369f1bbf48e88e070a6f07952e6abfb0bbe | programmer-anvesh/Hacktoberfest2021 | /BinarySearchTree/sort_arr_to_bst.py | 565 | 3.765625 | 4 | #The main task here is to convert a sorted array into a Balanced Binary Search Tree
'''
Made by: Ansh Gupta(@ansh422)
Date: 03/10/2021
'''
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.val=val
self.left=left
self.right=right
def sortedArrayToBST(nums):
if not nums:
return ... |
18dbba52155a6b2b44c0615573ceedaba5b7ae43 | aikaos/loops | /venv/Flip number.py | 120 | 3.8125 | 4 | # flip numbers
n = int(input("Enter any number: "))
m = 0
while n > 0:
m = m * 10 + n % 10
n = n // 10
print(m)
|
ee610a4257cd6556b089ea082a89fc3b30aaaf98 | chenguiyuan/Leetcode | /1twosum.py | 451 | 3.640625 | 4 | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i, num in enumerate(nums):
if target - num in map:
return([map[target - num], i])
els... |
8143cfade544a1b663f8b7923296418c0ba81897 | jsmith09/ChopATweet | /TweetQueryGUI.py | 3,670 | 3.65625 | 4 | #TweetQueryGUI Class
#Programmed by: Jesse Smith
#Course: CIS225E-HYB1
#Description: GUI driver for ReadTweets, WriteTweets and Query Class.
#This allows a search, get an average, and display tweets
#for a user-searched word in the tweets.txt file.(Improvement for Assignment 5)
import tkinter
from read import ReadTwee... |
7812fef1e15b71cb44e39b2843d4de0f2e1a6b96 | Adamsdurga/Python | /python31.py | 102 | 3.75 | 4 | string = "hello"
c = 0
for i in range (len(string)):
if (string [i]!=''):
c = c+1
print (c)
|
da7ae155d25de771be41cac6c0f0ff2d6854db1d | klq/euler_project | /euler14.py | 1,914 | 3.859375 | 4 | def euler14():
# Problem:
"""
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
... |
ca311cb5fe1cd6063ab2133bbc93e7b5393cad29 | miguel007TMM2/final_mini_project | /crupier.py | 2,465 | 3.71875 | 4 | import os
from cards import Deck
class Crupier():
values_cards_crupier = 0
def __init__(self, deck_of_cards): #Each time the class is called this will be executed by granting the dealer 2 cards
self.deck_of_cards = deck_of_cards
self.cards = self.deck_of_cards.list_of_cards
self.crup... |
15b025c0c7ebfe4ee67d3f479f852d3d372253f6 | Sheretluko/LearnPython_homeworks | /lesson2/11_while_1.py | 366 | 4.0625 | 4 | # Напишите функцию hello_user(), которая с помощью функции input()
# спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо”
def hello_user():
answer = ''
while answer.lower() != 'хорошо':
answer = input('Как дела? ')
hello_user()
|
56a7259e9ec3ae779d563b045859615ac22c4fe3 | backmay/tisco_exam | /test_1.py | 438 | 3.609375 | 4 | input_a = '9876543'
input_b = [
'3467985',
'7865439',
'8743956',
'3456789',
]
def is_same_ditgit_in_same_index(input_a, input_b):
for index in range(len(input_a)):
if input_a[index] == input_b[index]:
print('{} : is Invalid'.format(input_b))
return
print('{} : is... |
cbea2286d9c3d24b5e791fc05f8b393b116092c3 | dsibars/PythonTutorialsAndSamples | /labs/test/friendclass/test_002.py | 1,037 | 3.75 | 4 | import unittest
from labs.Friend import Friend
# EXERCISE:
# Create a new function in friend, that allows you to change the name.
# Tests will check that after changing the name, the salutate method has the new name.
class TestFriend002(unittest.TestCase):
def setUp(self):
self.test_name = 'patata'
... |
0791a9047c221132071e1d2eddc16f5e24c07bf6 | a844810597/python_code | /primary/learn_class/class_turtle_and_fish.py | 4,448 | 3.875 | 4 | import random
# 行走区域
legal_x = [0, 10]
legal_y = [0, 10]
class Turtle:
def __init__(self, name='小乌龟'):
global legal_x
global legal_y
self.__pos_x = random.randint(*legal_x) # 初始化乌龟生成的位置
self.__pos_y = random.randint(*legal_y)
self.energy = 100
self.n... |
1600708d81d73d2077aca5ce1acf27d7ecd4d508 | Basma23/data-structures-and-algorithms-python | /data_structures_and_algorithms/data_structures/stacks_and_queues/stacks_and_queues.py | 2,429 | 3.890625 | 4 | class Node():
def __init__(self, info):
self.info = info
self.next = None
class Stack():
def __init__(self):
self.top = None
self.items = []
def push(self, info):
if self.top == None:
self.top = Node(info)
self.items.append(info)
else... |
3ad3d860bdccbf13d02d48744b1734f6724cafae | nicknii29/first_hirst_painting | /main.py | 1,214 | 3.53125 | 4 | from turtle import Turtle, Screen
import random
timmy = Turtle()
timmy.speed(3)
timmy.hideturtle()
timmy.penup()
timmy.goto(x=-125, y=-125)
screen = Screen()
screen.setup(500, 500)
screen.colormode(255)
color_list = [(238, 246, 244), (249, 243, 247), (1, 12, 31), (54, 25, 17),
(218, 127, 106), (9, 104, 1... |
4eba9d749aa84b4d6e37d2547c4183e1795f3b34 | Sejopc/ScriptingEthicalHackers | /Python/Semana5/user.py | 84 | 3.546875 | 4 | #!/usr/bin/env python3
name = input("Cual es su nombre? \n")
print("Hello,", name)
|
0198675adadf90de44988f4ba7094578b571c1e5 | nambroa/Algorithms-and-Data-Structures | /arrays/M_total_time_covered_by_intervals/algorithm.py | 2,655 | 4.0625 | 4 | """
Given a list of arrays of time intervals, write a function that calculates the total amount of time
covered by the intervals.
For example:
input = [(1,4), (2,3)] return 3
input = [(4,6), (1,2)] return 3
input = {{1,4}, {6,8}, {2,4}, {7,9}, {10, 15}} return 11
QUESTIONS TO ASK (with example answers to guide the so... |
b2861bed82a654da12ab2aee8846b2136dd2fcc5 | globalfranck/banking_interface | /main.py | 3,212 | 4.8125 | 5 | # Bank project
# Creating a menu: new customer, existing customer and exit the program
bank_logo = " -------------------- \n --- Bank and Co. --- \n -------------------- \n "
menu = "1) New customer \n 2) Existing customer \n 3) Exit program \n Enter your choice : "
hyphens = " -------------------- \n"
# Bank data, u... |
56b585c38222657678c3b95cff17beb52bcb17d8 | cypaul85/HelloCoding | /quickSort.py | 388 | 4.0625 | 4 | def quickSort(arr):
if len(arr) < 2:
return arr
else:
pivot = arr[0]
less = [i for i in arr[1:] if i< pivot]
greater = [i for i in arr[1:] if i > pivot]
return quickSort(less)+[pivot]+quickSort(greater)
print(quickSort([10,5,2,3]))
arr = [1,2,3,4,5,6,7,8,9,10]... |
46a9bc3ea75408707f049c3fd25412edfbd935fc | LukasPol/URI_Online_Judge | /python/1005 - Média 1.py | 91 | 3.5 | 4 | A = float(input())
B = float(input())
print('MEDIA = {:.5f}'.format(((A*3.5)+(B*7.5))/11))
|
f922591dbc8d2580959740951a213918d2746113 | santhoshkumar22101999/python-programs-29-01-2020- | /Numberguessing.py | 295 | 3.9375 | 4 | import random
a=int(input("enter a value within 10"))
b= random.randrange(0,10)
if(a==b):
print("winner",a,b)
else:
print("better luck next time")
'''
SAMPLE OUTPUT:
enter a value 2
better luck next time
----------------------------------
enter a value 1
('winner', 1, 1)
'''
|
1392aba8a70102b8e7bdd56f85b83aea6a2875fb | Ziaeemehr/miscellaneous | /ictp_workshop/euler/17.py | 967 | 3.78125 | 4 | #!/usr/bin/env python
from sys import exit, argv
num_dict={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',
7:'seven',8:'eight',9:'nine',11:'eleven',12:'twelve',
13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',
17:'seventeen',18:'eighteen',19:'nineteen',
10:'ten',20:'twenty',30:'thirty',... |
a375c1710040b8cad8ed00f8fb7a9fe600680a7d | shivakrshn49/python-concepts | /bound_vs_unbound_methods.py | 1,584 | 3.765625 | 4 | #https://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object
#Whenever you look up a method via instance.name (and in Python 2, class.name), the method object is created a-new.
#Python uses the descriptor protocol to wrap the function in a method object each time.
#So, when you look up id(C.fo... |
52718d92b2ede7d3662451e04da18a26bb7a383b | signalwolf/Leetcode_by_type | /Facebook习题/dasd.py | 4,336 | 3.8125 | 4 | class LinkedListNode(object):
def __init__(self, key, count):
self.count = count
self.key = [key]
self.prev = None
self.next = None
class AllOne(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.count = {}
se... |
10ce42e1d632f53facf32c950a45b7cc10a97341 | pyplusplusMF/202110_68 | /_68semana05clase15Numpy.py | 3,202 | 3.734375 | 4 | # clase miercoles 2 de junio
# linea de comando para instalar numpy
# py -m pip install numpy (conda) (En windows)
# https://numpy.org/install/
import numpy as np
arreglo = np.array([1,2,3])
print (arreglo) # [1 2 3]
arreglo1D = np.array ( [1, 2, 3] )
print ('arreglo1D = ', arreglo1D) # [1 2 3]
print ('type = ',... |
552143bf089381f164f484f27167500f3148a99f | EugeneBad/Office_Space_Allocation | /PERSON/fellow_test.py | 1,018 | 3.625 | 4 | import unittest
from PERSON.person import Person, Fellow
class FellowTest(unittest.TestCase):
def setUp(self):
self.in_fellow = Fellow('Scott', 'Y')
self.out_fellow = Fellow('Aretha', 'N')
def test_Fellow_inherits_Person(self):
self.assertTrue(issubclass(Fellow, Person), msg='Fellow ... |
3c8bdfe4f883e137f0e79ba5042d6e7debcc63ae | homeworkofgit/gitdemo | /cal.py | 169 | 3.890625 | 4 | #calculator created by Gat Jiarui
a=int(input())
b=int(input())
x=input()
if(x=='+') print(a+b)
if(x=='-') print(a-b)
if(x=='*') print(a*b)
if(x=='/' and b!=0) print(a/b)
|
7941990da85aebcaaeed452c3be51ec0c3077cb0 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/303.py | 1,182 | 4.40625 | 4 | """
Problem:
Given a clock time in hh:mm format, determine, to the nearest degree, the angle between
the hour and the minute hands.
Bonus: When, during the course of a day, will the angle be zero?
"""
HOUR_ANGLE = {
1: (1 / 12) * 360,
2: (2 / 12) * 360,
3: (3 / 12) * 360,
4: (4 / 12) * 360,
5: (... |
25877630b3fa068a15946cea4692a619b17a900c | cybo-neutron/DS-and-Algo | /BinarySearch/ugly_number_iii.py | 642 | 3.53125 | 4 | import math
def lcm2(a,b,c):
return (a*lcm(b,c))//math.gcd(a,lcm(b,c))
def lcm(a,b):
return (a*b)//math.gcd(a,b)
def check(n,a,b,c,m):
num=0
num=m//a + m//b + m//c - m//lcm(a,b) - m//lcm(b,c) - m//lcm(a,c) + m//lcm2(a,b,c)
return num>=n
class Solution:
def nthUglyNu... |
611ac587fdb32648bd10eeb7f90013671344fdd3 | gitHirsi/PythonNotes | /001基础/015lambda表达式/04列表内字典数据排序.py | 608 | 4.0625 | 4 | """
@Author:Hirsi
@Time:2020/6/9 20:49
"""
students = [
{'name': 'DD', 'age': 20},
{'name': 'CC', 'age': 30},
{'name': 'BB', 'age': 18},
{'name': 'AA', 'age': 21}
]
# sort(key=lambda... , reverse=bool)
# name key对应的值 升序排序
students.sort(key=lambda x: x['name'])
print(students)
# name key对应的值 降序排序
stu... |
01933effba34a27fc9b06f397f2f65be18b7e5c2 | RyanKruegel/FileDialogDemo.GUI | /filedialogdemo.py | 1,240 | 3.6875 | 4 |
"""
Program: filedialogdemo.py
Author: Ryan K
Date: 10/19/20
"""
from breezypythongui import EasyFrame
import tkinter.filedialog
class FileDialogDemo(EasyFrame):
# demonstrated the use of a file dialog.
def __init__(self):
# sets up the window and the widget
EasyFrame.__init__(self, title = "F... |
c3c549d68da0db3fb06ac40b718d0a46d66b5298 | Adasumizox/ProgrammingChallenges | /codewars/Python/3 kyu/MakeASpiral/spiralize_test.py | 1,374 | 3.53125 | 4 | from spiralize import spiralize
import unittest
class TestMakeASpiral(unittest.TestCase):
def test(self):
def solution(size):
if size == 1:
return [[1]]
spiral = []
# Fill top row with '1's and rest with '0's
for i in range(size):
... |
b4cfe73b139d6af0f9305b2c420566fac84fc9ff | dixitomkar1809/Coding-Python | /GFG/String/removeAdjacentDuplicatesString.py | 1,354 | 3.65625 | 4 | # Author: Omkar Dixit
# Email: omedxt@gmail.com
'''
Given a string s, recursively remove adjacent duplicate characters from the string s. The output string should not have any adjacent duplicates.
'''
# Time Complexity: O(n)
class Solution:
def removeDups(self, s, lastRemoved):
if len(s) == 0 or len(s) == ... |
7baae670f50e97f5cd03300a53d66251c501e96b | varshachary/MyPracticeProblems | /unique_n_integers_add_upto0.py | 355 | 3.609375 | 4 | """
Given an integer n, return any array containing n unique integers such that they add up to 0.
#leetcode
"""
class Solution:
def sumZero(self, n: int) -> List[int]:
arr=list(range(1,n))
return arr+[-(sum(arr))]
"""
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-... |
ed9822e4abe55ae42bdcade9ab12e349e008893f | toshihikoyanase/optuna | /optuna/_hypervolume/hssp.py | 1,667 | 3.5 | 4 | from typing import List
import numpy as np
import optuna
def _solve_hssp(
rank_i_loss_vals: np.ndarray,
rank_i_indices: np.ndarray,
subset_size: int,
reference_point: np.ndarray,
) -> np.ndarray:
"""Solve a hypervolume subset selection problem (HSSP) via a greedy algorithm.
This method is a... |
5f94a72331002185e23a3a0839954e6865cc2744 | SurajPatil314/Leetcode-problems | /shortestcompletingword.py | 1,657 | 4.125 | 4 | '''
Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate
Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word.
It is guaranteed an answer exists.... |
72657c084eb68561cfda42a8c1920ddb0e04801c | jgam/hackerrank | /sorting/bubblesort.py | 611 | 3.546875 | 4 | def countSwaps(a):
num_swap = 0
if a == sorted(a):
print('Array is sorted in', num_swap, 'swaps.')
print('First Element:', a[0])
print('Last Element:', a[-1])
return 0
else:
for i in range(1,len(a)):
for j in range(len(a)-i):
if a[j] > a[j+... |
47de073c40eecb3a1fadf8ee409193ba4b989092 | Dawrld/student-python-introduction-qadr98 | /loops-for/arrayLoop.py | 101 | 3.515625 | 4 | def insert_squares(arr, num):
arr1 = arr + [i ** 2 for i in range(1, num + 1)]
return arr1
|
d076b02566d759ffb6124532e0909deea51fbf39 | serdaraltin/Freelance-Works-2020 | /202003161131 - alaca (Java - Soru-Cevap)/example-code/advent_of_code_2018-master/estomagordo-python3/1b.py | 250 | 3.53125 | 4 | def solve(d):
count = 0
reached = set([0])
while True:
for line in d:
count += int(line)
if count in reached:
return count
reached.add(count)
with open('input_1.txt') as f:
data = [line.rstrip() for line in f]
print(solve(data)) |
49bc0217670a611c8a049f587f8dd0a215b6145d | lancekindle/pysolation | /RobotBoard.py | 6,815 | 3.84375 | 4 | import Game
import random
import BoardAnalyzer
class RandomBot(object):
""" controller for any non-humanControlled playing tokens. Using a board-representation, it can decide where
to move, and what tiles to remove. Calls to the RandomBot must be made for each moving-or-removing turn. Future
inheriting cla... |
8491effdf9af4f995f507106744610a6d256709f | shankar-jasti/AIND | /Sudoku/solution.py | 5,418 | 3.640625 | 4 | assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(A, B):
return [s+t for s in A for t in B]
boxes = cross(rows,cols)
row_units = [cross(r, cols) for r in rows]
col_units = [cross(rows, c) for c in cols]
diag_units = [[m+str(n) for m,n in zip(rows,cols)],[m+str(n) for m,n in zip(rows,cols[::-1])]]
squa... |
7d75401857437af4eb57a927645de55bdcf40936 | jasonsahl/UGAP | /igs/threading/channels.py | 1,806 | 3.890625 | 4 | ##
# Channels provide a means of communicatin between threads
from Queue import Queue
class Channel:
"""
A channel is a unidirectional form of communication between threads.
A channel allows for the following actions:
send - Send an object over the channel
sendError - Sends an error, the ob... |
1be18deb0efcc552010a944cd8aeb1301ecac7bb | alebreux/iot | /moteur2.py | 1,038 | 3.5 | 4 | import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
Motor1A = 16
Motor1B = 18
Motor1E = 22
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
print ("Going forwards")
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
... |
cd858b51e939cde7ea878deae2077f7030a09706 | peng00bo00/optlearningcontrol | /Project/infrastructure/sumtree.py | 1,951 | 3.5625 | 4 | import numpy as np
class SumTree:
"""
A sum-tree data structure for prioritized replay buffer.
"""
def __init__(self, capacity):
"""
Initialize sum-tree with given capacity.
"""
## self.data is used to store data
self.data = np.zeros(capacity, dtype=object)
... |
80da32d74fe931426b1e9297724d93f47c256c4c | PedroLSF/PyhtonPydawan | /6b - CHALLENGE ADV/6.2.3_MoreFrequentItem.py | 449 | 3.875 | 4 | # We have a conveyor belt of items where each item is represented by a different number.
#We want to know, out of two items, which one shows up more on our belt
def more_frequent_item(lst, item1, item2):
new_lst1 = lst.count(item1)
new_lst2 = lst.count(item2)
if new_lst1 >= new_lst2:
return item1
else:
... |
25d4b161df40ed5b5b375140f97b72fc51b08596 | koder-ua/python-classes | /examples/rational_3.py | 1,001 | 3.53125 | 4 | def nod(x, y):
x = abs(x)
y = abs(y)
return _nod(max(x, y), min(x, y))
def _nod(x, y):
if y == 0:
return x
return nod(y, x % y)
class BasicRational(object):
"basic rational number"
def __init__(self, num, denom):
self.num = num
self.denom = denom
def __add__(s... |
af7c4f92decc61a9a69565593923c87926d36f3d | HarryKT/LCD-Display | /example/single_custom-4-bit.py | 745 | 4.09375 | 4 | ## PRINTING A SINGLE CUSTOM CHARACTER
'''
Take a look at this code, which prints a single smiley face character to the display:
'''
from RPLCD import CharLCD, cleared, cursor # This is the library which we will be using for LCD Display
from RPi import GPIO # This is the library which we will ... |
b66882851b3f8d42c3b6e3b49d20c7715f6844a8 | wupai/myFirst | /judgeprime.py | 554 | 4.03125 | 4 | '''
题目:判断101-200之间有多少个素数,并输出所有素数。
程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,
则表明此数不是素数,反之是素数。
'''
import math
def jdprime(n):
for i in range( 2, int(math.sqrt(n)+1)):
if n%i==0:
return False
return True
sum=0
for i in range(1,200+1):
if jdprime(i):
sum+=1
print('%6d'%i, e... |
46a4df21932f5b4499c0335698fd6dc024bc7b7c | dbahsa/python_algoBunch | /tri_selection/main.py | 954 | 3.953125 | 4 | import random
# tri par sélection
# l = [5, 8, 1, 4]
# V
# [1, 5, 8, 10, 2]
# sorted / unsorted
# V
# [1, 2, 5, 8, 10]
# V
# [1, 2, 5, 8, 10]
# O(N^2)
# print("UNSORTED:", l)
# generate_random_list(n, min, max) 3, 0, 10 [7, 10, 5]
# selection_sort(l)
def generate_random_list(n, min, max):
l... |
723b762f929afe151eed62520cf91b4063846a24 | jmnelmar/LeetCodeChallengues | /Python/PlusOne.py | 1,555 | 4 | 4 | '''
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, e... |
977884ee193e0d6a43ab9dfd82cc4cd9caae757d | mhiro216/atcoder_abc_python | /abc/162_C.py | 229 | 3.8125 | 4 | """
gcd(a,b,c) = gcd(a, gcd(b,c))
"""
K = int(input())
from math import gcd
ans = 0
for i in range(1,K+1):
for j in range(1, K+1):
for k in range(1, K+1):
ans += gcd(i, gcd(j,k))
print(ans) |
e3f4e2950867374e895f78e47644d147c43e98d7 | robsonshockwave/poo-python | /algoritmos_sort/bublue_e_quick.py.py | 2,150 | 4.15625 | 4 | # -*- coding: utf-8 -*-
from random import randint
from random import seed
import timeit
import time
#Implemente uma função que receba uma lista de inteiros e ordena essa lista utilizando o Bubble Sort
def bubblesort(l):
for _ in range(len(l)):
for j in range(len(l) - 1):
if l[j] > l[j+1]:
l[j], l[... |
0313ffe8611cbca38c4f3ae829a5e57465aa7c21 | WangYoudian/Useful-Toolkit | /A算法竞赛问题/模拟除法.py | 864 | 3.828125 | 4 | # 立华奏在学习初中数学的时候遇到了这样一道大水题:
# “设箱子内有 n 个球,其中给 m 个球打上标记,设一次摸球摸到每一个球的概率均等,求一次摸球摸到打标记的球的概率”
# “emmm...语言入门题”
# 但是她改了一下询问方式:设最终的答案为 p ,请输出 p 小数点后 K_1 到 K_2 位的所有数字(若不足则用 0 补齐)
def fastPower(base, power, MOD):
res = 1
while power > 0:
if power&1:
res = res*base%MOD
power >>= 1
base... |
fe74fa4ce8cc10ece9323dfffe45cd395119feeb | 18sg/recipeGrid | /recipeGrid/generator/serves.py | 199 | 3.59375 | 4 | import re
serves_regex = re.compile("(serves?|for|makes) (?P<num>\d+)")
def interpret(english):
match = serves_regex.search(english)
return int(match.group("num")) if match is not None else None
|
1ac8cbf6e3b872651909839822fcdb923bb3349f | ahdahddl/cytoscape | /csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/tags/rs_Python_Pack090515/General_Packages/Data_Struct/ListList.py | 2,692 | 3.71875 | 4 | #!/usr/bin/env python
class ListList:
def __init__(self, ilists = None):
if ilists is None:
self.slists = []
else:
self.slists = ilists
def add_list(self, ilist):
self.slists.append(ilist)
def add_lists(self, ilists):
self.slists += ilists
def empty_list... |
99020ae9a2442bf65129790a4d58b5184b75e9c9 | beddingearly/LMM | /125_Valid_Palindrome.py | 649 | 3.953125 | 4 | # coding=utf-8
import string
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# s = s.translate(string.maketrans("",""), string.punctuation) # 去标点符号
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in... |
0f83d07991ff8835c6697d499e9971c86ac3eb36 | hhongjoon/TIL | /etc/pycharm/day2_problem/min_max.py | 643 | 3.515625 | 4 | import sys
sys.stdin = open("sample_input.txt")
def min_max(data, a, z):
if a < z :
copy = list(data)
mid = int(a + z)/2
# min_max(copy[:mid+1],0,mid)
# min_max(copy[mid+1:],mid+1,len(copy)-1)
min_max(copy, 0, mid)
min_max(copy, mid + 1, len(copy) - 1)
mer... |
efbe07cfed9320597ebf131ae146d11817e8c419 | LoboCgv/Tutorial-Python | /PruebaPython/Mascota.py | 294 | 3.625 | 4 | class Mascota:
def __init__(self,raza,nombreMascota,peso,color):
self.raza=raza
self.nombreMascota=nombreMascota
self.peso=peso
self.color=color
def __str__(self):
print(self.raza+" "+self.nombreMascota+" "+str(self.peso)+" "+self.color)
|
b5293f52e17755bc070840491a345fa9451dd79f | Chandler/planet_app | /utils/create_tables.py | 1,422 | 3.71875 | 4 | import sqlite3
from os import sys
# use as a script:
# python utils/create_tables.py planet.db
def create_tables(db_name):
conn = sqlite3.connect(db_name)
# "userid" comes from the specification
# if this project were continued I would probably
# switch it out for uuid "user_id" and a user defined
... |
f4b55ff90ad210ceaefe26c0d93446993381f8ac | challeger/leetCode | /每日一题/2020_10_04_两数相加.py | 1,290 | 3.59375 | 4 | """
day: 2020-10-04
url: https://leetcode-cn.com/problems/add-two-numbers/
题目名: 两数相加
给出两个 非空 的链表用来表示两个非负的整数.
其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字.
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和.
您可以假设除了数字 0 之外,这两个数都不会以 0 开头.
思路:
同时遍历两个链表,定义一个进位carry来判断下一次相加是否需要进位即可
"""
class ListNode:
def __init__(self, x):
... |
23a31ed469a1bee059f5572478fa9e09876a7b38 | Jan-zou/LeetCode | /python/String/67_add_binary.py | 883 | 3.828125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Description:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Tags: Math, String
Time: O(n)
Space: O(1)
'''
class Solution(object):
def addBinary(self, a, b):
... |
37d959edf740464ebade95b257fdc78945b2a1d9 | shubhamgg1997/pyspark | /excersise/list.py | 262 | 3.546875 | 4 | '''Write a program which take a list of list and give result of
# all list'''
from pyspark import SparkContext
sc = SparkContext("local", "list app")
list1=[[1,2,3],[4,5,6],[7,8,9]]
list2=sc.parallelize(list1)
list3=list2.reduce(lambda x,y: x+y)
print(list3)
|
49c5e9b6859f86f8101f965e3365dfbfbd9cafcb | lfteixeira996/Coding-Bat | /Python/List-2/sum67.py | 907 | 3.90625 | 4 | import unittest
'''
Return the sum of the numbers in the array, except ignore sections of numbers
starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7).
Return 0 for no numbers.
sum67([1, 2, 2]) -> 5
sum67([1, 2, 2, 6, 99, 99, 7]) -> 5
sum67([1, 1, 6, 7, 2]) -> 4
'''
def sum... |
13c6d7124de8b0e3d261fded9113266911c9a0ee | TrevorBagels/nomorediscordcreeps | /dev/program/utils.py | 1,850 | 3.640625 | 4 | from datetime import datetime, timezone, timedelta
def now() -> datetime:
return datetime.now().astimezone(timezone.utc)
def long_ago() -> datetime:
return datetime(1990, 1, 1).astimezone(timezone.utc)
def hms(seconds):
"""Returns h:m:s from seconds
"""
seconds = seconds % (24 * 3600)
hour = seconds // 3600
s... |
e9cc5eb16fd308d1f904bc6efc6541277120ebc3 | AlonsoDo/ensayosenpython | /EjemplosNivelMedio/ejercicio1.py | 222 | 3.734375 | 4 | #!/usr/bin/env python
anchura = int(input("Anchura del rectangulo: "))
altura = int(input("Altura del rectangulo: "))
for i in range(altura):
for j in range(anchura):
print("* ", end="")
print()
|
0fda81fbc2fc4911bfbfd19a846370c5a6ed9555 | skinder/Algos | /PythonAlgos/Done/Kth_Largest_Element_in_an_Array.py | 797 | 4.09375 | 4 | '''
https://leetcode.com/problems/kth-largest-element-in-an-array/
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: ... |
88839bbb94816f1d470c06dfae72fe0890903dc8 | justinba1010/CSCE557 | /proj3-retry/point.py | 3,855 | 4 | 4 | """
Justin Baum
21 October 2020
point.py
Points on an elliptic curve
"""
from utils import multiplicative_inverse as m_inv
class Point:
"""
Point Module
Represents points in affine form on some curve
"""
def __init__(self, x, y, curve):
"""
Construct a point on some curve
"... |
b0d276a316f8f383bf55f81dcfe4ed2f83b391d5 | rafaelperazzo/programacao-web | /moodledata/vpl_data/22/usersdata/71/11766/submittedfiles/av1_2.py | 187 | 3.890625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a=input("a: ")
b=input("b: ")
c=input("c: ")
d=input("d: ")
if a==c or b==d:
print("V")
else:
print("F")
|
fd5c82689e02b697f9ab341c7c0c5057e04b75e5 | Cccmm002/my_leetcode | /378-kth-smallest-element-in-a-sorted-matrix/kth-smallest-element-in-a-sorted-matrix.py | 1,073 | 3.875 | 4 | # -*- coding:utf-8 -*-
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
#
# Example:
#
# matrix = [
# [ 1, 5, 9],
# [10,... |
068ceb20671a7d62204d40ef4e6eac177744a136 | lim1202/LeetCode | /Dynamic Programming/unique_paths.py | 3,056 | 4.15625 | 4 | '''Unique Paths'''
# Unique Path
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time.
# The robot is trying to reach the bottom-right corner of the grid
# (marked 'Finish' in the diagram below).
# How many... |
c46c0f32d0ba6590200f8f09a54a7e8b345ccc83 | flfelipelopes/Python-Curso-em-Video | /ex039.py | 1,630 | 4.03125 | 4 | #Um programa que leia se uma pessoa está na idade de alistamento militar ou não,
#se já está em tempo de se alistar ou se já passou da época de alistamento.
from datetime import date
atual = date.today().year
print('X'*10, '{}ANALISADOR DE ALISTAMENTO MILITAR{}'
.format('\033[1m', '\033[m'), 'X'*10)
print('')
p... |
0ca9f2ce8c1a06349351b878e590a57d2f01965f | dshinzie-zz/exercism | /python/pig-latin/pig_latin.py | 529 | 3.53125 | 4 | def translate(word_list):
words = []
for word in word_list.split():
if word[0:3] in ['squ','thr','sch']:
words.append(word[3:] + word[0:3] + "ay")
elif word[0:2] in ['ch','qu','th']:
words.append(word[2:] + word[0:2] + "ay")
elif word[0:2] in ['yt', 'xr']:
... |
a87dd3e4a1ce10f98b87db1c7c96fb970ca0f459 | kemingy/daily-coding-problem | /src/reduce.py | 974 | 3.921875 | 4 | # reduce (also known as fold) is a function that takes in an array, a combining
# function, and an initial value and builds up a result by calling the
# combining function on each element of the array, left to right. For example,
# we can write sum() in terms of reduce:
# def add(a, b):
# return a + b
# def sum(l... |
dedd0012be11d9185387662f52fe6562ea9286ec | harrisrf/IAB_SA_EM | /sample_rotation.py | 2,320 | 4 | 4 | import sqlite3
import sys
#Create our in-memory database object
db = sqlite3.connect(':memory:')
#Iterator to pull in the necessary data
def importer(yyyymm):
with open('D:\\Users\\F3879852\\Documents\\Telmar\\Demographics\\data_demo_c1_' + str(yyyymm) +'0100_30') as demo:
for line in demo:
y... |
ce73aaecebce0fa506dcec0ba2bab70601d7785d | somasan/projectone | /three/three9.py | 427 | 3.9375 | 4 | import turtle
import math
turtle.shape('turtle')
def oct(n, R):
turtle.begin_fill()
turtle.left(90 - (360/(2*n)))
for i in range(n):
turtle.left(360/n)
turtle.forward(R * 2 * math.sin(math.pi/n))
turtle.end_fill()
turtle.right(90 - (360 / (2 * n)))
turtle.penup()
turtle.for... |
ba437ee1bc0ed8239635c918024848b48fb173cc | KeerthikaRajvel/T9Hacks | /map/authentication.py | 858 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 8 03:20:52 2020
@author: matth
"""
class authentication:
def __init__(self):
# Go to http://apps.twitter.com and create an app
# The consumer key and secret will be generated for you after
#Twitter Credentials
... |
0d46264e9ae28e252fb8be7ef15786a14edb7245 | Julioc10/CursoPython | /palindrome.py | 121 | 3.84375 | 4 | palavra = input('Palavra:')
palindrome = palavra == palavra[::-1]
print(f'{palavra} é palindrome?')
print('palindrome')
|
bc4cd7187486acef7eff8bb0fd7244f33ae4d0b3 | marchelleboid/adventofcode | /2016/day10/day10a.py | 2,663 | 3.703125 | 4 | class Instruction:
def __init__(self, output, number):
self.output = output
self.number = number
def __repr__(self):
return str(self.__dict__)
class Bot:
def __init__(self, low_instruction, high_instruction):
self.value1 = -1
self.value2 = -1
self.low_instru... |
6620169ce013282bc4602f63a40de682aa0d77de | Momo227/PracticeAlgorithm | /FullSearch/found_mini.py | 320 | 3.5625 | 4 | def main():
N = int(input())
min = int(20000000)
data = []
for i in range(N):
a = int(input())
data.append(a)
min_value = min
for i in range(N):
if(data[i] < min_value):
min_value = data[i]
print(min_value)
if __name__ == '__main__':
main() |
7dd205fd51c837b6f31bcd544ea60f1c9c49ceaf | Kaecchi/mroczko_python | /2/zadanie11.py | 186 | 3.5625 | 4 | # -*- coding: utf-8 -*-
n = int(input('Podaj n'))
wart = 0
for i in range(2, n-1):
if n % i == 0:
wart = 1
if wart == 1:
print('Złożona')
else:
print('Pierwsza') |
7ae18bb53b77f3b272ea244887d3d75f565205aa | readxia/basketball_stats | /BasketballStats.py | 5,114 | 3.9375 | 4 | from Player import Player
"""
player=Player("Read")
player.shoot(3, True)
player.shoot(2, False)
player.shoot(2, False)
player.shoot(2, True)
player.rebound(False, 2)
player.rebound(True, 1)
player.print_stats()
"""
user_input = "";
player_list = [];
def help_me():
#list commands here
print "\n \nList of commands... |
fba3c13b38ea7753480b18ffaf8228ed5c4fdde8 | abnerlourenco/Aprendendo_python3 | /seçao 3/funcao.py | 430 | 3.96875 | 4 | # -*- coding utf: -8 -*-
def chamar():
print("Bem vindo a declaração de uma função")
chamar()
# a função tambem pode receber parametros, com isso podemos inserir dentro do escopo da função
def soma(x,y):
resultado = x + y
print(resultado)
soma(8, 9)
# o objetivo da função é retornar algum ... |
01f273f0acc05f7af7a5e72c817f244fcc73a34b | klknet/geeks4geeks | /datastructure/array/sum_of_all_primes.py | 414 | 4.03125 | 4 | """
Sum of all the prime numbers with the count of digits <= D.
"""
def sum_of_prime(d):
n = 10 ** d
prime = [True] * n
for i in range(2, n):
m = i*i
if prime[i]:
while m < n:
prime[m] = False
m += i
s = 0
for i in range(2, n):
if... |
ee6c768e39a186746c8adf4dcc520d7a4d8cb342 | 772766964/Python | /Variable.py | 239 | 3.90625 | 4 |
# python会根据赋予的类型来决定该变量的类型
# char(),str(),int()...可以进行强制转型
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串
print counter
print miles
print name
|
d465365c9c6bfdad459e68a4bc1887eebed35185 | KonstantinMyachin/HSEPython | /ru/myachin/homework/sixth/main.py | 13,664 | 3.5625 | 4 | import pandas as pd
# ### Задача 1 (1 балл)
# В датафрейме `df` находится информация об успеваемости студентов: в столбцах `First Name` и `Last Name` — имя и
# фамилия, а в следующих столбцах — оценки за разные курсы по пятибальной системе (целые числа от 0 до 5).
# Напишите функцию `get_grade(df, lastname, firstname,... |
03a3bb2c109e0b5d609cb21950566254bb610159 | priyankasomani9/basicpython | /Assignment13/basic13.2_matrix.py | 250 | 4.09375 | 4 | import numpy as np
x=int(input("enter values of how many rows you want"))
y=int(input("enter values of how many column you want"))
matrix=[]
for i in range(x):
for j in range(y):
matrix.append(i*j)
matrix = np.array(matrix).reshape(x, y)
|
2317756811d89bfe16020e90071c4266339b448d | yuanzhi0515/guandan-ai | /client/utils.py | 4,722 | 3.578125 | 4 | # ----------------------------------------------------------
# Representation String
# ----------------------------------------------------------
def suit_to_str(suit):
map = ['♠', '♥', '♣', '♦']
return map[suit]
def card_to_str(card):
if card[1] == 'PASS':
return 'PASS'
if ... |
cd60c3eaa61424ac3082beaef3c42f9771cdc220 | lbarthur/bing | /zhuce.py | 716 | 3.671875 | 4 | f = open("/reboot/user.txt", "a+")
username=""
password=""
while True:
username=input("please input your username(quit):").strip()
password = input("please input your password:").strip()
repass = input("please confirm your password:").strip()
if username =="":
print ("user name is null, ... |
7a943c6b4345ad6d9613f7903e51b165d94aeb49 | ITlearning/ROKA_Python | /2021_03/03_12/CH04/014_Reversed_For02.py | 134 | 3.9375 | 4 | # 반대로 반복하기(2)
for i in reversed(range(5)) :
print("현재 반복 변수 : {}".format(i))
# reversed() 사용하기 |
adcc18ea2a893f049fb50e45f0a038f1fb81febf | poojaGit95/DataStructures-Algorithms-Python | /Graphs/BellmanFordAlgorithm.py | 1,249 | 3.578125 | 4 | class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.nodes = []
self.graph = []
def addNode(self, node):
self.nodes.append(node)
def add_edge(self, src, dest, dist):
self.graph.append([src, dest, dist])
def distanceFromSource(self, dist):
... |
ce24094b2dc93793a2126aca18ba696b21ed75fa | NianchenGuo/myproject | /weiwei_pro/weiwei_pro3/file_reader.py | 884 | 3.703125 | 4 | # coding=utf-8
"""
作者:郭伟伟
简介:
从文件中读取数据
日期:2019-12-10
"""
with open("pi_digits.txt") as file_object:
""" 函数open() 接受一个参数:要打开的文件的名称 """
contents = file_object.read()
print(contents.rstrip())
# 绝对路径读取文件
file_path = "C:\\my\\MyProject\\myproject\\weiwei_pro\\weiwei_pro3\\pi_digits.txt"
with open(file_path) a... |
0042af4cde7dd06de6b5f2d931493a54fc76ed7a | btke/CS61A-Fall-2016 | /lab/lab11/lab11.py | 1,537 | 3.875 | 4 | def countdown(n):
"""
>>> for number in countdown(5):
... print(number)
...
5
4
3
2
1
0
"""
"*** YOUR CODE HERE ***"
val=n
while val>=0:
yield val
val-=1
def trap(s, k):
"""Return a generator that yields the first K values in iterable S,
... |
3eb69f257265bd083fff31758a8143b0caef73ff | RahulRwt125/Classwork | /UPPERLIST.py | 70 | 3.65625 | 4 | n=input("Enter a string please: ")
a=[i for i in n.upper()]
print(a) |
9aeb74f45630b5c5fee5371b6c9e81fa626b2860 | Demoleas715/PythonWorkspace | /Unit4Objects/Encryptor.py | 1,193 | 4.21875 | 4 | class Encryptor(object):
def __init__(self, file_name):
self.file_name=file_name
self.e_dict={}
self.d_dict={}
text_file=open(file_name, "r")
for line in text_file:
line=line.strip().split("\t")
self.e_dict[line[0]]=line[1]
... |
b48f510412b93341d0312385eb07c65de7216c70 | nicolasduran25/Python-Daw | /practica 3/practica3ej6.py | 186 | 3.671875 | 4 | Precio = int(input("precio del producto:"))
Producto = input("nombre del producto:")
IVA = Precio*0.21
Total = Precio + IVA
print ("el producto",Producto ,"vale en total",Total,"euros")
|
303ce88fb36a2454fbd5bd3e20a72531073c2514 | ZainQasmi/LeetCode-Fun | /gcd.py | 178 | 3.546875 | 4 | # def gcd(a,b):
# if b==0:
# return a
# else:
# return gcd(b,a%b)
# print gcd(2,4)
def ajeeb(n,k,i):
if k<n:
print i-1
else:
print i+(k%n)-1
ajeeb(3,5,1) #1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.