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 |
|---|---|---|---|---|---|---|
511f49330d20309105a5f8863954bd14a37b3e51 | udhayprakash/PythonMaterial | /python3/07_Functions/012_function_with_variable_n_keyword_args.py | 757 | 3.96875 | 4 | #!/usr/bin/python3
"""
Purpose: Functions Demo
Function with variable keyword arguments
NOTE: PEP8 recommends not use more than 7 args for an function
"""
# Function Definition
def myfunc(**kwargs):
print(type(kwargs), kwargs)
myfunc()
myfunc(name="Udhay")
myfunc(name="udhay", age=55)
def hello(*given, ... |
5d63caa7bb42ce123cdc5e26b598d40d33820c40 | alinkolns/orders | /array.py | 764 | 3.515625 | 4 | import random
import numpy as np
random.seed(23)#Зерно
m, n = 5, 10
a = [[random.randint(100, 999) for j in range(m)] for i in range(n)]#генерация массива 5х10
a=np.array(a)
print("Исходный массив:\n\n", a)
numb = int(input("Введите целое число: "))
print("Простые:", end = " ")
for i in range(numb - 1, 1... |
7b7f73a0b9aae6e85b8cfbc4ebf117f1d420b997 | Aasthaengg/IBMdataset | /Python_codes/p03633/s182708114.py | 179 | 3.59375 | 4 | def gcd(a, b):
if (b == 0):
return a
return gcd(b, a % b)
arr = [int(input()) for i in range(int(input()))]
ans = 1
for i in arr:
ans = (ans*i)//gcd(ans, i)
print(ans) |
1cad03ba55df1f26a3cd6ee3b9bbfe4559499ed6 | joaramirezra/Can-You-Solve-a-Problem | /In-house/SendMail.py | 753 | 3.828125 | 4 | import smtplib as smtp
print("\n")
name = str(input("Please input your name: "))
sender = str(input("Please input your email address: "))
recipient = str(input("Please input the recipient's email address: "))
subject = str(input("Please input the email's subject: "))
message = str(input("Please input your message: ")... |
4cdfae7142640111d0a7fc4d08bf990fcf638e58 | se000ra/sqltest | /assignamet3a.py | 982 | 3.84375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2014 van <van@vanleno>
#
# Distributed under terms of the MIT license.
"""
"""
import sqlite3
import random
with sqlite3.connect('newnum.db') as connection:
c = connection.cursor()
c.execute("""
DROP TABLE if exists randomnum... |
285b7a9d4d34a5f79c274a26ec5c9adaec61359a | Buelabue/python | /multipleseven.py | 222 | 3.96875 | 4 | n=eval(input("enter the number"))
if(not isinstance(n,int)):
print("wrong input")
else:
if(n>7):
if(n%7==0):
print("n of multiple numbers of 7")
else:
print("Not Divisible")
|
aa739637525264ceca9982b1e3e78e5e9a69c984 | igorkoury/cev-phyton-exercicios-parte-1 | /Aula07 - Operadores aritiméticos/ex008 - Conversor de medidas.py | 238 | 4.0625 | 4 | # Crie um programa que leia um valor em metros e mostre convertido em centímetros e milímetros
m = float(input("Digite um valor em metros: "))
cm = m * 100
mm = m * 1000
print("O valor convertido é {}cm e {}mm" .format(cm, mm))
|
44acc59b0a41bdc8eb6e88bc1b6b5bc50c45157e | Jackmrzhou/codewars | /python/chain_add.py | 233 | 3.640625 | 4 | def add(num):
class add_object(int):
def __init__(self, num):
super().__init__()
def __call__(self,args):
self += args
return add_object(self)
return add_object(num)
result = add(6)
print(result+5)
print(result(1)) |
ecd4306ef729d3a1be7a56a4b76adce15596bd07 | romontei/Piscine-Python-Django | /d01/ex04/state.py | 776 | 3.5 | 4 | import sys
def capitalCities():
if len(sys.argv) != 2:
exit(1)
states = {
"Oregon" : "OR",
"Alabama" : "AL",
"New Jersey": "NJ",
"Colorado" : "CO"
}
capital_cities = {
"OR": "Salem",
"AL": "Montgomery",
... |
4537a08be33a29a8e535d44c76d6aa92b9a4ecad | dingqqq/LeetCode | /intersectionOfTwoArraysII.py | 858 | 3.5 | 4 | class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
"""
result = []
for num1 in nums1:
if num1 in nums2:
result.append(num1)
num... |
95d2a1cc287a896063cfd7275c137d090106dea9 | WaqasAkbarEngr/Python-Tutorials | /Strings.py | 2,542 | 4.84375 | 5 | # While writing a string a single quotation marks or double quotation marks are used
# For example
print ( "This is a string which is written between double quotation marks" )
# Or
print ( 'This string is written between single quotation marks' )
# In order to find the length of a string in python "len()" is u... |
dc1906751d652c64d29120c22e205a336b745e36 | DebjitDasgupta068/The-Caesar-Cipher-in-Python | /Problem1.py | 5,283 | 4.4375 | 4 | #Problem 1 - Build the Shift Dictionary and Apply Shift
# The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or
# to decrypt a message (since for Caesar codes this is the same action).
# In the next two questions, you will fill in the methods of the Message class f... |
421b38ecf51ba9168ca2e845a9421782b5d5051e | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_11/pattern6.py | 129 | 3.59375 | 4 | def pattern5(n):
for i in range(n):
for j in range(i+1):
print(i+1,end=" ")
print()
#pattern5(8)
|
cddb3c8a35e5d1e1afb1619f329f52a85babc9f9 | kevinjycui/ICS4U1 | /Stacks and Queues Exercises/War Game.py | 5,224 | 3.671875 | 4 | # Name: Kevin Cui
# Date: 2020-02-28
# Description: War Game
from Structures import Queue # Import queue data structure for decks and hands
import random
class Player(object): # Define player class
def __init__(self, name): # Initialize
self.name = name
self.hand = Queue()
self.totalPoint... |
dacc3a8cfe6b1d437e0a2095e6159b15a2f5f4eb | choigww/choigww-blockchain | /python/blockchain.py | 10,661 | 3.859375 | 4 |
############### Step 1. Building a Blockchain ###############
# Create a Blockchain class whose constructor creates an initial empty list
# and another list to store transactions
# Blueprint for our class below.
# What does a Block look like?
# index + timestamp(Unix time) + list of transactions + proof + hash of th... |
0b87952f8677b7659555d6cf3f8fcbec4db6d538 | cdemeke/Learn-Python-The-Hard-Way | /ex33/ex33_extra_practice.py | 1,812 | 4.28125 | 4 | #Study Drills
#1 (complete). Convert this while-loop to a function that you can call, and replace 6 in the test (i < 6) with a variable.
#
#2 (complete). Use this function to rewrite the script to try different numbers.
#
#3 (complete). Add another variable to the function arguments that you can pass in that lets you c... |
54f641d2648cff6d6a3d0a67b66761e040c73476 | ndnmonkey/Algorithm | /排序/heap-sort2.py | 1,367 | 4.03125 | 4 | #调整树的三个节点,调整调整后的下层节点。
def adjuste_tree(heap,root):
HeapSize = len(heap)
#有右子节点 且 (左节点 > 根 or 右节点 > 根)
if 2*root+2 <= len(heap)-1 and (heap[2*root+2] > heap[root] or heap[2*root+1] > heap[root]):
if heap[2*root+1] > heap[2*root+2]:
heap[2 * root + 1], heap[root] = heap[root], heap[2 * ... |
7c53c39782f6a6c8129b7b77e4bedbd9497f1fb9 | htmlprogrammist/kege-2021 | /Homework/polyakov-16/task_14.py | 387 | 3.875 | 4 | """
(№ 2217) Значение арифметического выражения: 9^8 + 3^24 – 18
записали в системе счисления с основанием 3. Сколько цифр «2» содержится в этой записи?
13
"""
x = 9 ** 8 + 3 ** 24 - 18
counter = 0
while x > 0:
if x % 3 == 2:
counter += 1
x //= 3
print(counter)
|
a8436f6d2cd738d12fd8bb4e960c848d125d21d8 | FrancoCastro89/parcial_tecnicas_programacion | /punto1.py | 852 | 3.703125 | 4 | def devuelveUnaLisDeTodasLasRotacionesPosibles(palabra):
"""
:param palabra: recibe un str
:return: regresa una lista de todas las posibles rotaciones de ese str
"""
lista = []
palabravacia = palabra.split(" ")
for recorePalabra in range(len(palabravacia)):
if palabravacia[recor... |
384240ec949b2b5628831b8934320c050d56abf4 | flxshujie/pythonpractice | /crossin/lesson_9.py | 433 | 3.96875 | 4 | from random import randint
num = randint(0,100)
bingo =False
print('what number do I think')
while bingo == False:
answer = input()
if answer < num :
print ('%d is too small' %answer)
elif answer >num :
print ('%d is too big' %answer)
else:
bingo =True
print ('bingo,%d ... |
c31e830f7f170515a0c70cf5f3fd4405a1a04cf8 | sdanil-ops/stepik-beegeek-python | /week4/task8.py | 1,419 | 4.15625 | 4 | # -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# Write a program that, according to the entered age of the user,
# tells which age group he belongs to
# -----------------------------------------------------------
class User:
def __init__(self, age: i... |
fa559fff39e2ca5f1cb425fba70aab994aa44935 | Adeodato-Alpha/Adeodas | /calc-e.py | 1,375 | 3.65625 | 4 | """
Program By Jesús Adeódato López Carranza
All rights reserve to its creator at https://github.com/Adeodato-Alpha/Adeodas.git
"""
from math import *
import math as mt
from decimal import Decimal, getcontext
getcontext().prec= 10000
"""
El getcontext nos ayudará a que nos arroje el numero de
decimales que s... |
b35045cdd060bd3da361726c8786608c017c9e3a | KGHustad/SudokuFormatter | /sudoku_formatter.py | 2,265 | 3.75 | 4 | instructions = """INSTRUCTIONS:
Copy a sudoku puzzle from http://www.menneske.no/sudoku/ to a text file,
and provide this file as the first command line argument and the file for
output as the second command line argument
Remember that box height and width must be added manually (before/after
formatting)"""
import... |
e80f5284d431ba1593c7679322265bcc797b7951 | eKids-Garage/boost_your_python_chatbot | /mod02-joker/initial_code.py | 574 | 3.90625 | 4 | #func What we should get after the Module 1
chatbot_name = "Garik"
user_name = input("Hello! What's you name? ")
#1
phrase = input(chatbot_name + ": What do you think? ")
print("Yes, " + user_name + ", " + phrase)
#2
phrase = input(chatbot_name + ": What do you think? ")
print("Yes, " + user_name + ", " +... |
2f79ec157b5e541b8a21f7a40393c9bed583847e | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d23.py | 190 | 3.578125 | 4 | a1=(input('Digite um número inteiro de 0 a 9999'))
print(f"""Você digitou o número {a1}, portanto, suas propriedades:
Unidade: {a1[3]}
Dezena: {a1[2]}
Centena: {a1[1]}
Milhar: {a1[0]}""") |
deccc57a497b4871b5fdda6b8e3dfc4fd2f607dc | NiharikaSinghRazdan/PracticeGit_Python | /Function_Practice/1_test.py | 383 | 4.34375 | 4 | #Write a function that returns the lesser of two given numbers if both numbers are even, but returns the
#greater if one or both numbers are odd
def check_num(a,b):
if (a%2==0 and b%2==0):
if a<b:
print (a)
else:
print (b)
else:
if a>b:
print (a)
... |
38dde8b721681bc273083f7bd983f43964b052a6 | yaobinwen/robin_on_rails | /Python/cookbook.py | 395 | 3.890625 | 4 | #!/usr/bin/env python
'''The cookbook contains various useful code snippets.
'''
def dict_comprehension():
'''PEP 274 - Dict Comprehensions: https://www.python.org/dev/peps/pep-0274/
The example comes from [here](https://stackoverflow.com/a/14507637/630364).
'''
print {n: n**2 for n in range(5)}
de... |
e6096d90ffbbd39482c376d02d05c01cd7dc294d | Sasha1152/Training | /decorators/function_tracker.py | 693 | 3.53125 | 4 | # https://hackernoon.com/the-goodies-of-python-decorators-66r3tsy
class FunctionTracker:
def __init__(self, func):
self.func = func
self.stats = []
def __call__(self, *args, **kwargs):
try:
result = self.func(*args, **kwargs)
except Exception as e:
self.... |
c0dd1cb37493839759ca95ac70ef39c106f10cee | AlecGoldstein123/April-Create-Task | /CountHeadsCoins.py | 1,645 | 3.796875 | 4 | # Count the number of Heads
import random
# Traching the number of simulators
'''
simNum=0
flip = random.randint(0,1)
countHeads=0
while simNum<10:
if flip==1:
print("Head - ", end="")
countHeads= countHeads+flip
print(countHeads)
print(flip)
flip=random.randint(0,1)
simNum= s... |
50653dd4d29f94e216be664dd13f874907301587 | Aasthaengg/IBMdataset | /Python_codes/p03424/s103208291.py | 165 | 3.6875 | 4 | n=int(input())
lst = []
s = input().split(" ")
for i in range(n):
if s[i] not in lst:
lst.append(s[i])
if len(lst) == 3:
print("Three")
else:
print("Four") |
5350df05b41192a872d778ec26db3e5ece0472c9 | ErNaman/python-practice | /fun.py | 139 | 3.84375 | 4 | def add(a,b):
z=x+y
print("sum of x any is:- ",z)
x=int(input("enter value of x"))
y=int(input("enter value of y"))
add(x,y)
|
3ba3627fa3c8700e9c42fce170b04303d6015e41 | NeelayRanjan/learning-PY | /Functions.py | 451 | 3.59375 | 4 | #Function
def Exponent(x,y):
print(x**y)
#Return
def name(x,y):
print(x+y)
return(x+y)
name1=name("Neelay ", "Ranjan")
#Defualt Values
def pet(name, type = "dog"):
print("Animal Type:",type)
print("Animal Name:",name)
#Arbitrary Number of Arguments
def pizza(*toppings):
print(toppi... |
26f0181ddd24c329b10387914092156d0f5a234e | luischaparroc/holbertonschool-machine_learning | /math/0x03-probability/exponential.py | 1,304 | 4.125 | 4 | #!/usr/bin/env python3
"""Module with Exponential class"""
class Exponential:
"""Class that represents an exponential distribution"""
EULER_NUMBER = 2.7182818285
def __init__(self, data=None, lambtha=1.):
"""Class constructor"""
if data is not None:
if not isinstance(data, li... |
4e98a5cd1aa66b1607177f6c72f892755f645527 | yosoydead/data-structures | /queue/Q.py | 1,278 | 3.671875 | 4 | from node import Node
class myQueue:
def __init__(self):
self.first = None
self.last = None
self.count = 0
def enqueue(self, data):
new = Node(data)
if self.count == 0:
self.first = new
self.last = self.first
self.count += 1
e... |
465265cb179524f0e5ced7c2c1a943b7f63dd937 | ToraNova/library | /guides/python/pysample/trycatch.py | 373 | 3.546875 | 4 | #!/usr/bin/python3
import time
def dangerous(a,b):
if(b==0):
#do something
raise ZeroDivisionError('b must not be zero')
out = a/b
return out
if __name__ == "__main__":
for i in range(5):
try:
time.sleep(0.5)
print(dangerous(i,0))
print('hi')
except ZeroDivisionError:
print("You are stupid")... |
60193bb0e6aa7dc1e615627fad42ceeb502fe303 | YsisEstrella/algoritmo_2020 | /Ejercicio #3, parte 3.py | 278 | 4.21875 | 4 | numero = -1
potencia = -1
while(numero <=0 or potencia <=0):
numero = int(input("Digite un numero entero positivo:"))
potencia = int(input("Digite una potencia entera positiva:"))
if(numero <= 0 or potencia <=0):
print("Error. Solo positivos.")
|
5e4ca3203ffa1b4742e5206b71c68ab4142eb74b | michalkasiarz/learn-python-programming-masterclass | /program-flow-control-in-python/ForLoopsExtractingValuesFromInput.py | 432 | 4.28125 | 4 | # For loops extracting values from user input
# prints entered number without any separators
number = input('Please enter a series of numbers, using any separators you like: ')
separators = ''
numberWithNoSeparators = ''
for char in number:
if not char.isnumeric():
separators = separators + char
else:... |
6ab1b67bd74db23d250f0e74ff81812b11905455 | SunnyMosquito/test | /interview/due/singleton.py | 2,209 | 3.703125 | 4 | # class Singleton(object):
# def test(self):
# print(self.__class__,'test')
# singletion = Singleton()
# datas = ['abcd'] * 1000000
# print(['abc']*2)
# string = ''
# import time
# start = time.time()
# string = ''.join(datas)
# end = time.time()
# print(end - start)
# start = time.time()
# for data in... |
5769e307593239212796ed4d042dbc9d393a434e | dlwaysi/ProjectEuler | /Multiples_3_5/Mult_3_5_mod_long.py | 1,461 | 4.09375 | 4 | #Project Euler
#Problem # 1
#Task: Calculate the sum of all of the multiples of 3 and 5 below 1000
#Author: Daniel Lwaysi
#Note: This is my first solution
#Date: 9/6/2017
#Program Header
print 'This program will sum all multiples of 3 and 5,up to but not including, a number you specify'
#USER PROMPT INPUT
x =... |
dd3e2fb6ea6ee78ff77fed38ffb50aeda334c26f | zaighumg20/CSCE-204 | /Exercises/March23/file_reading_exceptions.py | 493 | 3.96875 | 4 | def getMovies():
movies = []
#get the movie from the file
try:
with open("movies.txt") as file:
for line in file:
movie = line.replace("\n", "")
movies.append(movie)
return movies
except FileNotFoundError:
print("The movie file ... |
2665a1e6be71fbeed54a026aaf64b153845ec335 | peterCcw/alien_invasion | /alien_bullet.py | 1,233 | 3.703125 | 4 | import random
import pygame
from pygame.sprite import Sprite
class AlienBullet(Sprite):
"""Manages bullets shot by the aliens"""
def __init__(self, ai_game):
"""Create the bullet obj in the random alien's location"""
super().__init__()
self.ai_game = ai_game
self.screen = ai_g... |
da49acb694e2dedfdce7df53b2cd45bce0c6e27d | Giorc93/Python-Int | /tuples.py | 209 | 3.640625 | 4 | tuple1 = (1, 2, 3)
print(tuple)
tuple2 = tuple((1, 2, 3, 4, 5))
print(tuple2)
locations = {
(33.097234, 98.9827394): 'Belin',
(33.097234, 98.9827394): 'Tokio',
(33.097234, 98.9827394): 'Paris'
}
|
3ad6799ad4bca57686cb87755efdce197f364726 | jiangnanhugo/clustering | /pramod_setlur_hclust.py | 9,890 | 3.71875 | 4 | '''
ALGORITHM
__________
There are various data structures in this algorithm:
DIMENSIONS - an integer indicating the number of dimensions present for each point in the eucledien space
POINTS_COUNT - an integer representing the number of points present in the input file
input_point_list = [[1.0,2.3,4,2,1.3],... |
74ef23204052f44026fc8222bbe714bb4c9721c0 | luos1993/python-100day | /day17/test_textwrap.py | 470 | 3.5 | 4 | #!-*-coding:utf-8 -*-
"""
问题:有一些长字符串,想以指定的列宽将它们重新格式化
解决:textwrap模块
"""
import os
import textwrap
s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."
s1 = textwrap.fill(s, 70)
s2 = textwrap.fill(s, 40, initial_i... |
966bd54045d149ac79b3bb024f630955dc64f4d2 | scperkins/46-python-exercises | /SimpleIO/guess_the_number.py | 1,287 | 4.3125 | 4 | #! /usr/bin/env python
# -*- coing: utf-8 -*-
"""
Write a program able to play the "Guess the number"-game, where the number to
be guessed is randomly chosen between 1 and 20. (Source:
http://inventwithpython.com) This is how it should work when run in a terminal:
>>> import guess_number
Hello! What is your na... |
0ed0cf6e79d9a00308e92501be168d96db9c8437 | YJL33/LeetCode | /current_session/python/68.py | 4,380 | 3.96875 | 4 | """
68. Text Justification
Given an array of words and a width maxWidth,
format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach;
that is, pack as many words as you can in each line.
Pad extra spaces ' ' when necessar... |
ed4fe85d1310410c437c6978e50a0f4adb9c3640 | HELLO-world8999/python | /minions efficient.py | 621 | 3.625 | 4 | def minion_game(string):
stuart=[]
kevin=[]
for i in range(len(string)):
if string[i] not in ("A","E","I","O","U"):
for j in range(i,len(string)):
s=string[i:j+1]
stuart.append(s)
else:
for x in range(i,len(string)):
... |
86132531ffb47ee9297b3b508757530759fb45ca | dariianastasia/Instructiuni-de-introducere-aplicatie-practica- | /exercitiul.1.py | 455 | 4.09375 | 4 | """De la tastatura se introduce numarul de rind al culorii curcubeului.De afisat denumirea culorii.Convenim ca culoarea rosie are numarulde rind 1"""
n=int(input("introdu numarul culorii"))
print("ati introdus culoarea cu numarul:",n)
if n==1:
print("rosu")
if n==2:
print("oranj")
if n==3:
print("ga... |
cd94fcc3abc64a793b75af7c281129195f848c8c | truongnguyenlinh/procedural_python | /A3/test_change_hp.py | 737 | 3.546875 | 4 | # Linh Truong
# A01081792
# 03/06/2019
from unittest import TestCase
from character import change_hp, pokemon
class TestChangeHp(TestCase):
def setUp(self):
"""Assert that global variable pokemon HP is setup for unit testing."""
pokemon["HP"] = 10
def test_change_hp_subtract(self):
... |
a9398bd73852a4b8ffdc1a9208e855053f4aadef | evaristrust/Courses-Learning | /SecondProgram/input and output/write_texts.py | 476 | 4.25 | 4 | # we are going to open a simple txt file
cities = ["Kigali", "Kampla", "Dar es Salaam", "Nairobi", "Buja"]
with open("cities.txt", 'w') as cities_file:
for city in cities:
print(city, file=cities_file)
# what if i want to append this by a times 2 table
with open("cities.txt", "a") as tables:
for i i... |
b4ab0c434434ba62b3334797b4f96d9e6c400591 | cpoIT/Graphs | /projects/graph/social/social_demo.py | 1,215 | 4.09375 | 4 | #!/usr/bin/python
"""
Demonstration of Graph functionality.
"""
from sys import argv
from social import User, SocialGraph
# {
# '0': {'1', '3'},
# '1': {'0'},
# '2': set(),
# '3': {'0'}
# }
# {
# '0': {'1', '3'},
# '1': {'0', '4'},
# '2': set(),
# '3': {'0', '5'}
# '4': {'0', '1... |
2c3b5b31fbc5def7dc723e253021634c59644732 | AdamHutchison/palindrome-checker | /palindrome.py | 468 | 3.90625 | 4 | from dequeue import Dequeue
class PalindromeChecker:
def __init__(self):
self.dq = Dequeue()
def check_if_palindrome(self, word):
self.dq.items = list(word)
is_palindrome = True
while self.dq.size() > 1:
first_letter = self.dq.remove_front()
last_letter ... |
980e4b004ea3da2befbc294ce65395aaba557940 | Grimnimbulus3/py4e | /Chapter_4/Assignment_4_7.py | 876 | 4 | 4 | #rewrites the Grading script to be a function
#score = input("Enter a score between 0.0 and 1.0:")
def computegrade(score):
try:
score_int = float(score)
#print("Enter score: "+score)
except:
#print("Enter score: "+score)
grade = ("Bad score")
return grade
quit()
... |
40af63054fe14e0b8b8320c82f7aed84426b8225 | JDChiang/sc-project | /stanCode_Projects 1/my_photoshop/shrink.py | 1,108 | 4.4375 | 4 | """
File: shrink.py
-------------------------------
Create a new "out" image half the width and height of the original.
Set pixels at x=0 1 2 3 in out , from x=0 2 4 6 in original,
and likewise in the y direction.
"""
from simpleimage import SimpleImage
def shrink(filename):
"""
:param filename:... |
eb2878868f3a2f28d96c75e6907c248444fb3cb5 | marchuknikolay/bytes_of_py | /byte028/dates.py | 1,575 | 3.546875 | 4 | """
Bite 28. Converting date strings to datetimes
In this Bite you are provided with a list of publish dates of all our PyBites blog posts. They are in this format:
Thu, 04 May 2017 20:46:00 +0200.
Write a function called convert_to_datetime that takes a date string and convert it to a datetime object. You can
leave ... |
f941c6a9d84b1ffa4e2ebdec747ad93fb0891fd0 | raveena17/workout_problems | /basic_python/ Definite_Iteration_for_loops.py | 708 | 4.0625 | 4 | def IterationForLoop():
artists = []
for i in [0, 1, 2]: # using range[1,10] or ["i","lke","mom"] or [42,42,42]
next_artist = raw_input('Enter an artist that you like:')
artists.append(next_artist)
print ("Thank you! We'll work on your recommendations now.")
... |
63e5b343f49cbe174dfc3f9e1d35722aeb7739c8 | yeasellllllllll/bioinfo-lecture-2021-07 | /0708_theragenbio/bioinformatics_4_4.py | 1,791 | 3.734375 | 4 | #! /usr/bin/env python
# Op1) Read a FASTA format DNA sequence file
# and make a reverse sequence file.
# Op2) Read a FASTA format DNA sequence file
# and make a reverse complement sequence file.
# Op3) Convert GenBank format file to FASTA format file.
a = "sequence.nucleotide.fasta"
# Op1) Read a FASTA form... |
af825b01bec28087fd3e1c5879b605c054371062 | Fernito69/pythongames | /blackjack2.py | 22,573 | 3.90625 | 4 | #!/usr/bin/env python
# coding: utf-8
# IMPORTS
import random
import os
import math
import time
#clears the screen
os.system("cls")
#defines the amount of players
global amount_players
print("Welcome to Fernito's Blackjack\n")
#before anything, we ask how many players will be playing
#check for... |
e094cb2a9547c00dffcc6a1cbda8002b804af066 | liugenghao/pythonstudy | /Array&Str/forloop.py | 111 | 3.890625 | 4 |
num = [1,2,3,4,5,6,7,8,9]
for i in range(0,9,3):
print(num[i])
a = [1,2,3]
for i in a:
print(a[i-1]) |
8516924f2eebf1b555ab42e68873f64d9130f7a6 | bolmstedt/advent-of-code-python | /app/y2020/d02_password_philosophy.py | 1,570 | 3.78125 | 4 | """Solution for day 2, 2020."""
from typing import Callable, Union
from app.base_solver import BaseSolver
class Solver(BaseSolver):
"""Solver for day 2, 2020."""
day = '02'
year = '2020'
name = r"""Password Philosophy"""
def part_one(self, data: str) -> Union[int, str]:
"""Solve part on... |
c57dc40df70eada89f74827f6ec191b79156182b | angelvv/HackerRankSolution | /Algorithms/Implementation/12.AppleAndOrange.py | 1,279 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
print(sum(s <= (a + x) <= t for x in apples))
print(sum(s <= (b + x) <= t for x in oranges))
""" For unknown reason, this on... |
862da4efd7b2b08a0287f8e71785b29118c97016 | robertkohl125/Movies_Website | /media.py | 1,038 | 3.625 | 4 | import webbrowser
class Video():
"""This Parent class constructs a list of media variables for the
child classes Video and TvShow for our web site."""
# This is the Parent class for the media classes (Movie and TvShow).
def __init__(self, title, storyline, poster_image_url,
trailer_y... |
13d946f9af667dc136357046e6ca796d4e432e05 | Baig-Amin/python-practice-2 | /Division.py | 346 | 4.1875 | 4 | #The provided code stub reads two integers, a and b, from STDIN.
#Add logic to print two lines.
#The first line should contain the result of integer division,
# a//b .The second line should contain the result of float division, a / b.
#No rounding or formatting is necessary.
a = int(input())
b = int(input())
z = a / ... |
c1f4fbfff2bfa955daabd77b05ab7441f3c4a798 | LEMSantos/udemy-data_visualization | /lessons/compare_bar_charts.py | 335 | 3.515625 | 4 | import matplotlib.pyplot as plt
x1 = [1, 3, 5, 7, 9]
y1 = [2, 3, 7, 1, 0]
x2 = [2, 4, 6, 8, 10]
y2 = [5, 1, 3, 7, 4]
title = 'Gráfico de barras 2'
x_axis = 'Eixo X'
y_axis = 'Eixo Y'
plt.title(title)
plt.xlabel(x_axis)
plt.ylabel(y_axis)
plt.bar(x1, y1, label='Grupo 1')
plt.bar(x2, y2, label='Grupo 2')
plt.legend(... |
915abe12322a35caedb31fe0fb50ac9af000c62a | DominikaJastrzebska/Kurs_Python | /03_kolekcje/zad_3_set.py | 874 | 4.3125 | 4 | '''
3▹ Utwórz 2 krotki. Następnie utwórz listę będącą połączeniem elementów o parzystym indeksie z
pierwszej krotki, a oraz nieparzystych elementów z drugiej.
'''
tuple_1 = tuple('ala''ma''kota''356')
tuple_2 = tuple('tra''ta''ta''23''35')
print(tuple_1)
print(tuple_2)
tuple_1_to_list = list(tuple_1)
tuple_2_to_list ... |
3193cfc3d8efafcbdfd5e0fc1efc1dd99de6c91a | Nihal-prog/Calendar-in-python | /main.py | 584 | 4.1875 | 4 | # Calender Program
# Importing modules
import calendar
import datetime
# Introduction To The Program
print("\n\t\t\t$$$$$$$$$$$$$$$ Calendar Printing Program $$$$$$$$$$$$$$$\n")
date = datetime.datetime.now()
x = date.strftime("%d-%m-%y")
print(f"Date of Execution: {x}\n")
# Taking User Inputs
year = int(input("Ente... |
1a6b008b05b876ecd1694f95d7e8d36cfb8cf794 | valeriischipanovskyi/Python-Project | /lists.py | 308 | 4.1875 | 4 | def even_only(numbers):
for num in numbers:
if num% 2 == 0:
yield num
def sum_even_only_v2(numbers):
"""Суммирует все четные числа"""
result = 0
for num in even_only(numbers):
result += num
return result
print(sum_even_only_v2([5,7,8,9,10,2,2])) |
bfdb8fd0fe777a267f09bc2a7f2268d42a3905b6 | Aasthaengg/IBMdataset | /Python_codes/p03424/s304152425.py | 99 | 3.765625 | 4 | n=int(input())
s=input().split()
x=set(s)
if len(x)==3:
print('Three')
else:
print('Four') |
604354119108a25be61ad9dbf09d4098450aac5f | GianlucaTravasci/Coding-Challenges | /Advent of Code/2020/Day 1/solution1.py | 862 | 4.1875 | 4 | from itertools import combinations
# return the product of two that summed gives 2020
def problem1(values):
for a, b in combinations(values, 2):
if a + b == 2020:
print('matching numbers are: ', a, b)
return a * b
# return the product of 3 numbers that summed gives 2020
def pro... |
06fc0b15462064b4be1f418a6528db529878b137 | PrateekJain999/Python-Codes | /Class/single level inheritance.py | 318 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 23:52:49 2019
@author: prateek jain
"""
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak... |
e58339b6244e93a6dbf4553aaaa069b5ed143a4e | nildiert/holbertonschool-machine_learning | /math/0x03-probability/binomial.py | 2,325 | 4.25 | 4 | #!/usr/bin/env python3
""" This class represents an binomial distribution """
class Binomial():
""" This class represents a binomial distribution """
e = 2.7182818285
pi = 3.1415926536
def __init__(self, data=None, n=1, p=0.5):
" The initialized the class "
if data is None:
... |
4b3e633730e5e16fbce55770b03cadcc0f12cf85 | yzl232/code_training | /mianJing111111/new_leetcode_new/maximum path sum a b c d.py | 1,740 | 3.90625 | 4 | # encoding=utf-8
'''
给定一个binary tree, 每个节点有一个数字值, 对于 每个节点定义:
a = 从根到该节点的path sum
b = 以该节点左子节点为root的maximum path sum指
c = 以该节点右子节点为root的maximum path sum值
d= b + c - a
求最大的d
leetcode maximum path sum改变而来。
换了公式。 加了cur path ,
# F家
'''
# Definition for a binary tree node
# class TreeNode:
# def ... |
7794cfd92888e516be30525126abe470057f0b32 | kangmin1012/Algorithm | /2020.11.08(SUN)/1003_Fibonacci.py | 485 | 3.9375 | 4 | def addFibonacci(arr1,arr2) :
result = []
result.append(arr1[0]+arr2[0])
result.append(arr1[1]+arr2[1])
return result
if __name__ == '__main__':
fibo = [[1,0],[0,1],[1,1],[1,2]]
T = int(input())
for _ in range(T) :
fiboLen = len(fibo)-1
N = int(input())
if (N > fi... |
f696f66bd296671071139db8994a11591a4673b4 | juaniscarafia/AnalisisNumerico | /SistemaDeEcuaciones/Viejos/Sistemas_Ecuaciones123.py | 3,219 | 3.828125 | 4 | import numpy as np
from numpy.linalg import *
if __name__ == '__main__':
seguir= True
while seguir:
print """Seleccione Tipo de metodo:
1- Gauss Jordan
2- Gauss Seidel
3- Salir"""
try:
n = int(raw_input('Opcion: '))
... |
c5e5aebf4738252d700520bc92f6b9af01f9679b | corner1990/dream | /python/高级特性/切片.py | 235 | 4.1875 | 4 | # 切片
# 取一个list或tuple的部分元素是非常常见的操作
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
# 获取下标0开始,取两个值
print(L[0:2])
# 支持负数, 可以直传一个值,
print(L[-3:])
print(L[: -3])
|
7cc0099f02699785751c5168bf95322717cecf20 | mohaimin95/data-structures-and-alorithms-py | /recursion/factorial.py | 309 | 4.125 | 4 | def factorial_without_recursion(num):
result = 1
while(num != 1):
result *= num
num -= 1
return result
def factorial(num):
if num == 1:
return 1
return num * factorial(num-1)
input = 6
output = factorial(input)
print(output, factorial_without_recursion(input))
|
06bca54756ca2317826e62ea2e7b0a08b9969777 | Kushal997-das/Hackerrank | /Hackerrank_python/12.Python Functionals/79.Reduce Function.py | 406 | 3.859375 | 4 | from fractions import Fraction
from functools import reduce
def product(fracs):
t =reduce(lambda numerator,denominator:numerator*denominator,fracs)
# complete this line with a reduce statement
return t.numerator, t.denominator
if __name__ == '__main__':
fracs = []
for _ in range(int(input())):
... |
9a268a08c59b0f3505492156ce5c59ab675efe45 | nikhilsamninan/python-files | /day9/funprog.py | 172 | 3.65625 | 4 | def name(a):
if(len(a)%2==0):
return("even")
else:
return(a[0])
a=['nova','sreerag','orange','apple']
name(a)
print(list(map(name,a))) |
1f3249acee4f3021e491ad75ba0865c520c82539 | pyre/pyre | /packages/journal/Firewall.py | 1,399 | 3.625 | 4 | # -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2023 all rights reserved
# superclasses
from .Channel import Channel
# the implementation of the Firewall channel
class Firewall(Channel, active=True, fatal=True):
"""
Firewalls are used to communicate that a bug was ... |
c91cc4be8d64391da69e0eae73e28f5f7e60136c | schari2509/coderspack | /Python/task9.py | 253 | 4.1875 | 4 | #Odd Even
numbers = (45, 67, 22, 35, 80, 14, 26)
odd = 0
even = 0
for i in numbers:
if i % 2 == 0:
even = even + 1
else:
odd = odd + 1
print("No. of odd numbers : ", odd)
print("No. of even numbers : ", even)
|
78de01df5cc93ead33e01fd8ecb39aee51c050c3 | lemgrb/REFERENCE | /python/Examples/02_dictionary.py | 149 | 3.5625 | 4 | # Create a dictionary type
data = {'user':'lemuel','password':'P@ssw0rd'}
# Iterate through the dict
for k,v in data.items():
print(f'{k}={v}')
|
1225862fa09c70946a9d1e974226a80b4bd77af4 | HermanLin/CSUY1134 | /homework/hw04/hl3213_hw4_q8.py | 666 | 3.578125 | 4 | def flat_list(nested_lst, low, high):
flat = []
if low == high:
if isinstance(nested_lst[low], list):
flat.extend(flat_list(nested_lst[low], 0, len(nested_lst[low]) - 1))
else:
return [nested_lst[low]]
else:
#print("low: ", low)
#print("high: ", high)
... |
b9b1c766b20fae8b64adb98da3d6b139ecff7423 | matheus073/projetos-python | /CorridaDeBits/1041.py | 363 | 3.59375 | 4 | p=input()
q=p.split()
x,y=float(q[0]),float(q[1])
if x>0:
if y>0:
print("Q1")
elif y<0:
print("Q4")
else:
print("Eixo X")
elif x<0:
if y>0:
print("Q2")
elif y<0:
print("Q3")
else:
print("Eixo X")
elif x==0 and y!=0:
pr... |
09ea65c304d7d247882ed5d75934fcdb4b92b2a0 | fwfurtado/functional | /lambda_calculus/data_structure.py | 757 | 3.65625 | 4 | from lambda_calculus.arithmetic import four, three
from lambda_calculus.base import konstant
from lambda_calculus.logical import to_bool, true, false
from lambda_calculus.numbers import to_int, one, two
pair = lambda first: lambda second: lambda f: f(first)(second)
fst = lambda some_pair: some_pair(true)
snd = lambda... |
61c71771c36b9bf50b00d7a3956ddd74f77ab08c | Davidhfw/algorithms | /python/offer/05_replace_space.py | 405 | 3.953125 | 4 | """
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
解题思路:正则替换或者字符串分割,然后使用%20拼接起来
"""
class Solution:
def replaceSpace(self, s: str) -> str:
if not s or s == "":
return s
new_s = ''
for i in s:
if i == ' ':
i = '%20'
new_s += i
return new_s
|
9f6c89beb25fa25781ce32b947d5761dd24418a3 | jsolorzano/simple-tic-tac-toe | /tic_tac_toe.py | 4,808 | 4.34375 | 4 | # -*- coding: utf-8 -*-
'''
Un simple programa que simula jugar a tic-tac-toe (nombre en inglés)
con el usuario.
'''
def DisplayBoard(board):
#
# la función acepta un parámetro el cual contiene el estado actual del tablero
# y lo muestra en la consola
#
# ~ print(board)
print("+-------+-------... |
13186f55033dd1561d2239ac0429da43227d36d8 | NoahSaso/alfred-factorials | /factorial.py | 1,096 | 3.984375 | 4 | # Initial code to create list
print('<?xml version="1.0"?>')
print('<items>')
print('<item uid="factorial" valid="no">')
# Get arguments
num = int("{query}")
result = 1
if num < 0:
print('<title>Are you crazy? No negative numbers!</title>')
elif num == 0:
print('<title>0! = 1 (still debated but this works)</title>'... |
428f3743d26c530d6672c5d86189a1d284c91831 | MAD-FiS/resmon-autoclient | /src/request/ResponseError.py | 637 | 3.59375 | 4 | class ResponseError(RuntimeError):
"""
Represents HTTP error which occurs \
during doing requests to external servers
"""
def __init__(self, code, message):
"""
Initializes response error
:param code: HTTP error code
:param message: Message returned by external serve... |
f15d2ec316bad8539a837197ac293e95fe81bad3 | TheFuzzStone/hello_python_world | /chapter_7/7_3.py | 304 | 4.21875 | 4 | ### 7-3. Multiples of Ten: Ask the user for a number, and then
# report whether the number is a multiple of 10 or not.
n = input("Give me a number, please: ")
n = int(n)
if n % 10 == 0:
print(str(n) + " is a multiple of 10.")
else:
print("Sorry, but " + str(n) + " is not a multiple of 10.")
|
af10aa4993b833b6b982b9aab4dc0f395e306fee | bonicim/technical_interviews_exposed | /src/algorithms/blind_curated_75_leetcode_questions/valid_parenthesis.py | 808 | 4.125 | 4 | def valid_parenthesis(string):
stack = []
closing = {")": "(", "]": "["}
opening = set(["(", "["])
for char in string:
if char in opening:
stack.append(char)
elif char in closing:
if stack:
peek = stack[-1]
if peek == closing.get(c... |
33202e77164b82a34c8369148ba30f2ca8e5d93b | herereadthis/timballisto | /tutorials/abstract/abstract_06.py | 1,442 | 4.5625 | 5 | """Use abc as a skeleton for subclasses."""
"""https://www.smartfile.com/blog/abstract-classes-in-python/"""
from abc import ABC, abstractmethod
class AbstractOperation(ABC):
def __init__(self, operand_a, operand_b):
"""Initialize by storing 2 args."""
self.operand_a = operand_a
self.ope... |
241617bcdabe26b379f703f3f81ab4973675d392 | jae04099/PS-Study | /Algorithms/Binary-Ternary-Search/191-LENA-LEET.py | 1,608 | 3.6875 | 4 | # 생각한 풀이법
# 스트링으로 받고 리스트로 만듬
# 정렬 한다.
# 1이 시작되는 지점을 찾는다. 이전이 0이고 현재 1이면 됨.
# 1이 시작되는 지점부터 끝까지 1일테니 그 숫자를 리턴
# 0이라면 start를 다음부터 설정
# 1이라면(전이 0도 아니라면) end를 이전부터 설정
# def binsearch(n):
# str_n = str(n)
# sort_list = list(map(int, sorted(list(str_n))))
# start, end = 0, len(sort_list) - 1
# while start <=... |
be836d774ad2e3d2ee5f75917256091a8fdff080 | nikhgupt/Patterns | /PYRAMID/Pyramid 03/pyramid03.py | 91 | 3.78125 | 4 | # Pyramid 3
for i in range(1,6):
print((5-i)*' ',end='')
print((2*i-1)*str(2*i-1))
|
83efa0baf48c4d8fd10ccddc30c02e7662c9bba3 | RonanLeanardo11/Python-Lectures | /Lectures, Labs & Exams/Lecture Notes/Lect 5 - Classes and Definitions/Lab 5.3.py | 2,666 | 4 | 4 | # Lab 5.3 Ronan Breen X00152190
# Building upon Q1 and Q2. You can assume that the instance of the Student and the instance
# of the PrintCard are related. That is to say that the Print Card is the Students print card.
# Then (using both instances only): Calculate the average of the Students 2 CA grades. If the
# stud... |
b1c9e1f5cf35c27641499928ac8bc4bfd43c3b51 | bigeyesung/Leetcode | /234. Palindrome Linked List.py | 1,818 | 3.984375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
#iterate the list in order to get the middle node(1st,2nd) parts
#while the iteration, we can... |
f7d2bb0726a2517af85700875c3052f0a5da83e5 | saouinet/RoboticArm | /python/keyboardControl.py | 4,544 | 3.875 | 4 | #!/usr/bin/env python
# Robotic arm manipulation with the keyboard and the ncurses module.
# W. H. Bell
import curses
import usb.core, usb.util
#---------------------------------------------------
# A function to check if the bit corresponding to the search command
# is already set or not.
def commandSet(currentCmd, s... |
27f66a0bdfc95bca6f7ab4515b21469c3af42917 | qizongjun/Algorithms-1 | /Leetcode/Binary Search/#162-Find Peak Element/main.py | 1,555 | 3.90625 | 4 | # coding=utf-8
'''
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak
element and return its index.
The array may contain multiple peaks, in that case return the index
to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞.... |
d2bb3a0e3d85103ce00c9b31009da671e032b08f | Aasthaengg/IBMdataset | /Python_codes/p02388/s150650140.py | 131 | 3.5 | 4 | #coding: UTF-8
def X_Cubic(x):
return x*x*x
if __name__=="__main__":
x = input()
ans = X_Cubic(int(x))
print(ans) |
0a99bdb6128b2f165c5139d289dbf3e334b4952c | justin-p/my-notes-and-snippets | /courses/Python4N00bs/ExercicesCode/SharedExercises/03.py | 109 | 3.890625 | 4 | user_list = ['paul','marie','isabell','jochem']
user_list.reverse()
for user in user_list:
print(user) |
1fbd2fcd186d7b471c09f1db2c9586625be39dd1 | dandraden/Python-Projects | /AlgorithmDesign/DPFibonacci.py | 1,750 | 3.796875 | 4 | import time;
def fibnaive (n):
if n == 1 or n == 2: return 1;
else: return fibnaive(n-1) + fibnaive(n-2);
memo={};
def fibdptopdown (n):
if n in memo: return memo[n];
if n == 1 or n == 2: result = 1;
else: result = fibdptopdown(n-1) + fibdptopdown(n-2);
memo[n] = result;
return r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.