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 |
|---|---|---|---|---|---|---|
b35e2f33b1f9b2f3af1e5f10a783b9245a6127f7 | janaobsteter/PyCharmProjects | /Pratice/max.py | 472 | 3.59375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
#use function product(*ListOfLists)
from itertools import product
k, m = map(int, input().split(" "))
lists = []
for l in range(0, k):
lists.append([x for x in map(int, input().split(" "))])
if sum([m ^ 2 for m in [max(l) for l in lists]]) < m... |
4fe49c1db08ccc139af1ca077a2db6c630b1a462 | chenmingjian/did_chenmingjian_coding_today | /.leetcode/106.从中序与后序遍历序列构造二叉树.py | 1,019 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=106 lang=python3
#
# [106] 从中序与后序遍历序列构造二叉树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postord... |
4319c0b12ed945e3586c16032d2606c38377a837 | DOYEON96/TIL | /0719/algoithm/Code11-03.py | 451 | 3.703125 | 4 | # 함수
def selectionSort(ary):
n = len(ary)
for i in range(n-1):
minIdx=i
for j in range(i+1, len(ary)):
if ary[minIdx] > ary[j]:
minIdx = j
ary[i], ary[minIdx] = ary[minIdx], ary[i]
return ary
# 전역
import random
dataAry = [random.randint(50, 200) for _ i... |
1735b1909a44dfb898755a9dd74023c25993f451 | Universatile/AdventofCode | /day6.py | 1,020 | 3.90625 | 4 | # Day 6 of Advent of Code
# Author: Jason Rennie
def redist(banks):
"""Resdistributes the blocks from the largest memory bank to other banks,
sequentially with one per bank until completely redistributed.
"""
k = max(banks)
i = banks.index(k)
end = len(banks)
banks[i] = 0
while k > 0:
... |
f337e0063a053b9be1238f26a9e9b71110fedd3c | dlhauer/Sprint-Challenge--Intro-Python | /src/oop/oop2.py | 450 | 3.5 | 4 |
class GroundVehicle():
def __init__(self, num_wheels=4):
self.num_wheels = num_wheels
def drive(self):
return "vroooom"
class Motorcycle(GroundVehicle):
def __init__(self):
super().__init__(2)
def drive(self):
return "BRAAAP!!"
vehicles = [
GroundVehicle(),
... |
afc891b2b62e67286db2ae12893a3b5c9ac16b85 | harshitkakkar/PythonBasics | /Basics/pandas2_python.py | 1,117 | 3.703125 | 4 | import pandas as pd
import sqlite3
df = pd.read_csv("nwedemo.csv")
df["esal"]=pd.Series([1000,1200,1300,900,200],dtype="float")
print(df)
print("------------------")
print(df.sum())
print("------------------")
print(df["Pid"].max())
print("------------------")
print(df["esal"].min())
print("------------------")
print... |
669dfe62d9f641072d3157e23e48208c7d41a993 | daniel-reich/ubiquitous-fiesta | /GaJkMnuHLuPmXZK7h_13.py | 324 | 3.640625 | 4 |
def letters(word1, word2):
s, u1, u2 = '','',''
for i in word1:
if i in word2:
if i not in s:
s += i
else:
if i not in u1:
u1 += i
for i in word2:
if i not in word1:
if i not in u2:
u2 += i
return [''.join(sorted(s)), ''.join(sorted(u1)), ''.join(sorted(u2)... |
d0a49722a651b6741471772eb5161fbd34a7e470 | BlackRussians/Tic-Tac-Toe | /Stage #5/tictactoe.py | 2,389 | 3.5 | 4 | def make_field(cells):
for i in range(len(cells)):
if cells[i] == "_":
cells[i] = " "
print('---------')
for i in range(0, 7, 3):
print("| {} {} {} |".format(cells[i], cells[i+1], cells[i+2]))
print('---------')
def chk_field(cells):
global active
x_win = 0
o_wi... |
93fc2a939cec4ffbb5149514eb94cda5c51c7be3 | f1amingo/leetcode-python | /剑指offer/剑指 Offer 58 - I. 翻转单词顺序.py | 1,012 | 3.8125 | 4 | # 翻转单词,而不是字符,空格分隔
# 1.移除前后的多余空格
# 2.单词之间也可能有多空格
class Solution:
def reverseWords(self, s: str) -> str:
if not s:
return ''
start, end = 0, len(s) - 1
ans = []
while start <= end:
# 倒序找到第一个非空字符
rt = end
while start <= rt and ... |
3f8b55d7b9970d207a89fba19192a472d6e527fc | AlexandraFil/Geekbrains_2.0 | /Python_start/lesson_2/1.py | 616 | 3.859375 | 4 | # 1. Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента.
# Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list = [1, 1.1, 34.56, False, (1, 2, 3, 4), True, ['... |
05a8e6094da25444a389a35d2fd62afd30306a8a | t3hpr1m3/More-Python-Testing | /Login.py | 547 | 3.8125 | 4 | import pickle
dict_1 = {
}
print(dict_1)
filename = 'Email_dict.txt'
file = open(filename, 'rb')
x = pickle.load(file)
dict_1.update(x)
print(dict_1)
def login():
a = input('Please enter your Email: ')
if a in dict_1.keys():
b = input('Please enter your password!: ')
if dict_1[a] == b:
... |
55527d79419603521fa1a7c6f861f4304c5ccc02 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/Nol/codeJam2.py | 1,244 | 3.765625 | 4 | #!/usr/bin/env python3
#flip the N first pancakes of the S piles
# aka "the maneuver"
def flipPiles(S,N):
toflip=S[:N]
flipped=toflip.translate(str.maketrans("+-","-+"))
flipped=flipped[::-1]
return flipped+S[N:]
def main():
inFile=open("dataset.txt",'r')
outFile=open("output.txt... |
5e4d48ed166b8e2923013b235b4b4987efc45fc3 | arichen/algorithm-notes | /tic_tac_toe.py | 1,432 | 3.765625 | 4 | from collections import defaultdict
class TicTacToe:
def __init__(self, n = 3, current = 0):
# current symbols: 0 or 1
self.n = n
self.board = [[None] * n for _ in range(n)]
self.current = current
self.count = 0
self.is_finished = False
self.out = {0: "O", 1: "X", None: " "}
# marks moves
self.rows... |
47483c87e95bc0091524b82df46b2b178e9e4cf9 | r-luis/Python-CursoemVideo | /Download/PythonExercicios/ex077.py | 501 | 4.25 | 4 | '''Desafio 77 Crie um programa que tenha uma tupla com várias palavras (Não usar acentos).
Depois disso, você deve mostrar para cada palavra, quais são as suas vogais.'''
palavras = ('Luffy', 'Zoro', 'Nami', 'Sanji', 'Chopper', 'Robin', 'Franky', 'Brook', 'Jimbe')
vogais = 'aeiou'
for p in palavras:
print(f'\nA p... |
fb8947d9297b34e21a756c46b8a701602aea55d0 | PythonCHB/Sp2018-Accelerated | /students/ahwall/Lesson 02 Homework/FibLuc_Seq Exercise_HW2/FibLucSeq.py | 528 | 3.578125 | 4 | def fibinacci(x):
a = 0
b = 1
c = 0
if (x == 0):
print(x)
else:
for i in range(x):
a = b
b = c
c = b + a
print(c)
def lucas(x):
a = 2
b = 1
if x == 0:
print(2)
elif x == 1:
print(1)
else:
for i ... |
d4c7f190ff2183168e1a8e3b08fcc9a3720f9cd3 | life-sync/Python | /subhash1612/anagram.py | 839 | 4.34375 | 4 | '''
This program checks if two strings are anagrams of each other.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase
'''
def check(str1,str2): #Function to check if they are anagrams
if(len(str1) != len(str2)): #Comparing the lengths of the two strings
pri... |
3c75d4c85b40335b0c91fd4c8f420931b2fe0562 | jakubszczyglewski/Tic-Tac-Toe | /tictactoe.py | 5,788 | 3.8125 | 4 | import random
class Player:
def __init__(self, sign):
self.sign = sign
def move(self, moves, sign):
print('Your move, please choose a field.')
player_move = input()
while player_move not in moves or moves[player_move] != '_':
print('Something is wrong, you may want to check your move')
print('Your mo... |
30576bf602b971f024e69afe8607f86945d61127 | emanonGarcia/mystery_word | /mystery_word.py | 3,818 | 3.96875 | 4 | import random
import string
MAX_GUESSES = 8
def lets_play():
answer = input("Let's play: [Y]es or [N]o ")
if answer.lower() == 'y':
print_game_title()
return True
elif answer.lower() == 'n':
print("Maybe next time...")
exit()
else:
lets_play()
return Tr... |
f66e2344c4b4d9bb46be28cf04fd908dea77fe21 | vardecab/coursera-py4e | /Course 1 - Programming for Everybody (Getting Started with Python)/7 • Largest, Smallest & Error.py | 968 | 4 | 4 | # 5.2 | Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
# Once 'done' is entered, print out the largest and smallest of the numbers.
# If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message
# and ignore the num... |
3e90e2cf23a86e987166a942b49e2930935a4cc2 | cassiomedeiros/q_learning_project | /qlearning/estado.py | 2,481 | 3.53125 | 4 |
import numpy as np
from typing import Tuple, List
class Estado:
"""Classe responsável por mover o agente dentro do espaço vetorial.
"""
def __init__(self, estado: Tuple[int, int]=(5, 0)):
self.estado = estado
self.entregou_objeto: bool = False
self.deterministico: bool = True
... |
9cbb001f8c12a0ae850cbd5d2e43dca37ff2536a | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/hard_algo/4_1.py | 11,483 | 3.703125 | 4 | Maximum size of square such that all submatrices of that size have sum less
than K
Given an **N x M** matrix of integers and an integer **K** , the task is to
find the size of the maximum square sub-matrix **(S x S)** , such that **all
square sub-matrices** of the given matrix of that size have a sum less tha... |
601b00c80794e71cf0cca6148d29b855fa998aed | jfriend08/practice | /linkList/compStringLinkList.py | 940 | 3.890625 | 4 | '''
Compare two strings represented as linked lists
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s->b
Output: -1
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s
Output: 1
Input: list1 = g->e->e->k->s
list2 = g->e->e->k->s
Output: 0
'''
from ListNode import ListNode
def compareString(... |
b4c4803692537a2c2881b6da571b9c0d5f8c3145 | heenashree/HRCodes | /minion-game.py | 88 | 3.578125 | 4 | A = [i for i in input().upper().split()]
print(A)
for i in range(len(A)):
if (A[i]) |
fb2163e6f84be0a1b210e0c5e32ceeacafc3488a | CrazyHatish/DAS5334 | /AulaN/Exercise6.py | 137 | 3.796875 | 4 | def is_anagram(s1, s2):
l1 = list(s1)
l2 = list(s2)
return sorted(l1) == sorted(l2)
print(is_anagram("batata", "tatbaa"))
|
2564e32ecf9c32308b08890bc9950caec284b782 | brianchiang-tw/leetcode | /2020_August_Leetcode_30_days_challenge/Week_3_Sort Array by Parity/by_two-pointers_and_swap.py | 1,892 | 4.25 | 4 | '''
Description:
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3... |
67bb7c668146f5fa00b9547ea1fcef9f1ef8fcc3 | alexjercan/algorithms | /old/leetcode/problems/merge-sorted-array.py | 745 | 3.953125 | 4 | from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
array_len = m
i = 0
j = 0
while i < array_len and j < n:
if nums1[i] >= nums2[j]:
insert(nums1, i, nums2[j])
i = i + 1
... |
63eacee47ea7dfcae872d03123e2db3fec20327d | usercngit/INF123_TeamCSS | /srcGame/GetUsername.py | 1,353 | 3.71875 | 4 | """
@author: Sofanah
"""
import pygame
from pygame.locals import *
import string
class GetUsername:
def __init__(self, window, height, width):
self._screen = window
self._height = height
self._width = width
def get_key(self):
while True:
event = pygame.event.poll()
if event.type == KEYDOWN:
ret... |
9cc22875e1b88e774b90f075b810ef602e35739d | daniel-reich/turbo-robot | /eA94BuKYjwMoNQSE2_13.py | 557 | 4.3125 | 4 | """
Create a function that returns `True` if a given inequality expression is
correct and `False` otherwise.
### Examples
correct_signs("3 < 7 < 11") ➞ True
correct_signs("13 > 44 > 33 > 1") ➞ False
correct_signs("1 < 2 < 6 < 9 > 3") ➞ True
### Notes
N/A
"""
def correct_signs(txt):
cha... |
07037668596908c2a8aa226c6c2fd09e73181559 | jefferyyuan/interviewjam | /dynamic_programming/leetcode_House_Robber.py | 710 | 3.5625 | 4 | """leetcode_House_Robber.py
https://leetcode.com/problems/house-robber/
"""
class Solution:
"""DP.
dp[i] = max(dp[i - 2] + arr[i], dp[i - 1])
Yes you can use an array to represent dp states but in this case use two
variables are good enought, just like fibonacci.
"""
def rob(self, nums):
... |
49e75e4a132e40c105e00eee4d6a2f6f3f0b10aa | SAIKUMARAR7/Python | /area_circle.py | 76 | 3.96875 | 4 | r=int(input("enter the radius"))
print("area of circle is",round(3.14*r*r))
|
28ee60df40b07e022b5524f324ccaf23f8ceae1f | Thiago-Mauricio/Curso-de-python | /Curso em Video/Aula17 Listas parte1/Aula17 Listas.py | 696 | 3.875 | 4 | l = []
for c in range(1,10):
l.insert(0, c)
print(l)
l = []
for c in range(1,10):
l.append(c)
print(l)
num = [2, 5, 9, 1]
num[2] = 3
num.append(7)
num.sort(reverse=True)
num.insert(2, 0)
if 4 in num:
num.remove(4)
print(num)
print(f'essa lista tem {len(num)} elementos.')
valores = []
valores.append(5)
val... |
0859f2533db665fdc00e3b5cb67946d50188d667 | rudeqit/crypto | /graph/graph.py | 3,534 | 3.65625 | 4 | #!/usr/bin/env python3
# Take it from here: https://github.com/plutasnyy/Cycles-in-graphs
from random import randint
import copy
import time
class Graph:
def __init__(self, number_of_vertices, density):
'''
minimum destinity -> n * (n-1) / 2 * d >= n - 1
is equal to d >= 2/n
''' ... |
ed2ec2292903b50b00ab779d56fdda5e6d20be19 | SimonVarga2008/sandbox | /demo.py | 238 | 3.765625 | 4 | sum = 0
for i in range ( 0 ):
sum += i
print ( sum )
x = 5
y = "Nieco"
print( x, y )
print2 = 22
print( print2 )
def print3(item):
print(item)
print(item)
print3( 33 )
print()
def x2( x ):
print( x * x )
x2( 5 )
|
7972cb83a570b01fa1c7ec2827edb8fd136ae2d8 | leonhostetler/undergrad-projects | /computational-physics/03_plotting/sunspots.py | 804 | 3.6875 | 4 | #! /usr/bin/env python
"""
Plot the observed number of sunspots for each month.
Leon Hostetler, Feb. 2, 2017
USAGE: sunspots.py
"""
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
# Main body of program
r = 5 # The 'half-length' of the weighted average
# Load th... |
936af4208862ce16bfb4dec8e7c9e94df5a2ae54 | romskr9/python_examples | /math/myparser.py | 2,411 | 3.515625 | 4 | from mymath import *
class Parser:
def __init__(self, name = None):
self.init(name)
def init(self, name = None):
self.token = None
self.one = None
if name:
self.name = name
self.f = file(name, 'r')
def getone(self):
if self.one:
result = self.one
self.one = None
# print 'got one ch... |
3e98206e8874bf1a5a58b4fd84516e9251c2c181 | mmkhaque/LeetCode_Practice | /1213. Intersection of Three Sorted Arrays.py | 1,161 | 4.28125 | 4 | '''
Time: O(N)
Space: O(N)
'''
'''
Better here
https://leetcode.com/problems/intersection-of-three-sorted-arrays/solution/
'''
'''
Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order,
return a sorted array of only the integers that appeared in all three arrays.
Example 1:
Input: arr1... |
ceb26aefe922da6142caee7622ddf7b4eff36c38 | geddings/pynancial | /tests/test_pynancial.py | 1,661 | 3.515625 | 4 | from collections import namedtuple
Bracket = namedtuple('Bracket', ['rate', 'floor', 'ceiling'])
class MarriedFilingJointly(object):
def __init__(self):
self.brackets = [
Bracket(rate=0.10, floor=0, ceiling=19750),
Bracket(rate=0.12, floor=19751, ceiling=80250),
Brack... |
0648d6e1fd48aa2b4155f01e9d8dc1ad7bdcf836 | ydzhang12345/LeetCode | /22.Generate_Parentheses/sol.py | 641 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
out = set()
left, right, s = 0, 0, ''
def dfs(l, r, s):
if l==n and r==n:
out.add... |
92eb9ba5db45831bbdb5f89bddaf3c5ca8943ce6 | capncrockett/beedle_book | /Ch_09 - Simulation and Design/cube_field_solution.py | 2,060 | 4.03125 | 4 | # cube_field_solution
# c09ex15.py
# Puzzle problem. Imagine a cube circumscribed about a unit sphere.
# An "eyeball" at the origin "sees" each wall as 1/6 of the field of
# view. Suppose the eye is moved to (0.5, 0, 0), what proportion of
# the total field of view is taken up by the side of the cube a... |
c3769b66b74b2aa10daff6f8d39faa5478f97e9d | skye7803/new_project | /v2/main.py | 4,549 | 3.59375 | 4 | from world import World
from player import Player
class Main:
actions = {
'help': {
'commands': ['h', 'help'],
'description': 'Show this help text',
},
'north': {
'commands': ['n', 'north'],
'description': 'Move in a north direction',
... |
cb63ed5d91c5fd208da03eba11bfb3eb7d604ff1 | emanoelmlsilva/Lista-IP | /exercicio05/programa06.py | 882 | 3.921875 | 4 | valor_produto = int(input('Informe o valor do produto: '))
tipo = str.lower(input('Informe a forma de pagamento:(Dinheiro / Cheque ou Cartao)'))
if((tipo == 'dinheiro') and (valor_produto >= 100)):
pagar = (valor_produto - (valor_produto*0.10))
elif((tipo != 'cheque') and (tipo != 'dinheiro') and (tipo != 'cartao')... |
5fb9a27ad482228625151d0363d913f97e8c7ed5 | Eacruzr/python-code | /individual/reto1.py | 1,150 | 3.78125 | 4 | print("Bienvenido al sistema de ubicación para zonas públicas WIFI")
nombre_usuario='51743' #El usuario definido
contraseña='34715' #La contraseña definida
dato_usuario=input('Ingrese el nombre de usuario: ') #Se solicita el usuario a la persona
if dato_usuario==nombre_usuario: #Se compara el usuario ingresado con el ... |
15efd26ca928a0b61aa1b2f943081972c54f5072 | JenZhen/LC | /lc_ladder/company/gg/high_freq/Isomorphic_String.py | 1,405 | 4.15625 | 4 | #! /usr/local/bin/python3
# https://leetcode.com/problems/isomorphic-strings/
# Example
# Given two strings s and t, determine if they are isomorphic.
#
# Two strings are isomorphic if the characters in s can be replaced to get t.
#
# All occurrences of a character must be replaced with another character while preserv... |
833ddf8db957715a7740e57ec0e4225e40ad737a | lunatic-7/python_course_noob-git- | /while_loop.py | 129 | 3.90625 | 4 | # loops
# while loop, for loop
# print("hello world") # 10 times
i = 1
while i<=10:
print(f"hello world {i}")
i = i + 1 |
3e640c49e51eaa6a15bd927cd4b25e11245a7d32 | stephenjust/arduino-gps-glasses | /server/pqueue.py | 3,123 | 4.1875 | 4 | """
Priority queue implementation as a binary heap
pop_smallest()
remove the element with the lowest priority
return tuple (key, priority)
update(key, priority)
lower the priority of an element
if priority is not lower do nothing,
if key is not in priority queue, add it
return True if priority... |
9cbd45bb5f2a735f4602c7d5f25639c4b1fbd210 | osvaldohg/hacker_rank | /warmup/time_conversion.py | 402 | 3.90625 | 4 | #!/bin/python
# https://www.hackerrank.com/challenges/time-conversion/problem
# by oz
import sys
time = raw_input().strip()
ltime=time.split(":")
hour=int(ltime[0])
if "AM" in time:
if hour==12:
print "00"+time[2:8]
else:
print time[:-2]
else:
if hour==12:
print time[:-2]
... |
27d0a50576656923cc061e99d24c633eabcf4ce4 | srashee2/CourseProject | /SKlearn_w_subclass.py | 6,263 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Import essential libraries
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from nltk.stem import WordNetLemmatizer
import pyLDAvis.sklearn
... |
9914afa82f6f497a41fc30c230dbcf3544a0aa4f | luisniebla/queue | /queue.py | 929 | 3.953125 | 4 | # Create the object type 'queue'
class Queue:
def __init__(self, n):
self.Q = [0] * n
self.tail = 0
self.head = 0
self.length = n
def enqueue(self, x):
self.Q[self.tail] = x
if self.tail == self.length:
self.tail = 0
else:
self.tai... |
9da4356c719d0767fe227bc2eb297aa82627fae0 | rfcamo/python-challenge | /PyParagraph/main.py | 1,042 | 3.6875 | 4 | # Imports of dependencies
import os
import re
import string
# Files to load and output
fileload = "raw_data/paragraph_1.txt"
# Open and read the txt file
with open(fileload) as txtfile:
paragraph_txt = txtfile.read()
# Count word in the paragraph
count_word = len(re.findall(r'\w+', paragraph_txt))
# Count sent... |
f6e69661f699f5aa0ea96aa261221e98a2893a11 | ganlanshu/leetcode | /sliding-window-maximum.py | 2,134 | 3.59375 | 4 | # coding=utf-8
"""
239. Sliding Window Maximum
"""
import collections
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
先想到一个简单粗暴的方法
"""
if not nums:
return []
n = len(nu... |
56b4c5dfe50189e8febe755465c6ea0837f6e27c | sgrade/pytest | /codeforces/987A.py | 394 | 3.671875 | 4 | # A. Infinity Gauntlet
colors = {
'purple': 'Power',
'green': 'Time',
'blue': 'Space',
'orange': 'Soul',
'red': 'Reality',
'yellow': 'Mind'
}
n = int(input())
present = list()
for _ in range(n):
present.append(input())
ans = list()
for color in colors.keys():
if color not in present:... |
494711637a4b7f3af7a65de242efecb471c0e280 | SmartTech-SD/Chess_Board_in_Turtle_Python | /chess_board_in_Turtle.py | 3,441 | 3.890625 | 4 | # creating a simple chess board
# Each row having 8 columns
# total 4 column black and 4 column white alternativly
import turtle
t1=turtle.Turtle()
screen=turtle.Screen()
screen.bgcolor('blue violet')
screen.title('***Chess Board***')
t1.hideturtle()
t1.penup()
t1.goto(-20,200)
t1.pendown()
t1.color('pink')... |
e53a199ee7041011103c852b16f22dc1b9bcb6ab | arsamigullin/problem_solving_python | /techniques/monotonous_stack/NLE.py | 567 | 3.984375 | 4 | # this monotonous technique helps to find Next Less Element (PLE)
# instead of storing the value itself we will store the index-
def find_nle(arr):
stack = []
next_less = [-1] * len(arr)
for i in range(len(arr)):
while len(stack) > 0 and arr[stack[-1]] > arr[i]:
next_less[stack.po... |
d68efac49a2a5ca4c25ca565e1b8ba859fa2b58c | frankbozar/Competitive-Programming | /Barcelona Bootcamp/Day4/C.py | 497 | 3.546875 | 4 | z = int(input())
for _ in range(z):
n = int(input())
if n == 1:
print('1 1 1 2')
elif n == 2:
print('1 1 1 2')
print('1 3 1 4')
print('1 5 1 6')
elif n == 3:
print('1 1 1 2')
print('1 3 1 4')
print('2 3 3 3')
print('1 5 2 5')
print('2 4 3 4')
print('4 3 4 4')
elif n == 4:
print(1,2,1,3)
pri... |
d0a26e5f7f3747afa8f878ae0e08f545a02dcbc1 | girish-patil/git-python-programs | /Python_Assessment/Q24.py | 502 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 18:52:11 2017
@author: Girish Patil
"""
#24.Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
#Suppose the following input is supplied to the program:
#34,67,55,33,12,98
#Then,... |
1b1cb110f7e1ca7b29184314bf3ee1a9ba504a29 | cody-berry/gravitation | /Repulser.py | 889 | 3.984375 | 4 | from Attractor import *
# Repulser is the oppisite of Attractor.
class Repulser(Attractor):
# We don't need a constructer because if we did, then it would be the exact
# same. Python allows us to not contain a constructer if it is the exact
# same as the class's constructer that it is 'inheriting' from.
... |
3268821cc6c30890b9f9af1a1f3b62f7e1e8cf0d | amaxwong/mbs-3523 | /OpenCV-3-webcam.py | 615 | 3.5625 | 4 | # Save this file as OpenCV-3-webcam.py
import cv2
#import numpy as np
print(cv2.__version__)
# you may need to change the number inside () to 0 1 or 2,
# depending on which webcam you are using
capture = cv2.VideoCapture(0)
# Below 2 lines are used to set the webcam window size
capture.set(3,640) # 3 is the width of ... |
20659b5366b8b022995348a411331e1fe248fd79 | siddeshshewde/Competitive-Programming | /CodeAbbey-Solutions/2. Sum in Loop/Solution.py | 119 | 3.578125 | 4 | def sum():
n = input()
a = input()
sum = 0
for i in a:
sum = sum + i
return sum |
9e0959065f058dfb117b48fb8ed92cfb3345787e | abixadamj/Abix.Edukacja | /Python101xEDU/klasy.py | 2,346 | 3.984375 | 4 | class Torebka(object):
'''
Tego opisu i tak nie widzimy
'''
def __init__(self, zawartosc, nazwa='Torebeczka'):
'''
Tu __init__ - co podajemy na starcie, czyli:
elementy początkowe listy
nazwę naszej torebki (Domyślnie: Torebeczka)
'''
self.zawartosc_torebk... |
262a6b1b9251c93c17287efe9f58bb9ee4cbc353 | xxxhol1c/cs61a-su2021 | /hw/hw02/hw02.py | 6,235 | 4.03125 | 4 | from operator import add, mul, sub
square = lambda x: x * x
identity = lambda x: x
triple = lambda x: 3 * x
increment = lambda x: x + 1
HW_SOURCE_FILE = __file__
def compose1(func1, func2):
"""Return a function f, such that f(x) = func1(func2(x))."""
def f(x):
return func1(func2(x))
return f... |
96cfe827966912ec376b5b30b5431cdce7ce8bdc | gbodeen/algorhythmix | /python/project-euler/PE050.py | 1,973 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime
below one-hundred.
The longest sum of consecutive primes below one-thousand that adds
to a prime, contains 21 terms, and is equ... |
9f75514636a3f925dc9bfaa4cde83c0070b69578 | LeKillbit/CTF_Writeups | /tenable/hackers_manifesto/solve.py | 1,388 | 3.5 | 4 | #!/usr/bin/env python3
data = open("hacker_manifesto.txt", "rb").read()
def reset_chunk(c):
ret = b""
ret += b"\x00"
ret += b"\x00"
ret += bytes([c[2]])
return ret
def insert(chunks, idx, offset, length):
ret = []
if length & 1 != 0:
offset += 256
if (length >> 1) & 1 != 0:
... |
f8158eb850b6cc95afcfceed63b7e034b7a48223 | WILLIDIO/ExercicioPython | /exercicio9.py | 423 | 3.921875 | 4 | # -*- coding: utf-8 -*-
print("Faça um Programa que leia um vetor A com 10 números inteiros,")
print("calcule e mostre a soma dos quadrados dos elementos do vetor.")
print()
vetorA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
vetorB = []
print("Vetor A: ", vetorA)
for i in vetorA:
i = i ** 2
vetorB.append(i)
print("V... |
a5b4cb7eedfa1b1ba9859199231060b755f9849a | bhavya152002/dice-project-python- | /with2dice.py | 369 | 4 | 4 | import random
import time
roll = "yes"
while roll == "yes":
print("rolling the dice----")
time.sleep(1)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print("the values are : ")
print("Dice 1 = ",dice1,"\nDice 2 = ", dice2)
choice = input("Do you want to roll the dice again? (y/n)... |
83ecf08838e13e9913f3e2702bcf3659e2301fae | akanksha007/CTCI | /linked_list/linked_list.py | 1,069 | 4.03125 | 4 | class Node:
def __init__(self, data, address):
self.data = data
self.address = address
def getNextNode(self):
return self.address
class LinkedList:
def __init__(self, head = None):
self.head = head
def addNode(self, data):
newNode = Node(data, self.head)
... |
873e37c5edf4accdbfb3fd0b524cfe7c6d58ed1d | Peytonlb/comp110-21f-workspace | /exercises/ex01/hype_machine.py | 293 | 3.546875 | 4 | """Hype Machine: Series of Hype Messages."""
__author__ = "730309987"
name: str = input("What is your name? ")
print("You are going to have a great day " + str(name))
print(str(name) + ", you are going to crush it today!")
print("You know it, " + str(name) + ", today will be the best day!") |
61ac5e9699fb201bc53748f53d69e8c03626d059 | enerhy/Udemy_Features | /Feature_Enigneering.py | 32,225 | 3.78125 | 4 | ------FEATURE ENGINEERING STEPS
---1. Analyse variable types and values and characteristics
# Data types - # make list of variables types
data.dtypes
# numerical: discrete vs continuous - SELECTION
discrete = [var for var in data.columns if data[var].dtype!='O' and var!='survived' and data[var].nunique()<10]
#OR
'''... |
c8e59885ff7db47dbeeaca811f004baf823c1d57 | ArisQ/learn-python | /37_collections.py | 616 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import namedtuple, deque, defaultdict, OrderedDict, Counter
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(Point)
print(p)
print(p.x)
print(p.y)
q = deque(['a', 'b', 'c'])
print(q)
q.pop()
q.popleft()
q.append('x')
q.appendleft('y')
print... |
22167717430fd40100e859cd14ae752ab689730d | chenenfeng/lt | /35. Search Insert Position.py | 1,229 | 3.953125 | 4 | """
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
"""
# my program seems low efficient, a lot of if determine which position the target should insert
class Solution:... |
c2ca1cfa85d26dfb6fa4ca0518fbcbe951d1ccdf | decretist/Delta | /burrows/burrows.py | 3,932 | 3.5 | 4 | #!/usr/local/bin/python3
# Paul Evans (10evans@cua.edu)
# 11-14 March 2020
import itertools
import math
import statistics
import sys
sys.path.append('..')
import utility as u
def main():
'''
Assemble a large corpus made up of texts written by an arbitrary
number of authors; let’s say that number of authors ... |
9b206a858162edeecd4ce5586bd466b0dca61b90 | ZihengZZH/LeetCode | /py/ZigZagConversion.py | 948 | 4.34375 | 4 | '''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conve... |
c9fdaa54540f9911ef73b982f819972dea6b18a7 | amisha1garg/Arrays_In_Python | /Replace0swith5.py | 745 | 4.09375 | 4 | # You are given an integer N. You need to convert all zeroes of N to 5.
#
# Example 1:
#
# Input:
# N = 1004
# Output: 1554
# Explanation: There are two zeroes in 1004
# on replacing all zeroes with "5", the new
# number will be "1554".
# Function should return an integer value
def convertFive(n):
# C... |
1fb21d9d0f5fe307ee60102926576d67846ce91e | FelipeRodri03/Trabajos-algoritmos-y-programaci-n | /Taller de estructuras de control/Ejercicio9.py | 490 | 3.71875 | 4 | """
Entradas
a-->int-->Monto de la compra
Salidas
b-->int-->Valor final de la compra
"""
a=int(input())
#caja negra
if (a<50000):
b="El valor de la compra es "+str(a)
elif (a>50000 and a<100000):
b="El valor de la compra es "+str(a-(a*0.05))
elif (a>=100000 and a<700000):
b="El valor de la compra es "+str(a... |
7cce5f8b4cbad6fd7492391f5fde04a21e28f965 | 951237/TIL | /TIL_2021/일상/210402_백준_10809_정답.py | 276 | 3.921875 | 4 | # 입력받은 단어에 사용된 알파벳의 사용여부 및 위치 출력하기
word = input()
alphabet = list(range(97,123)) # 아스키코드 숫자 범위
for i in alphabet:
print(word.find(char(x))) # char() : 숫자를 문자로 , ord() : 문자를 숫자로 |
22b1fd3a48fc4b8cace7aeeb5b5a2ba57c129283 | pagotarane/program_for_reffer | /Python/python/L1/p10.py | 232 | 4.21875 | 4 | #wapp to check if the given year is leap or not
year = int(input("Enter year "))
b1 = (year%100==0) and (year%400==0)
b2 = (year%100!=0) and (year%4==0)
if b1 or b2 :
print("It is leap year")
else :
print("It is not leap year")
|
7a60e7e8eef8f59bc2d780e09be9980c7981e3d7 | athiq-ahmed/Python | /numbers.py | 5,262 | 4.03125 | 4 | var1 = 10
var2 = 20
del var1, var2
#Python supports four different numerical types −
# Integers - They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
# Long - Also called longs, they are integers of unlimited size, written like integers and followed ... |
4e66b24b0c7cd23369f80aa62018b2310b5d33da | maddy-dolly/Python_Tutorial | /Advance_Python/formate.py | 817 | 3.765625 | 4 | person = {'name':'Madhu Acharya', 'age':23}
setence = 'My name is ' + person['name'] + ' and i am ' + str(person['age']) + ' year old'
setence_1 = 'My name is {0} and I am {1} year old.'.format(person['name'],person['age'])
setence_2 = 'My name is {0[name]} and I am {1[age]} year old.'.format(person,person)
setence_3... |
85fa3c64fdfccbfeaae21dd943c068d0de022754 | grbalmeida/hello-python | /programming-logic/repeating-structures/count-to-5.py | 86 | 3.921875 | 4 | number = 0
while number < 5:
print(number)
number = number + 1
print('Ended!')
|
7e73c0a3b07675bca0b2639c75a8f8576e983b8f | Mr-wr/python | /study_python/python基础/Demo_11生成器.py | 1,428 | 3.921875 | 4 | #!/usr/bin/env python3
#告诉linux system this is execute procedure
#windows 会忽略这个
# -*- coding: utf-8 -*-
#告诉python解析器是按照utf-8编码的
#------------------------------生成器
#在python中一遍循环一遍计算的机制就称作为生成器
#在python中只要把】改成)就是了但是不用用平时的print用next来打印
# g = (x*x for x in range(1,10))
# '''for x in g:
# print(x)'''
#赋值语句
# def fib(ma... |
fabdd7050818f130862b576bce425c67bfb77e17 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/bndtat003/question3.py | 723 | 4.375 | 4 | #Program to encrypt a program with the next set of characters in the alphabet
#Matthew Bandama
#BNDTAT003
#07-May-2014
def encrypt(string):
if len(string) == 0:
return()
else:
letter = ord(string[0]) + 1
next_letter = chr(letter)
if string[0] == ' ':
next_letter = ' '
... |
ef9154f033b7a659033d41b5dad80cc79e03f317 | mikel-codes/python_scripts | /MTs_py/mtsleep.py | 1,136 | 3.546875 | 4 | import thread
import re
from time import ctime, sleep
loop_st = [5, 2]
def loop(nloops, nsecs, lock):
print "loop",nloops , " started .>", re._compile('\d\d:\d\d:\d\d', 0).search(ctime()).group()
sleep(nsecs)
print "loop",nloops , " ended .>" , re._compile('\d\d:\d\d:\d\d', 0).search(ctime()).group()
... |
4dcc095c32665370daa5431befa26c49386d9a17 | Ideaboy/python_projects | /TetrisGame/gamewall.py | 2,901 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time : 2019-6-17 22:14:13
# @Author : WUGE
# @Email :
# @Copyright:
from settings import *
from gamedisplay import *
class GameWall(object):
"""游戏区墙体类。功能:记住落到底部的方块组成的“墙体”"""
def __init__(self, screen):
"""游戏开始,有20*10 个格子为‘-’表示,墙为空"""
self.... |
439101c6488325d0d8b2e498b8193e67634a41b3 | OK19/Python-Notes | /ttl.py | 156 | 3.671875 | 4 | '''
import turtle
bob = turtle.Turtle()
bob.position()
(0.00, 242.00)
bob.circle(113)
turtle.mainloop()
'''
def drawRing(t, ring):
ring = circle(113)
|
c9fed3ef2fadadaee07a36333c25eb6f8c540641 | Ho0ost/UvA_inleiding_prog | /module 2/randomgen.py | 176 | 3.671875 | 4 | import random
def random_range(a,b):
return a +(b-a)*random.random()
minimum = -5
maximum = 5
for i in range(10):
x = random_range(minimum, maximum)
print(x) |
1b1030308d7e9282a032566d60e51b1f12e45895 | 981377660LMT/algorithm-study | /21_位运算/格雷码/1238. 循环码排列.py | 437 | 3.96875 | 4 | from typing import List
# 给你两个整数 n 和 start。你的任务是返回任意 (0,1,2,,...,2^n-1) 的排列 p
class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
return [start ^ i ^ (i >> 1) for i in range(2 ** n)]
print(Solution().circularPermutation(n=3, start=2))
# 输出:[2,6,7,5,4,0,1,3]
# 解释:这个排列... |
b1501784cad274af8abb9fc85e8e50a2cb841d11 | xiao2912008572/Appium | /测试代码/列表.py | 653 | 3.75 | 4 | # Author:Xiaojingyuan
# list = [23,45,23,23 ,67,45,88,67]
# dict = {}
#
# count = 0
# for i in range(len(list)):
# for j in range(i+1,len(list)):
# if list[i] == list[j]:
# dict[list[i]] = count
# print(list[i])
# print(dict)
#
#
#
#
# mylist = [1,2,2,2,2,3,3,3,4,4,4,4]
... |
5af6317cfc6b5415fae0459bd3512661ff1a7b16 | nizbit/protonlabs | /645Project/test.py | 6,197 | 3.515625 | 4 | import tkFileDialog
def extract(text, sub1, sub2):
"""
extract a substring from text between first
occurances of substrings sub1 and sub2
"""
#Needs to be fixed
temp = text.split(sub1, 1)[-1].split(sub2, 1)[0]
temp = temp.strip()
return temp.split("\n")
def storeInDict(text... |
2a843e5b03aad6d518469ec22ae74ce2823fa9d3 | anatshk/SheCodes | /Exercises/lecture_9/lecture_9_roman_to_int.py | 1,065 | 3.796875 | 4 | def romanToInt(self, s):
"""
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
:type s: str
:rtype: int
"""
mapping = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M'... |
3c112db14262791e4149047360fcb099fd3065da | qs8607a/Algorithm-45 | /SortAlgorithm/MergeSort.py | 641 | 4.28125 | 4 | # Introduction to Algorithm - Chapter 2: Getting Started
# MERGE_SORT
def merge(left, right):
res = [];
i = 0;
j = 0;
while i < len(left) and j < len(right):
if left[i] <= right[j]:
res.append(left[i]);
i = i + 1;
else:
res.append(right[j]);
... |
a53d1f56294c7bdd720490a2ea54ecf5e57b8740 | LuizFernandoS/PythonCursoIntensivo | /Capitulo03_IntroducaoListas/03_06DinerGuestsBigger.py | 2,270 | 4.09375 | 4 | """3.6 – Mais convidados: Você acabou de encontrar uma mesa de jantar maior,
portanto agora tem mais espaço disponível. Pense em mais três convidados
para o jantar.
• Comece com seu programa do Exercício 3.4 ou do Exercício 3.5. Acrescente
uma instrução print no final de seu programa informando às pessoas que
você... |
32e80281f3f90765e59236dd5f6975168f0f1411 | mattmc96/python_notes | /main.py | 569 | 4.1875 | 4 | # 1 - Create a program that asks the user to enter their name and their age. Print out a message addressed
# to them that tells them the year that they will turn 100 years old.
# Request input from user
name = str(input('Enter your name: '))
age = int(input('Enter your age in years: '))
# Request an additional numb... |
0b69c504b2f15c83b97964893feb8d3ebbba14b9 | yparam98/leetcode-exercises | /rectangle_area_ii.py | 879 | 3.765625 | 4 | #!/usr/bin/python3
from typing import List
class Solution:
def rectangleArea(self, rectangles: List[List[int]]) -> int:
total_area: int = 0
for rectangle in rectangles:
base: int = rectangle[2]-rectangle[0]
height: int = rectangle[3]-rectangle[1]
area: int = bas... |
52893f66b264c98b56c04ae08f94c7885afeff4f | AidenJauffret/COGS18-FINAL-PROJECT | /final_project.py | 3,674 | 3.84375 | 4 | import pickle
import webbrowser
#global dictionary
song_list = {}
""" This class assigns a song URL to a chosen name. """
class URLAssignment():
global song_list
""" This function creates a dictionary of songs and their names. """
def song_assign(self, song_url, assigned_name):
song_list.update(... |
9d8b3e702a5f8258ea3c3c2039b5f68ca3bb25c6 | grigor-stoyanov/PythonAdvanced | /comprehension/flatten_list.py | 101 | 3.515625 | 4 | line = input().split(*'|')
flat = [num for ele in reversed(line) for num in ele.split()]
print(*flat) |
8a494da75b13047517588ef85cbafab832eac3e5 | d4rkr00t/leet-code | /python/leet/987-vertical-order-traversal-of-a-binary-tree.py | 713 | 3.859375 | 4 | # Vertical Order Traversal of a Binary Tree
# url: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
# medium
def verticalTraversal(root): # [1,2,3,4,5,6,7]
if (not root):
return []
tmp = {}
def dfs(node, x=0, y=0):
if (node):
if (not x in tmp):
... |
dfedf94fe6329d057d5931be38dc097d6a8a3abc | Taoge123/OptimizedLeetcode | /LeetcodeNew/python/LC_082.py | 1,457 | 3.828125 | 4 |
"""
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
"""
class ListNode:
def __init__(self, x):
self.val = x
self.ne... |
3d63f6d74bdf852fa40176f8c528c92c419c796d | gaya38/devpy | /Python/assignment/pes-python-assignments-1x.git/131.py | 317 | 3.578125 | 4 | a=[]
for i in range(4):
b=input("Enter a value:")
a.append(b)
a.append(6)
print "Large number among the five values is:"
for l in range(len(a)-1):
if (a[l]>a[l+1]):
temp=a[l]
a[l]=a[l+1]
a[l+1]=temp
else:
continue
print a[-1]
|
41128adcb41ff09632b167725a258f387ee7437c | fghjklvmbn/practice-python | /양수 음수 구별기.py | 229 | 3.8125 | 4 | number = input("숫자를 입력하십시오: ")
number = int(number)
if number < 0:
print("음수입니다.")
if number > 0:
print("양수입니다.")
if number == 0:
print("음수도 양수도 아닌 0 입니다.") |
bca34a1fd55212fe4bf920638893c8b8e017b989 | Uva4/mi_primer_programa | /spaces_dots.py | 403 | 3.640625 | 4 |
user_sentence = input('Escribe una frase: ')
space = ' '
dot = '.'
comma = ','
n_space = 0
n_dots = 0
n_commas = 0
for letra in user_sentence:
if letra in space:
n_space += 1
elif letra in dot:
n_dots += 1
elif letra in comma:
n_commas += 1
print('Espacios = {}'.format(n_space... |
8166fa37568c99cdd5411b3fd5ebe29e5dad7363 | YashKesarwani/Python_Games | /LotterySimulation.py | 777 | 3.78125 | 4 | import random
import matplotlib.pyplot as plt
account=0
x=[]
y=[]
for i in range(365):
x.append(i+1)
bet=random.randint(1,10)
#bet=int(input("Your bet from 1 to 10"))
lucky_draw=random.randint(1,10)
#print("Bet=",bet)
#print("Lucky draw= ",lucky_draw)
if bet==lucky_draw:
account=acc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.