blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
0a7def488ed51a9d0b3e3a1a5ccc8a29efa89a23 | selva86/python | /exercises/concept/little-sisters-vocab/.meta/exemplar.py | 1,648 | 4.3125 | 4 | def add_prefix_un(word):
"""
:param word: str of a root word
:return: str of root word with un prefix
This function takes `word` as a parameter and
returns a new word with an 'un' prefix.
"""
return 'un' + word
def make_word_groups(vocab_words):
"""
:param vocab_words: list of... |
6c71b4825c2811a097cb6e9c1bdd71514862f48c | sjogleka/Algorithm_and_Data_Structures | /Project 1/Code/mergeSort.py | 1,671 | 3.9375 | 4 | import random
import timeit
def merge_sort(S):
if len(S) <= 1:
return S
left=[]
right = []
middle = int(len(S) / 2)
#print(middle)
for i in range(0,middle):
left.append(S[i])
for i in range(middle,len(S)):
right.append(S[i])
#right = S[middle:]
... |
28eb69835171fcf303d217d5097649e3fba1d590 | almartins1/Probabilidad- | /Ejercicio_B/Punto_B.py | 4,205 | 3.515625 | 4 | import matplotlib.pyplot as plt #libreria para graficar
import random #libreria generar numeros aleatorios
#Punto B
#----------------------------------------------------------------------------------------------------------------------------------------
#Ejercicio 1
#-------------------------... |
c2f079ea8d6387e8b64395e0d45271c9c00ee2e6 | douglasmsi/sourcePython | /par.py | 319 | 4.125 | 4 | #!/usr/bin/python3
#!/usr/bin/python3
#Ler numero e verificar se ele e par ou impar
# e adicionar ele em uma lista com o Resultado
#[2, 'par']
#[3,'impar']
#
entrada = int(input('Numero: '))
lista = []
if (entrada%2) == 0:
lista.insert(0,[entrada,'Par'])
else:
lista.insert(0,[entrada,'Impar'])
print(lista)
|
7486bf329791269150ec63ea1153094fa0a6a448 | douglasmsi/sourcePython | /loopNomes.py | 303 | 4.0625 | 4 | #!/usr/bin/python3
#Lista de nome vazia
# Ler nomes, adicionar na lista até digitar sair
#mostrar a lista no final
lista = []
while True:
valor = input("Digite um nome ou Sair : ")
if valor.strip().lower() == 'sair':
break
lista.append(valor)
print('Lista: {}'.format(lista))
|
47de22d59f7d60d09ecccecaf4d461e5ed3aeacb | ashishthapa08/Madlibs | /Madlibs.py | 1,035 | 3.71875 | 4 | STORY = "This morning %s woke up feeling %s. 'It is going to be a %s day!' Outside, a bunch of %ss were protesting to keep %s in stores. They began to %s to the rhythm of the %s, which made all the %ss very %s. Concerned, %s texted %s, who flew %s to %s and dropped %s in a puddle of frozen %s. %s woke up in the year %s... |
2d609edcc83ebf5641d3f252f1f0cbab01a462f0 | LiT-BRo/Filenames-Handler | /(v0.0.1)/main.py | 1,927 | 3.609375 | 4 | """ @name Filenames Handler
@version 0.0.1
@description Helps in generating a list of the files in a directory (with multiple files). Warm regards, LiTBRo! ;)
@author LiTBRo
@source https://github.com/LiT-BRo
@date 31 Aug 2021
"""
import tkinter as tk
from tkinter import filedialog
import os
# # #... |
7101a1e9f48462829805a56f338eb61782ff0c59 | eAlasdair/Fighting-Fantasy-GUI | /ff_extras.py | 3,668 | 3.640625 | 4 | """
Alasdair Smith
Started 20/12/2016
Module for the Fighting Fantasy Program
Includes the initial decision question GUI, a few helper functions,
and code to run the whole program
For Fighting Fantasy Gamebooks:
Ian Livingstone's Caverns of the White Witch & similar
"""
from tkinter import *
from tkin... |
17c47ebb8a42c670d05d90ffe2c5f0a18bd6c298 | guillevn/python | /zodiaco.py | 1,409 | 3.765625 | 4 | # -*- coding: cp1252 -*-
def zod():
dia=input("Introduce el día de nacimiento")
mes=input("Introduce el mes de nacimiento (en número)")
if mes==1:
if dia<=20:
print "Capricornio"
else:
print "Acuario"
elif mes==2:
if dia<=19:
print "Acuario"
... |
dae2b6ecbf75a847305d51ddc1e1a1dfd4d132cb | PradipH31/Python-Crash-Course | /Part_II/rw_visual.1.py | 814 | 3.71875 | 4 | #!./P2ENV/bin/python
# Random Walk visually
import matplotlib.pyplot as plt
from random_walk import RandomWalk
rw = RandomWalk(5000)
rw.fill_walk()
# Colormap for the walk light color(start) to dark color(end) of the walk
# point_numbers stores the steps of the walk in order and used in c=
point_numbers = list(range... |
3db5a554acc92051d4ec7a544a4c922fcad49309 | PradipH31/Python-Crash-Course | /Chapter_9_Classes/C2_Inheritance.py | 1,094 | 4.5625 | 5 | #!./ENV/bin/python
# ----------------------------------------------------------------
# Inheritance
class Car():
"""Class for a car"""
def __init__(self, model, year):
"""Initialize the car"""
self.model = model
self.year = year
def get_desc_name(self):
"""Get the descrip... |
2c491529962855c0a6a23cc5fb8dc6c3b328887b | PradipH31/Python-Crash-Course | /Part_II/scatter_square.py | 1,025 | 3.53125 | 4 | #!./P2ENV/bin/python
# Imorting the pyplot module
import matplotlib.pyplot as plt
# plt.scatter(x, y, s=size)
plt.scatter(2, 4, s=500)
# Modifying display of both x and y axis
plt.tick_params(axis='both', labelsize=14)
# scatter with a series of points
# use two lists of equal dimension
# plt.scatter(list_x, list_y)... |
c684cf0f8d15e4e684b2668eaf0bfadd8b30306a | PradipH31/Python-Crash-Course | /Chapter_9_Classes/C1_Book.py | 959 | 4.4375 | 4 | #!./ENV/bin/python
# ----------------------------------------------------------------
# # Classes
class Book():
"""Class for a book"""
def __init__(self, name, year):
"""Initialize the book with name and year"""
self.name = name
self.year = year
def get_name(self):
"""Ret... |
1b776fe62f0e7edd85875a4dfeb20a66100b7824 | sadhikari0102/magic-temp-analyzer | /app.py | 1,562 | 3.609375 | 4 | from csv import DictReader
from temp_log_processor import TempLogProcessor
def start():
filepath = input("Enter File path for data set:")
temp_log_processor = TempLogProcessor()
with open(filepath, 'r') as csvfile:
filereader = DictReader(csvfile)
print("Processing Data...")
for ro... |
c05013b2034536fbdf145939e37cf709037bb014 | amandotzip/stalinsort | /runner.py | 3,404 | 3.515625 | 4 | import random
from art import *
from pygame import mixer
#load music
mixer.init()
mixer.music.load("Moskau Ear Destruction.mp3")
mixer.music.play()
# list of random unique numbers
list = random.sample(range(100), 50)
print(list)
#If a number is larger then the one after it, delete the comrade that has fallen out of ... |
3ceb5c72bc49fade422fe4c59f1e6a8cb6e1dd99 | gradam/project-euler | /041_Pandigital_prime.py | 588 | 3.84375 | 4 | def is_pandigital(x):
y = str(x)
cyfry = []
for z in y:
if z in cyfry or int(z) == 0:
return False
cyfry.append(z)
numbers = "123456789"
cyfry.sort()
lenght = len(cyfry)
if "".join(cyfry) == numbers[0:lenght]:
return True
return False
def is_prime(x)... |
180b09a4945cbbe0ec1ed54b6c764dc88e85b0f6 | yulya2787/python_advanced | /less3/#1.py | 839 | 3.515625 | 4 | import time
def decorator(num_of_repeats=1):
def time_to_do_function(function):
def wrapped(*args, **kwargs):
dic_result = {}
for i in range(num_of_repeats):
dic_result[f"result for iteration {i}"] = {}
start_time = time.time()
end_tim... |
3b2023ce61bfa403f7d4f4b340e54b2140614026 | yulya2787/python_advanced | /less2/#2.py | 1,011 | 4.21875 | 4 | '''Создать класс магазина. Конструктор должен инициализировать
значения: «Название магазина» и «Количество проданных
товаров». Реализовать методы объекта, которые будут увеличивать
кол-во проданных товаров, и реализовать вывод значения
переменной класса, которая будет хранить общее количество
товаров проданных всеми ма... |
80b9d8d6f0249274c26b67d9a7fb07a374762955 | yulya2787/python_advanced | /less1/#1.py | 102 | 3.671875 | 4 | #1
N = []
n = 10
i = 0
for i in range(n):
if i % 2 == 0 and i != 0:
N.append(i)
print(N)
|
9a76041b4f7465fc6061ed4ee3efb65899a258db | alexugalek/tasks_solved_via_python | /HW1/upper_lower_symbols.py | 374 | 4.46875 | 4 | # Task - Count all Upper latin chars and Lower latin chars in the string
test_string = input('Enter string: ')
lower_chars = upper_chars = 0
for char in test_string:
if 'a' <= char <= 'z':
lower_chars += 1
elif 'A' <= char <= 'Z':
upper_chars += 1
print(f'Numbers of lower chars is: {lower_chars}... |
7a2cbaac307d558ea191c82d097872ef0b62c943 | alexugalek/tasks_solved_via_python | /HW1/task_48.py | 2,339 | 3.6875 | 4 | def seven_segment(lit_seg, broken_seg):
"""Two displays with seven segment screen
:param lit_seg: Contains the lit segments as a set of
letters representing segments
:param broken_seg: Contains the broken segments as a set of
letters representing segments
:return: The total number that the devi... |
bb04a57a280a4c84e6042b210fc1500a5c57d3c4 | alexugalek/tasks_solved_via_python | /HW2/task_6.py | 973 | 4.09375 | 4 | def ordered_list(input_list):
"""Ordered list
:param input_list: list of integers
:return: sorted list where all 0 elements in the end of list
"""
el_index, iter_count = 0, len(input_list)
while iter_count > 0:
if not input_list[el_index]:
input_list.append(input_list.pop(e... |
fea598032ae2a1c7676e6b0286d2fae1362bdfa3 | alexugalek/tasks_solved_via_python | /HW1/task_5.py | 418 | 4.40625 | 4 | def add_binary(a, b):
"""Instructions
Implement a function that adds two numbers together
and returns their sum in binary. The conversion can
be done before, or after the addition.
The binary number returned should be a string.
"""
return bin(a + b)[2:]
if __name__ == '__main__':
a = ... |
3a30283bb1d94a297284d4957067ef29367ac89b | alexugalek/tasks_solved_via_python | /HW1/task_21.py | 1,555 | 3.953125 | 4 | def simple_nod(number):
"""Instructions
Quick find of simple dividers
for numbers
"""
nod = 2
temp_list = []
while nod ** 2 <= number:
if not number % nod:
temp_list.append(nod)
number //= nod
else:
nod += 1
if number > 1:
temp... |
94526a71e870c86247601dc6b790b650e154d939 | alexugalek/tasks_solved_via_python | /HW4/task_7.py | 503 | 4.0625 | 4 | def nd_pow_of_two(number):
"""Largest divisor of number
:param number: integer number != 0
:return: largest divisor of number which also is a power of two
"""
nd_pow = 1
while number % nd_pow == 0:
nd_pow <<= 1
return nd_pow >> 1
if __name__ == '__main__':
for i in range(1, 22... |
6889e39e73935e704d91c750b3a13edb36133afc | alexugalek/tasks_solved_via_python | /HW1/task_23.py | 1,327 | 4.4375 | 4 | def longest_slide_down(pyramid):
"""Instructions
Imagine that you have a pyramid built of numbers,
like this one here:
3
7 4
2 4 6
8 5 9 3
Here comes the task...
Let's say that the 'slide down' is a sum of consecutive
numbers from the top to the bottom of the pyramid. As
... |
acdcddc6a6e17466c36f1ad4ca46efd015689153 | alexugalek/tasks_solved_via_python | /HW1/task_53.py | 750 | 4.125 | 4 | def longest_palindromic(a):
"""The longest palindromic"""
result = ''
for i in range(len(a)):
for j in range(i, len(a)):
tmp_val = a[i:j + 1:1]
if tmp_val == tmp_val[::-1] and len(a[i:j + 1:1]) > len(result):
result = a[i:j + 1:1]
return result
if __name... |
3a9c3ff81d9973528d292203111105d148ace624 | alexugalek/tasks_solved_via_python | /HW1/task_14.py | 575 | 4.0625 | 4 | def productfib(prod):
"""Instructions
prod:: given integer natural argument
return:: list with two fibonacci numbers
whose multiplication >= prod and
flag ='False' if multiplication > prod,
flag = 'True' if multiplication = prod
prod = 45678
return = [233, 377, False]
"""
print(... |
eff87b15ecc852269e96484d1c89f0b464d4b1ad | JSalmen13/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 513 | 4.09375 | 4 | #!/usr/bin/python3
"""
text indention function
text is the string to be treated
"""
def text_indentation(text):
""" text indention function
text is the string to be treated """
if not isinstance(text, str):
raise TypeError("text must be a string")
cond = ['.', ',', '?', ':']
char = 0
w... |
81322dd226018292a5d3e33cfcc85cff0313ba56 | JSalmen13/holbertonschool-higher_level_programming | /0x05-python-exceptions/4-list_division.py | 547 | 3.765625 | 4 | #!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
my_list_results = []
for x in range(list_length):
try:
result = my_list_1[x] / my_list_2[x]
except (ZeroDivisionError):
print("division by 0")
result = 0
except (IndexError):
... |
bca71a3a39abc3d2c409af30d54fd7abf9c978ba | JSalmen13/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 303 | 3.859375 | 4 | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
L = len(my_list)
if L > 0:
new = list(my_list)
for K in range(L):
if my_list[K] % 2 == 0:
new[K] = True
else:
new[K] = False
else:
return(None)
return(new)
|
11addd1e999a77d3e0168995e37b6679521871c3 | JSalmen13/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 407 | 3.796875 | 4 | #!/usr/bin/python3
"""
int subclass
"""
class MyInt(int):
"""
int subclass
"""
def __init__(self, value):
"""
MyInt int
"""
self.value = value
def __eq__(self, obj):
"""
equal int
"""
return (obj != self.value)
def __ne__(self, ... |
61d6ff7bfcb53630a1b0ae3643db8af56fca8c14 | g8gg/PythonLearning | /FluentPython/02-An-Array-of-Sequences/bisect_demo.py | 1,659 | 3.703125 | 4 | # Managing Ordered Sequences with bisect
# BEGIN BISECT_DEMO
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position... |
26e46d124031240c3b9d601a9e75e57d01021015 | g8gg/PythonLearning | /FluentPython/02-An-Array-of-Sequences/slicing.py | 3,569 | 4.34375 | 4 | # Slicing
# 我们都知道sequences can be sliced using the s[a:b] syntax
# 所有的sequence types都支持切片,如: list, tuple, str
# Why Slices and Range Exclude the Last Item
# The Pythonic convention of excluding the last item in slices and ranges works well with the zero-based indexing
# used in Python, C, and many other languages. So... |
a5306511c39e1a2bd0e3077f86df25e6e47f2dc6 | firozsujan/pythonBasics | /Lists.py | 1,629 | 4.1875 | 4 | # Task 9 # HakarRank # Lists
# https://www.hackerrank.com/challenges/python-lists/problem
def proceessStatement(insertStatement, list):
if insertStatement[0] == 'insert': return insert(insertStatement, list)
elif insertStatement[0] == 'print': return printList(insertStatement, list)
elif insertStatement... |
86b3488e679b6e34d43d0be6e219a6f01761b3e1 | firozsujan/pythonBasics | /StringFormatting.py | 655 | 4.125 | 4 | # Task # HackerRank # String Formatting
# https://www.hackerrank.com/challenges/python-string-formatting/problem
def print_formatted(number):
width = len(bin(number)[1:])
printString = ''
for i in range(1, number+1):
for base in 'doXb':
if base == 'd':
width = len(bin(nu... |
e6da2815776433af2a7203c6beec50524a9eddd8 | PrajitR/elevator_problem | /simulation.py | 6,199 | 3.828125 | 4 | from elevator import Elevator, Actions
import random
import argparse
import math
class Simulation:
"""
Runs the elevator simulation.
"""
def __init__(self, nfloors, max_new_people):
self.nfloors = nfloors
self.expo_lambda = [1. / (f ** 2 + 1) for f in xrange(nfloors)]
self.intervals = [int(random.expovaria... |
49d9d519e30080386d6ac02a836f82d235d36c9e | JeffHritz/practice | /adventure_game.py | 2,111 | 3.796875 | 4 | # adventure_game.py - Jeff Hritz
# Currently still in development
"""
Text-based adventure game.
"""
import time
def intro():
"""Intro sequence."""
print("\n" * 100)
print("You are asleep, but still aware.")
time.sleep(2)
print("The world is a blur around you.")
time.sleep(2)... |
57c8a8916a99f86325a623e32a88dadad0bf0f05 | cameroncurry/SD-DeckBuildingGame | /src/Computer.py | 2,735 | 3.546875 | 4 | from time import sleep
from Player import *
class Computer(Player):
def __init__(self,aggressive):
super(Computer,self).__init__("Computer")
self.aggressive = aggressive
'''Computer game logic implemented here'''
def move(self,player,central,view):
view.displayTurn(self,player)
... |
ce7a7f3362652f37bbec4c976a02310a007e9c3d | vinikuttan/smallcodes | /dict_normalizer.py | 1,275 | 4.125 | 4 | #!/usr/bin/python
__author__ = 'vineesh'
def merge_nested_dict(mydict):
"""
flattening nested dict
"""
if isinstance(mydict, dict):
result = mydict.copy()
for each in mydict:
if isinstance(mydict[each], dict):
result[each] = mydict[each].keys()
... |
77bedb2d4338eddef918152c4ed8ad93c82e55ba | rjafar/cracking-coding-interview | /data_structures/Stack/stackMin.py | 506 | 3.921875 | 4 | # Implements a method to find the min element in an unsorted stack
# Time Complexity: O(1)
from myStack import MyStack
class StackMin:
def __init__(self):
self.sMin = MyStack()
def push(self,data):
if data < self.min():
self.sMin.push(data)
self.push(data)
... |
e0d8d959ca2a4aa0dc407e9b8d52311bbf1882db | rjafar/cracking-coding-interview | /data_structures/LinkedList/loopDetection.py | 400 | 3.96875 | 4 | from linkedList import LinkedList
# Description: Find node where circular linked lists begins
# Input: linked list
# Output: beginning of loop Node
# Time Complexity: O(n)
def loopDetection(LL):
curr = LL.head
m = {}
while(curr):
if curr not in m:
m[curr] = 1
els... |
d34060aeade9679e2a5eb9608af28aff0fcd9291 | dcoluccia/Pytilities | /tex_table.py | 3,276 | 3.75 | 4 | """
Write a TeX table given numpy array input.
@author: ColucciaD
"""
import os, subprocess
###############################################################
def write_table(col_names,
row_names,
content,
name = 'table'):
"""
Write in a TeX file a table... |
2f5785f87b438aa89bcc88f403048f69545259ac | oscar7692/python_files | /agendaPyton.py | 2,929 | 4.15625 | 4 | #!/usr/bin/python3.7
def menu():
print('******Directorio de Contactos******')
print('1- Crear nombre de la lista')
print('2- Agregar Contacto')
print('3- Buscar en directorio')
print('4- Editar contactos')
print('5- Mostrar contactos')
print('6- Cerrar directorio')
print()
def ... |
a004d1014405736eddb7ea1a028643e44e176a10 | dineshreddymarri/Python | /homework3program1.py | 185 | 3.78125 | 4 | def bunnyEars(bunnies):
if (bunnies == 0):
return 0
else:
if (bunnies % 2 == 0):
return 3 + bunnyEars (bunnies - 1)
else:
return 2 + bunnyEars (bunnies - 1)
|
c967cfecad0854422e89f7869cbde592bab0a690 | carlitrosglz/python-course | /01-basics/generators.py | 973 | 3.984375 | 4 | def generaNumerosPares(limit):
num = 1
while num < limit:
# YIELD construye un Iterable que contiene (en este caso) la lista con los numeros pares correspondientes
# Entrega los valores de uno en uno, por lo que será necesario ir llamando al método .next() del Iterable
# para obtener to... |
2f51299a035b6d120be53097a2fe07555d3d9e77 | muraliR/data_classes | /date_extra_constructor.py | 456 | 3.625 | 4 | from dataclasses import dataclass
from time import localtime
# example with alternate constructor
@dataclass
class Date:
year: int
month: int
day: int
@classmethod
def today(cls):
d = cls.__new__(cls)
t = localtime()
d.year = t.tm_year
d.month = t.tm_mon
d.... |
1f463d9d79a5a49ed4f1b586c5b5f759cdd73b04 | muraliR/data_classes | /named_tuple.py | 348 | 3.859375 | 4 | from typing import NamedTuple
class Person(NamedTuple):
person_id: int
name: str
gender: str
if __name__ == '__main__':
person_1 = Person(100,'Guido','M')
person_2 = Person(200,'Eric V Smith','M')
person_3 = Person(100,'Guido','M')
print(person_1 == person_3)
print(person_1 >= person_... |
4130a25182b9b5afaf46edaef4a7035cce4e1af1 | ankitkumar5422/FIR-management-systam | /dash.py | 11,739 | 3.515625 | 4 | from tkinter import *
import sqlite3
from tkinter.messagebox import *
con = sqlite3.Connection('DB.db')
cur = con.cursor()
def create():
cur.execute("create table if not exists login(username varchar(20) PRIMARY KEY, password varchar(20), name varchar(50))")
def create_admin():
cur.execu... |
f946999aa32cb00ef3ffa6c95937deb1841aa7b5 | scottkenanderson/advent-of-code-2018 | /2018-12-01/second_star.py | 991 | 3.671875 | 4 | def get_file(filename):
with open(filename) as f:
return [(line[0], line[1:].strip()) for line in f]
FUNCTIONS = {
'+': lambda num, change: num + change,
'-': lambda num, change: num - change
}
def get_number(num, operation, change):
f = FUNCTIONS[operation]
if not f:
raise Excep... |
34cbba0cf1f3f1a8982a2e15672c4d01e2774d4d | rishi4758/python-programmes- | /sql.py | 430 | 3.609375 | 4 | import sqlite3
c=sqlite3.connect("thpolkj2.db")
s=c.cursor()
s.execute("create table emp5(name text,address text,age real)")
s.execute("insert into emp5 values('rishav','lpu',20)")
s.execute("insert into emp5 values('adarsh','pune',000)")
s.execute("select * from emp5")
l1=[(4,'we',23),(25,'ty',9),(0,'oi',98)]
... |
87c593b7284aa67addbc59e21a02107da29b17af | rishi4758/python-programmes- | /gui prac.py | 1,010 | 3.609375 | 4 | from tkinter import *
b=Tk()
def fun1():
val=entry.get()
val1=entry.get()
sum=val+val1
sum.insert()
def fun2():
val=entry.get()
val1=entry.get()
sum=val-val1
sum.insert()
def fun3():
val=entry.get()
val1=entry.get()
sum=val*val1
sum.insert()
def fun4():
... |
0f71aa582878c764fd36666dc798c00b3fbf02c5 | m1plessnit/AAURecommender | /Assignment2/task2_1.py | 710 | 3.96875 | 4 | # Task 2.1: Getting used to Series
import pandas as pd
import numpy as np
def main():
print("Task 2.1: Getting used to Series")
# Create Panda's Series-instance based on an array
data = np.array(['Toy Story', 'Jumanji', 'Grumpier Old Men'])
series = pd.Series(data)
print("\n--- Print first eleme... |
6f7b726e2501ac97cfe1c625ae5192c8f96300b5 | ayush3298/geekforgeeks_practice | /contiguous integers in array.py | 426 | 3.59375 | 4 | #https://practice.geeksforgeeks.org/problems/check-if-array-contains-contiguous-integers-with-duplicates-allowed/0
# running time = 0.2
for _ in range(int(input())):
l = int(input())
lst = sorted(list(map(int, input().split())))
lst = list(set(lst))
c = 0
for i in range(len(lst) - 1):
if ls... |
25579f8fb61bfe94ad715aa3234c6aa16618a181 | iisharankov/Effelsberg | /Protocol_Practice/UDP Suit/UDP_Basic_Server.py | 2,679 | 3.546875 | 4 | import socket
# get the according IP address
localIP = socket.gethostbyname(socket.gethostname())
# Sets the port and buffer size as constants for later use
bufferSize = 1024
# port = 12345
server_address = ('', 0)
# Create a datagram Socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGR... |
21c759af95e15cc503f9dd74189b237f891f549d | imriven/coding_challenges | /hour_to_seconds.py | 239 | 3.875 | 4 | # https: // edabit.com/challenge/nyeNvKWdDFKRAk4Da
def how_many_seconds(hours):
minutes = hours * 60
seconds = minutes * 60
return seconds
print(how_many_seconds(2))
print(how_many_seconds(10))
print(how_many_seconds(24))
|
12efdf73aa2b9be29fead08b57895e7f1fcc072a | mikegleen/blackgold | /src/node.py | 4,847 | 3.75 | 4 | """
"""
from __future__ import annotations
import sys
from typing import Union, TYPE_CHECKING
if TYPE_CHECKING: # kludge to avoid circular imports at run time
from player import Player
class Node:
"""
cost: Number of movement points it costs to enter this node.
exhausted: True if a derrick has been ... |
e13507decfacf5f7dd3570bf941733cf8eee7470 | mikegleen/blackgold | /src/isort.py | 540 | 3.671875 | 4 | """
func insertionsort(A []*Node) {
for i := 1; i < len(A); i++ {
key := A[i]
j := i - 1
for j > -1 && A[j].Distance > key.Distance {
A[j+1] = A[j]
j -= 1
}
A[j+1] = key
}
}
"""
def insertionsort(a):
for i in range(1, len(a)):
key = a... |
ce4e41633801a3c8925bb13d6f80b2a7fb086890 | mhdz9/codewars | /Python/number-star-ladder.py | 608 | 4.0625 | 4 | #Task
# Using n as a parameter in the function pattern, where n>0, complete the codes to get the pattern (take the help of examples):
#Note: There is no newline in the end (after the pattern ends)
#Examples
# pattern(3) should return "1\n1*2\n1**3", e.g. the following:
# 1
# 1*2
# 1**3
#
# pattern(10): should return t... |
6c89918ec65409dfce3652bd902c75a889881234 | OvernightFries/Mission-Bit-Projects | /Folder/Functions/lists.py | 1,953 | 3.90625 | 4 | last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)]
subjects = [("physics"),("calculus"),("poetry"),("history")]
grades = [(98), (97), (85), (88)]
[print(values) for values in zip(subjects, grades)]
subjects.append(("Computer Science"))
grades.append((100))
gradebook =... |
e1877849ae9583f8ff64ae02aae1b613f308a14d | TFStudents/PythonLearn | /com/tfstudents/GUI/test2.py | 702 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from Tkinter import * # 导入 Tkinter 库
root = Tk() # 创建窗口对象的背景色
# 创建两个列表
li = ['C','python','php','html','SQL','java']
movie = ['CSS','jQuery','Bootstrap']
listb = Listbox(root) # 创建两个列表组件
listb2 = Lis... |
de44aea78510612da8472d8d74ae4d2de4dca04f | hyuji946/project_euler | /untitled.py | 97 | 3.71875 | 4 | def fib(x):
if x==1:
return 1
if x==2:
return 2
return fib(x-1)+fib(x-2)
print fib(8)
|
2ea41c44a4335e6f9329bce0ea7efe410ba309fd | hyuji946/project_euler | /p001.py | 510 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Project Euler Problem 1
10未満の自然数のうち, 3 もしくは 5 の倍数になっているものは
3, 5, 6, 9 の4つがあり, これらの合計は 23 になる.
同じようにして, 1000 未満の 3 か 5 の倍数になっている数字の合計を求めよ.
"""
def f35(x):
if x%3==0 or x%5==0:
return True
else:
return False
ans=0
for i in range(1,1000):
if f35(i):
... |
1c4f86c98c0e7d6aa7b32652eaba3b5c8500ea89 | hyuji946/project_euler | /01 解答例/p038.py | 1,197 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
===================================
Project Euler Problem 38
===================================
192 に 1, 2, 3 を掛けてみよう.
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
積を連結することで1から9の パンデジタル数 192384576 が得られる.
192384576 を 192 と (1,2,3) の連結積と呼ぶ.
同じようにして, 9 を 1,2,3,4,5 と掛け連結することで
パンデジタル数 918273645 ... |
ecf576b0007158929c58eed930917367982a2419 | cprimera/projects | /School Projects/Obstacle Avoider/Queue.py | 587 | 3.75 | 4 | ####################################################################
# Created by Christopher Primerano on 05-03-2012. #
# Copyright (c) 2012 Christopher Primerano. All rights reserved. #
# #
############################################... |
313bf24b6a88a2458d94d3ecad0abf2e9c7ba83f | av1kav/jupyter-notebooks | /Data Analytics/dpad/chisquare.py | 937 | 3.765625 | 4 | #chi square test.
def chiSquareTest(nrows,ncols,matrix):
"""
chiSquareTest(nrows,ncols,matrix):
Returns the Chi-Square value (float) for a given matrix[nrows][ncols] of data.
"""
expectedMatrix = [[0.0 for j in range(ncols)] for i in range(nrows)]
rowSum = [0 for i in range(nrows)]
colSum = [0 for j... |
817eb6d9822b5a8f701f71bb98e39dd07d9f50f0 | ElianAbrao/Advanced-virtual-assistant-with-voice-control | /main.py | 993 | 3.65625 | 4 | #Importing Libraries
import speech_recognition as sr
import os
#Main Function
def voice_recorder():
#enable user microphone
recorder = sr.Recognizer()
#using microphone recordings
with sr.Microphone() as source:
recorder.adjust_for_ambient_noise(source)
audio = recorder.listen(sour... |
ae56a301dde6a0f4e3063170dcab02000c70b6f8 | AdamHess/review-data-structures-in-python | /binarytree.py | 1,221 | 3.75 | 4 | class BinaryTreeNode:
def __init__(self, value = None):
self.__right = None
self.__left = None
self.__value = value
def getLeft(self):
return self.__left
def setLeft(self, leftNode):
self.__left = leftNode
def getRight(self):
return self.__right
def setRight(self, rightNode):
self.__right = rightN... |
d2c38d3b797e807201aad930bdeb22a2206a360a | PKR-808/30-Days-of-Code-in-Python-HackerRank-Challenge | /Day_9.py | 508 | 3.90625 | 4 | #!/bin/python3
#The additional codes of file write were already there in the HackerRank Python 3 Console
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(num):
if num == 1:
return 1
else:
fact = num * factorial(num-1)
return... |
b3f52b64596a5d29add18105564e5594693d3254 | xiyanjun/LeetCode | /476NumberComplement.py | 365 | 3.6875 | 4 | class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i=1
while i<=num:
num^=i
i=i<<1
return num
def main():
num=5
solution=Solution()
result=solution.findComplement(num)
print(... |
7c27d06882aab4e2fece0db82177a8b543cffc16 | xiyanjun/LeetCode | /28ImplementstrStr().py | 463 | 3.65625 | 4 | class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack)-len(needle)+1):
if haystack[i:len(needle)+i]==needle:
return i
return -1
if __name... |
eb0d5b8a30fdb14d5440b85d6aa5dbe60772b6f1 | xiyanjun/LeetCode | /70ClimbingStairs.py | 366 | 3.625 | 4 | class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
F=list(range(n+1))
F[0]=1
F[1]=1
for i in range(2,n+1):
F[i]=F[i-1]+F[i-2]
return F[n]
if __name__=='__main__':
solution=Solution()
res... |
9f4519c7c6314831ae221e86eb3f096e3fffa8eb | xiyanjun/LeetCode | /5LongestPalindromicSubstring.py | 507 | 3.6875 | 4 | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
for i in range(len(s)-1,-1,-1):
j=0
while i+j<=len(s)-1:
if s[j:i+j+1]==s[j:i+j+1][::-1]:
return s[j:i+j+1]
... |
a484c1fcb0fa8e8fa004feef5b22e8aaca455df0 | xiyanjun/LeetCode | /216CombinationSum3.py | 667 | 3.703125 | 4 | class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
ans=[]
def search(s,count,sums,nums):
if count==k and sums!=n:
return
if count==k and sums==n:... |
e043503d5bd9f2fe849f73d606bb5c2880fcb0fb | arpancodes/learning-python-mit-6.00.1x | /week-2/gcd-recur.py | 540 | 3.9375 | 4 | '''
A clever mathematical trick (due to Euclid) makes it easy to find greatest common divisors. Suppose that a and b are two positive integers:
If b = 0, then the answer is a
Otherwise, gcd(a, b) is the same as gcd(b, a % b)
'''
def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive intege... |
c5840f40495b9d156c201043fa3ffa80477d4618 | k-vader/CST-205-lab13 | /lab13.py | 3,952 | 3.90625 | 4 | # Ken Vader
# Ngoan Nguyen
# Chris Pina
# Ken Vader
# Lab 13, Part 1
# 12/8/2015
import time
import random
userInputCount = 0
story = """
As more than 100 stout and bearded men, all dressed in various shades of red and green,
board a train to go rattling through the Michigan countryside for no apparent reason, I... |
87324442d3dabfdcae8ef4bbea84f21f1586d663 | drdiek/Hippocampome | /Python/dir_swc_labels/lib/menu/select_processing.py | 1,109 | 4.125 | 4 | def select_processing_function():
reply = ''
# main loop to display menu choices and accept input
# terminates when user chooses to exit
while (not reply):
try:
print("\033c"); # clear screen
## display menu ##
print 'Please select ... |
c3c685f3afdbb97de4e31153df4804554bbeaf05 | ankurshaswat/AlphaGo-Zero | /submission/alphago_zero_sim_3/utils_3/go_board.py | 7,706 | 3.5625 | 4 | """
Wrapper over Board class of pachiy_py
"""
import numpy as np
import pachi_py
BLACK = np.array([1, 0, 0])
WHITE = np.array([0, 1, 0])
EMPTY = np.array([0, 0, 1])
MAX_MOVES = 250
class GoBoard():
"""
Wrapper over board class to modify representations and return new copies.
"""
def __init__(self,... |
d70d2fe8ee72724461584894e11239525c42352e | TheSentinel36/DFS-Scraper | /lib/make_db_stats.py | 10,794 | 3.8125 | 4 |
"""
Add something to check that player ID is in ID list.
"""
class Player(object):
def __init__(self, date, game_record):
"""
See specific sport subclasses for game_record format.
"""
self.date = date
self.name = game_record[1]
self.fd_position = None
self.f... |
cd9d4078611c026fb4d55e116d5c0fd4d93ceaea | yuvika22/hackerrank-python | /basic/Lists.py | 735 | 3.984375 | 4 | # Solution https://www.hackerrank.com/challenges/python-lists/problem
if __name__ == '__main__':
n = int(input())
l = []
for _ in range(n):
function, *param_input = input().split()
param_list = list(map(int, param_input))
# print(function, param_list)
if function == "insert":... |
f77924a09f7f0fd2a7eafd266a54a653dd79d13b | dmikos/PythonExercises | /geekbrains.ru/lesson_7759-Интенсив по Python/gibbet.py | 2,401 | 4.125 | 4 | #!/usr/bin/python3
import random
import turtle
import sys
# https://geekbrains.ru/lessons/7759
# 1:25:16
def gotoxy(x, y): #перемещаем курсор
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
def draw_line(from_x, from_y, to_x, to_y): #
gotoxy(from_x, from_y)
turtle.goto(to_x, to_y)
def dra... |
f294921e695cf0ff1c9bed573ffb86f3dd2fc56c | Ellian-aragao/URI | /py/area.py | 395 | 3.6875 | 4 | vet = [float(x) for x in input().split()]
total = (vet[0] * vet[2])/2
print('TRIANGULO: {:.3f}'.format(total))
total = vet[2] * vet[2] * 3.14159
print('CIRCULO: {:.3f}'.format(total))
total = ((vet[0] + vet[1])*vet[2])/2
print('TRAPEZIO: {:.3f}'.format(total))
total = vet[1] * vet[1]
print('QUADRADO: {:.3f}'.format... |
159de7145a60a9da5636b257b83af059efd80479 | Riztydogcio/Python-for-Absolute-Beginners | /20181015_if_else_conditional_logic.py | 478 | 3.921875 | 4 | #age = input("enter age: ")
#if int(age) >= 12:
#print("Age in 10 years is", int(age) + 10)
#else:
#print("It's good to be", age)
def check_guess(letter, guess):
guess = input("guess the letter: ").lower()
if guess.isdigit() == True:
print ("Invalid")
elif guess == letter:
print("Co... |
f46893c5784cc16ad9c4bcaf19d47a126e1f02a5 | Granbark/supreme-system | /binary_tree.py | 1,080 | 4.125 | 4 | class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST():
def __init__(self):
self.root = None
def addNode(self, value):
return Node(value) #returns a Node, see class
def addBST(self, node, number): #node = current node, number is what yo... |
7c02ca47e32dcdb136b27e68fd1d2912f42f6852 | traviskemper/streamm | /src/angles.py | 10,748 | 3.53125 | 4 | """
Class data structures for 2, 3, 4 point groupings of Particle objects
"""
import copy, sys
class Angle:
"""
Data structure for describing any 3-point associatiaon of Particle-s
"""
def __init__(self, pgid1=0, pgid2=0, pgid3=0, theta0=0.0, type="blank"):
"""
Constructor for a genera... |
788c30719fe1c0a38f2e94e785af84fbf17d2573 | albertoferreirademelo/13-datastructure-and-algorithms | /s_sort.py | 11,541 | 4.21875 | 4 | #-*- coding: utf-8 -*-
'''
Author: Alberto Ferreira
Course: Datastructures and algorithms (Umeå University)
Teacher: Lena Kallin Westin
Python 3.3
'''
import string
import random
import sys
from DirectedList import *
#function to read a directed list.
def read_DirList(dir_list):
pos = dir_list.firs... |
6a5cf3421133b39a0108430efee4d3c9ba51933f | megnicd/programming-for-big-data_CA05 | /CA05_PartB_MeganMcDonnell.py | 2,112 | 4.1875 | 4 | #iterator
def city_generator():
yield("Konstanz")
yield("Zurich")
yield("Schaffhausen")
yield("Stuttgart")
x = city_generator()
print x.next()
print x.next()
print x.next()
print x.next()
#print x.next() #there isnt a 5th element so you get a stopiteration error
print "\n"
citie... |
1c538c48a6373675104d4596ce5837ca2ae4c57a | jshumate8/learnPython | /tipcal.py | 285 | 3.8125 | 4 | string1 = raw_input("What is the total amount?")
string2 = raw_input("What percentage of tip do you want to leave?")
num1 = float(string1)
num2 = float(string2)
result= (num1 * num2 *.01)
money= "${:,.2f}" .format(result)
message = "The tip amount is {0}" .format(money)
print message |
8b5c88b0e70652ccd9d545014f0ab49d4c2c2e6a | jshumate8/learnPython | /factorial.py | 634 | 3.84375 | 4 | #again_prompt = True
#while again_prompt:
user_num = int(raw_input("Please give me a number: "))
factorial = 1
for i in range(1, user_num +1):
factorial = factorial*i
print "The factorial of", user_num, "is",factorial
#for i in range((user_num)-1, -1, -1):
# print(user_num*i)
# for i in range(len(user_nu... |
5f1d15fdcae68cba74fd923ec972f9148ce33bcd | MiyaJ/py-study | /basic/set.py | 320 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/12/21 14:36
# @Author : Caixiaowei
# @File : set.py
# @Desc : 集合
set1 = set('abcdefgccc')
set2 = {1, 2, 'hello', 'world', 1, 'a'}
print(type(set1), set1)
print(set1)
print(set2)
print('diff:', set1.difference(set2))
i = iter(set2)
for x in i:
print(x, end=' ')
|
386520fc408963500ee3799862d33f0945dd016a | xcyxiner/python_timesay | /2.py | 848 | 3.515625 | 4 | import json
import numpy as np
import matplotlib.pyplot as plt
import random
import pandas as pd
import csv
with open('timesay/items.json') as file_object:
contents = file_object.read()
totalMoneyJson = json.loads(contents)
totalMoney=0
totalMoneyList=[]
for tmpMoneyInfo in totalMoneyJson:
tmpMoney= float(tmpMo... |
4002465d6ff995f7e78df3460f1ed40c8afe33ad | hoanganhk52/Session-4 | /session_8/game.py | 3,012 | 3.59375 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode([400,300])
done = False
game_finish = False
COLOR_BLUE = [0,255,255]
class Player():
def __init__(self,x,y):
self.x = x
self.y = y
def move(self,dx,dy):
self.x += dx
self.y += dy
def calc_next_position(self,dx,d... |
5ea301010a36b255e734373562cdd2954bca1e6f | Tougee/udacity | /cs212/poker/poker.py | 3,920 | 3.515625 | 4 | import itertools
def poker(hands):
return max(hands, key=hand_rank)
def hand_rank(hand):
ranks = card_rank(hand)
if straight(ranks) and flush(hand):
return (8, max(ranks))
elif kind(4, ranks):
return (7, kind(4, ranks), kind(1, ranks))
elif kind(3, ranks) and kind(2, ranks):
... |
089de9f9ed8ba0657a889cebfbd9298a01689ce9 | AllenZPGu/MUMS-PH-2019 | /checkEmails.py | 150 | 3.75 | 4 | with open('emails.csv', 'r') as f:
x = []
for i in f:
y = i.split(',')[1][:-1]
if y not in x:
x.append(y)
x.sort()
print(x)
print(len(x))
|
1a5391c61faf4ae21a5e340a7acba6a2a0c0dac0 | onepcc/zoo-python | /animal.py | 1,477 | 4 | 4 | # Cada animal debe tener al menos un nombre, una edad, un nivel de salud y un nivel de felicidad.
# La clase Animal debe tener un método display_info que muestre el nombre, la salud y la felicidad del animal.
# También debe tener un método de alimentación que aumente la salud y la felicidad en 10.
class Animal:
... |
655a5ef00a324d30707e5ee318f30e0e32324d9b | sasingithub/storage | /ceph_radosgw/get_count_objects_s3.py | 955 | 3.625 | 4 | ###Funcao para fazer count de numero de objetos dentro de um bucket
###Count number of object using paginate 1000 objects
def get_count_objects(bucket_name, bucket_conn, CEPH_BUCKET_MAX_KEYS):
bucket = bucket_conn.lookup(bucket_name)
objects = bucket.get_all_keys(max_keys=CEPH_BUCKET_MAX_KEYS)
objec... |
0c0de06a03d52d8cf86523b07153d27032dd3cb0 | sedakurt/pythonProject | /venv/conditionals.py | 786 | 4.21875 | 4 | #comparison Operastors
'''
print(1 < 1)
print(1 <= 1)
print(1 > 1)
print(1 >= 1)
print(1 == 1)
print(1 != 1)
'''
##if, elif, else code block
#if
name = input("What is your name? ")
if name == "Seda":
print("Hello, nice to see you {}".format(name))
elif name == "Bayraktar":
print("Hello, you are a surname!")
e... |
927faddf89f6af3e0987bb549e6e964b30ecead9 | pvcraven/isometric_test | /Source/isometric_example.py | 6,311 | 3.984375 | 4 | """
Example code showing Isometric Grid coordinates
"""
import arcade
import os
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
MAP_WIDTH = 5
MAP_HEIGHT = 4
TILE_WIDTH = 128
TILE_HEIGHT = 128
def get_screen_coordinates(tile_x, tile_y, width, height, tilewidth, tileheight):
screen_x = tilewidth * tile_x // 2 + height * ... |
4bb989ebaca1ed9e289611696a31e7db58cd04d1 | tretyakovr/sobes-Lesson03 | /Task-02.py | 1,549 | 4.125 | 4 | # Третьяков Роман Викторович
# Факультет Geek University Python-разработки
# Основы языка Python
# Урок 3
# Задание 2:
# Написать программу, которая запрашивает у пользователя ввод числа. На введенное число
# она отвечает сообщением, целое оно или дробное. Если дробное — необходимо далее выполнить
# сравнение чисел до ... |
f831b12f35358f0d7f8a9abc0db9f85b54097db2 | joanenricb/Data-Science---Washington-University | /MapReduce/asymmetric_friend.py | 636 | 3.5 | 4 | """
Generate a list of all non-symmetric friend relationships.
"""
import MapReduce
import sys
mr = MapReduce.MapReduce()
def mapper(record):
# key: document identifier
# value: document contents
name = record[0]
friend = record[1]
mr.emit_intermediate(tuple(sorted((name, friend))), 1)
def red... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.