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 |
|---|---|---|---|---|---|---|
c4051d5b29c21c23b545cee418d14da0e11b29a0 | shaunakchitare/PythonLearnings | /function_programs.py | 2,152 | 4.40625 | 4 | #-------------------------------------------------------------------------------
#Exercise 1 - Creat a function that accepts 3 ardument and return their sum
print('\nExercise 1')
def add_numbers(x,y,z):
total = x + y + z
return total
total = add_numbers(5,1,9)
print(total)
#------------------------------------... |
ef9d3a2698eca0fdfa27eba669fff14558e1ebcf | shaunakchitare/PythonLearnings | /odd_even.py | 560 | 3.65625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Laxmikant
#
# Created: 16/05/2020
# Copyright: (c ) Laxmikant 2020
# Licence: <your licence>
#---------------------------------------------------------------------------... |
1cd0a2fc2283355d1398aafb3fea2e57a50b5312 | kovokilla/python | /namedTuple.py | 684 | 4.375 | 4 | # Import the 'namedtuple' function from the 'collections' module
from collections import namedtuple
# Set the tuple
#tuple je v podstate object
individual = namedtuple("Nazov_identifikacia", "name age height")
user = individual(name="Homer", age=37, height=178)
user2 = individual(name="Peter", age=33, height=175)
# Pri... |
2a7f7e78b63d04fca9cf5bb90ece4f7dd414157e | GoldenBlue/python | /spaceship.py | 17,244 | 3.875 | 4 | # program template for Spaceship
import simplegui
import math
import random
printonce = True
# globals for user interface
width = 800
height = 600
score = 0
lives = 3
time = 0
rock_spawn_time = 1
num_rocks = 1
acceleration = 1.2
debris = 0.8
min_acc = 0
max_acc = 8
acc_steps = 20
missile_vel... |
75f90baadc03152562d4ef37d19a8b050130664c | carlan/dailyprogrammer | /easy/2/python/app.py | 1,003 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""app.py: challenge #2"""
__author__ = "Carlan Calazans"
__copyright__ = "Copyright 2016, Carlan Calazans"
__credits__ = ["Carlan Calazans"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Carlan Calazans"
__email__ = "carlancalazans at gmail dot com"
__status... |
22756cf4528643cd5186f1d0567ef512729f9c88 | vsharmanyc/cse337 | /minor-hw2/hw2.py | 6,482 | 4.21875 | 4 | import re
def printMatches(regex, strings):
for str in strings:
if(re.search(regex, str)):
print(str)
"""1. (5 points) For each of the strings below, does the pattern [^O]*o+ match the string? If so,
list which part of the string will be matched. If not, then state "no match".
"""
strings = ["ball... |
16e5119005d3bce96b9bcc422fc35f020c9a5466 | buecktobias/TravellingSalesManProblem | /Leaf.py | 576 | 3.609375 | 4 | class Leaf:
def __init__(self, node):
self.__parent = None
self.__node = node
self.__leafs = []
def set_parent(self, leaf):
self.__parent = leaf
def get_node(self):
return self.__node
def delete_node(self):
self.__node = None
def get_parent(self):
... |
661bdeb3aa680a56a22f23bb4ac22d872bf1bbb0 | caesaralpha/tunaiku | /Tunaiku/load_csv.py | 836 | 3.625 | 4 | data_path = './dummy.csv'
class my_dictionary(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
def read_csv(data_path):
print("Data is loading..")
d=open(data_path,encoding="utf8").readline()
count_col=len(d.split(','))
re... |
bb2b5bd0d178b48b0de6261c129a0d6c35fe3fbb | codenameyau/calculation | /main.py | 717 | 3.9375 | 4 | """
calc.py
MIT License (c) 2014
codenameyau.github.io
Description:
Searches for ways to calculate a number from a given set of
numbers with the following operations: '+', '-', '*'.
Examples:
- List all ways to calculate the number 42 from the given set
python calc.py 3 9 8 4 5 -n 42
"""
from calc import calc
import ... |
11419f92040ef5f2f94cf038d49374c165092d23 | thefiltitoff/python_tasks | /pr2/task_1.py | 953 | 3.546875 | 4 | def f21(x):
tree_dictioinary = {
"terra": 10,
"lua": {
"kit": {
1978: 3,
1976: {
2011: 4,
2015: 5,
1958: 6
},
2015: {
2011: 7,
... |
8433b4e7cd6dd75a94344d8a5eb9d75f37a41ca3 | udoy382/PyCode15h | /chapter_005.py | 1,657 | 4.25 | 4 | # Chapter -5 Dictionary & Sets
# mydict = {
# "Fast": "In a quick manner",
# "Udoy": "Coder",
# "Marks":[1,2,3,4],
# "anatherdict": {'Udoy':'Player'}
# }
# print(mydict['Fast'])
# print(mydict['Udoy'])
# mydict['Marks'] = [22, 99, 436]
# print(mydict['Marks'])
# print(mydict['anatherdict']['Udoy'])
#... |
82e88f17c1afda546f60da5ab7801644ee7447fd | udoy382/PyCode15h | /project_2.py | 720 | 3.921875 | 4 | import random
randNumber = random.randint(1, 100)
print(randNumber)
userGuess = None
guesses = 0
while(userGuess != randNumber):
userGuess = int(input("Enter you guess: "))
guesses +=1
if (userGuess==randNumber):
print("You guessed it right!")
else:
if (userGuess>randNumber):
... |
9a2e62e99675489b4ea9da45cf42e633fc821813 | udoy382/PyCode15h | /chapter_011.py | 4,668 | 4.34375 | 4 | # Chapter -11 Inheritance
# ------------------------------------
# Single inheritance
# ------------------------------------
'''
class Employee:
company = "Google"
def showDetails(self):
print("This is an employee")
class Programmer(Employee):
language = "Python"
# company = "YouTube"
... |
310f9ad55b402e247ddacf31b5ae221624c65265 | katepisova/Snake-1 | /Snake.py | 2,829 | 3.671875 | 4 | from tkinter import *
import random
# Globals
# ширина экрана
WIDTH = 800
# высота экрана
HEIGHT = 600
# Размер сегмента змейки
SEG_SIZE = 20
# Переменная отвечающая за состояние игры
IN_GAME = True
#Сегмент змейки будет простым прямоугольником
#созданным при помощи метода create_rectangle
# класса Canvas модуля tk... |
0fc20b50aec0ad2f1baffca4777c506e1e83eb3a | camiF/real-estate | /progam.py | 2,716 | 3.5 | 4 | import csv
import os
import statistics
from data_types import Purchase
def main():
print_header()
filename = get_data_from_file()
data = load_file(filename)
query_data(data)
def print_header():
print("Real state app")
def get_data_from_file():
base_folder = os.path.dirn... |
51ee03a621f86ceffa9bd3abd790f746816e3f90 | will-hossack/JuniorHonsLab | /Stats/lindata.py | 551 | 3.578125 | 4 | """
Simple program to make linear data
"""
import numpy as np
import csvfile as f
import tio as t
def linear(x,a,b):
return a*x + b
def main():
xstart = t.getFloat("x start",1.0)
xend = t.getFloat("x end",10.0)
n = t.getInt("number",100)
a = t.getFloat("gradient",0.5)
b = t.getFloat("interce... |
f7da624f4a0f6a62cc5b4e700cd9d21ef5305429 | capeta0507/python_practice | /set-dictionary.py | 1,263 | 3.859375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
# 集合的運算
# s1={3,4,5}
# 判斷該數字是否在集合裡
# print(10 not in s1)
# s1={3,4,5}
# s2={4,5,6,7}
# s3=s1&s2 # 交集:取兩個集合中,相同的資料
# s3=s1|s2 # 聯集:取兩個集合中的所有資料,但不重複取
# s3=s1-s2 # 差集:從 s1 中,減去和 s2 重疊的部分
# s3=s1^s2 # 反交集:取兩個集合中,不重疊的部分
# print(s3)
# s=set("Hello") # 把字串中的字母拆解成集合:set(字串... |
b64c0f93bc2d67ec0c0551d6ee320e7f1a2b6813 | kevinfAAA/kev-PP3-Draft | /run.py | 1,191 | 3.53125 | 4 | import requests
from bs4 import BeautifulSoup
URL = "https://realpython.github.io/fake-jobs/"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
# Find Elements by ID
results = soup.find(id="ResultsContainer")
# Find Elements by HTML Class Name
print(results.prettify())
job_elements = resu... |
8f0a82f8fa05091a0915f606e13a4b2cccfebdfe | hrrrpb/data | /codes/python/crypto/RSAattack.py | 2,813 | 4.0625 | 4 | #!/usr/bin/python3
import math
import time
#the function will find the divisors, assume n is the product of two prime numbers
# the function itself does not validate n is the product of 2 prime numbers
def findPrimerDivisors(n) :
#get the largest int of squre root of n
sqrt = math.floor(math.sqrt(n))
if n % 2 ... |
e18c834aacdddff864d1d716dff2b29a097dc022 | hrrrpb/data | /codes/python/changeaccount.py | 625 | 3.90625 | 4 | #!/usr/local/bin/python3
filename = input("What is the password file name? ")
oldaccount = input("What is the old account name? ")
newaccount = input("What is the new account name? ")
textfile = open(filename, "r")
text = textfile.readlines()
textfile.close()
textfile = open(filename, "w")
for line in text :
acc... |
75124364a0c4cc7c626af69988aab871f6305e44 | hrrrpb/data | /codes/python/querydb.py | 492 | 3.859375 | 4 | #!/usr/local/bin/python3
import sqlite3
import sys
filename = sys.argv[1]
querycity = sys.argv[2]
dbconn = sqlite3.connect(filename)
dbcurs = dbconn.cursor()
#people = dbcurs.execute("SELECT * FROM peopletable")
people = dbcurs.execute("SELECT * FROM peopletable WHERE city == ? ORDER BY lastname, firstname", (quer... |
34617358e817cde58ff757583341fcb1e45e4989 | KevinVega-afk/Matracas13 | /Edades iguales.py | 147 | 3.953125 | 4 | Primero = int(input("Ingrese su edad: "))
Segundo = int(input("Ingrese la edad del otro usuario: "))
print(True if Primero == Segundo else False) |
c35518bef965634947b91fa3e9018e3de8749d3b | LeskoIam/monolit_izobrazevanje | /csv_json_pil/my_csv.py | 1,080 | 3.5 | 4 | # Documentation is like sex.
# When it's good, it's very good.
# When it's bad, it's better than nothing.
# When it lies to you, it may be a while before you realize something's wrong.
import csv
class MyCsvWriter:
def __init__(self, f_path, header, delimiter=","):
self.f = f_path
self.header = h... |
a3a51f7b27acb964ca23b38aa1698ca39b810366 | datho7561/Fourseal | /sprite.py | 2,341 | 3.921875 | 4 | # Author: David Thompson
# Date: 5 April, 2018
import random
import operator
from pygame import Surface
from constants import *
def sortSprites(sprites):
""" Sorts a list of sprites so that they can be drawn from the back to the front. """
sprites.sort(key = operator.attrgetter('y'), reverse = True)
class ... |
11cd97437da8390473e8e4799f146cf25ef01d6a | RaymondKerley/OOP | /FizzBuzz.py | 271 | 3.578125 | 4 | count = 1
while count <= 30:
if count % 15 == 0:
print(str(count) + " FizzBuzz")
elif (count) % 5 == 0:
print(str(count) + " Buzz")
elif count % 3 == 0:
print(str(count) + " Fizz")
else:
print(count)
count += 1 |
e017a997eb8186d3936510a19aee3c68af977e6d | azavalaana/unics | /Lab 6/topological_sort.py | 733 | 3.53125 | 4 | from Queue import Queue
from graph_al import GraphAL
# Sorts vertices following the topological sort algorithm
def topological_sort(graph):
all_in_degrees = graph.indegree_all_vertex()
sort_result = []
q = Queue()
for i in range(len(all_in_degrees)):
if all_in_degrees[i] == 0:
... |
9448424cac6e7ec1d4f2486209ac44432f6a4b3a | azavalaana/unics | /Lab_3_Complete/AVLNode.py | 1,844 | 3.671875 | 4 | # AVLNode class
class Node:
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
self.height = 0
# Assign either the left or right node with a new child
def set_child(self, child_dir, child):
if child_di... |
a25453e9053a159263590ba9b2f1ae9c314815fe | Vitold55/PythonLessons | /lesson12.py | 96 | 3.703125 | 4 | x = int(input('How old are you?'))
if x >= 18:
print('Welcome')
else:
print('Forbidden') |
af266765b235d538f5a8c88326b67d2b5ed4fc67 | Vitold55/PythonLessons | /lesson36.py | 288 | 3.671875 | 4 | class A:
def __init__(self, name):
# Class constructor
self.name = name
def get_info(self):
print("Hello, " + self.name)
def __del__(self):
# Class destructor
del self.name
a1 = A('Vilan')
a1.get_info()
a2 = A('Roman')
a2.get_info() |
4103d59221a5fd24212c24720f029675ba45f3bf | Vitold55/PythonLessons | /lesson31.py | 194 | 3.5 | 4 | from datetime import date, datetime
import locale
locale.setlocale(locale.LC_ALL, 'uk_UA.UTF-8')
today = date.today()
now = datetime.now()
print(today.strftime('%x'))
print(now.strftime('%X')) |
dc8c4dbac668dac8ae09edddb35d40492ade23db | pathikvsharma/pythonfiles | /python/hello.py | 2,383 | 3.703125 | 4 | import random
#numbers
x = 5
y = 10L
print (x+y)
#char
c = "p"
x = str(x) + "-men"
print x
#string : https://www.tutorialspoint.com/python/python_strings.htm
s = "Pathik Sharma"
print s
print s[3:5]
print s[5:]
print s + "'s"
print s * 2
str="pathik sharma is my name"
print "number of times 'a' comes is:",str.count(... |
156a87796bb205798846228c738bc98441071531 | AsanalievBakyt/classwork | /Classes_Planet.py | 854 | 3.90625 | 4 |
class Planet:
def __init__(self, name):
self.name = name
self.temp = -273
self.oxygen = False
self.water = False
self.humanity = False
def populate(self):
if self.humanity and self.oxygen:
self.population = 0
print('Планета пригодня дл... |
0161d8a35ce81625815121d56e93b56162a62b95 | sabirul-islam/Python-Practice | /ANISUL ISLAM/list.py | 1,125 | 4.34375 | 4 | subjects = ['javascript', 'python', 'php', 'java', 'flutter', 'kotlin']
print(subjects)
print(subjects[1])
print(subjects[2:]) # print from 2 number index
print(subjects[-1])
print('python' in subjects) # check is this subject in here?(case sensitive)
print('golang' not in subjects) # it returns true
print(subjects + [... |
d7fd7de4c9b9554039422265ecdf2cba2bc35f55 | sabirul-islam/Python-Practice | /ANISUL ISLAM/abstarct.py | 533 | 4.03125 | 4 | from abc import ABC, abstractmethod
class shape(ABC):
def __init__(self, dimension1, dimension2):
self.dimension1 = dimension1
self.dimension2 = dimension2
@abstractmethod
def area(self):
pass
class triangle(shape):
def area(self):
triangle = (self.dimension1 * self.dim... |
4cc11a706b7341e96f53f14043585f9579e8742b | sabirul-islam/Python-Practice | /ANISUL ISLAM/exerciseClasss.py | 283 | 3.734375 | 4 | class triangle:
def __init__(self, base, height):
self.base = base
self.height = height
def areaCalculation(self):
print(f'Area = {.5 * self.base * self.height}')
t1 = triangle(10, 20)
t1.areaCalculation()
t2 = triangle(20, 30)
t2.areaCalculation() |
7197abbb7dcdd8035d68e57288ca87895cee54be | sabirul-islam/Python-Practice | /ANISUL ISLAM/inheritanceOverWriting2.py | 510 | 3.8125 | 4 | class shape:
def __init__(self, dimension1, dimension2):
self.dimension1 = dimension1
self.dimension2 = dimension2
def area(self):
print('I am area method of shape class.')
class triangle(shape):
def area(self):
triangle = (self.dimension1 * self.dimension2) / 2
pri... |
67d15b1da589815fc8144d582097304feda1a6f9 | sabirul-islam/Python-Practice | /ANISUL ISLAM/queue.py | 186 | 3.703125 | 4 | # FIFO: First In Last Out
from collections import deque
bank = deque(['x', 'y', 'z'])
bank.popleft()
print(bank)
bank.popleft()
bank.popleft()
if not bank:
print('No persons left') |
f8d4364d89e13ea7fd73ecb11ab6adb3bfceff98 | arka2010/MyFirst123 | /Lasy Letter of a String.py | 607 | 3.828125 | 4 | # Make sure to un-comment the function line below when you are done.
# Remember to name your function correctly.
# Write your code here...
def last_letter(string):
return string[-1]
# Do not remove lines below here,
# this is designed to test your code.
def test_last_letter():
assert last_letter('... |
df39015b76cd8b95d0f0f45e984e8a5fdd68e1c5 | MonikaMel/homeworks | /script3.py | 490 | 3.546875 | 4 | def delete_punctuations(text: str):
from unicodedata import category
incomplate = ''.join(n for n in text if not category(n).startswith('P'))
text_without_punct = ''.join(n for n in incomplate if not category(n).startswith('S'))
return text_without_punct
text_data = ['Test!!!! hello. esim. test2...',
... |
6c1aaf56b5c7f18dee680a5445c3f684d81dfcb6 | Noman5237/RoutinePlanner | /Event.py | 855 | 3.5625 | 4 | from Time import Time
class Event:
name = ""
start: Time
end: Time
duration: Time
collidedEvents: [Time]
def __init__(self, name, start, end):
self.name = name
self.start = start
self.end = end
self.duration = end - start
if start > end:
... |
f2da440e5cff89b09893437b45548d8c48e187ac | debdip/CSE_DU | /ML/intermediate_pytorch.py | 87,736 | 3.9375 | 4 | """
NLP From Scratch: Classifying Names with a Character-Level RNN
**************************************************************
We will be building and training a basic character-level RNN to classify
words. This tutorial, along with the following two, show how to do
preprocess data for NLP modeling "from scratch", ... |
f65cdf6165baf7d38bea5d548629caa7f06de8f5 | leomatheuss/binarysearch | /binarysearch.py | 1,501 | 3.828125 | 4 | import random
import time
from sorts import bubble_sort, quicksort
import sys
sys.setrecursionlimit(300000)
def binary_search(vetor, inicio, fim, valor):
'''
Implementação recursiva
'''
i = fim - inicio // 2
if vetor[i] == valor:
return print(i)
elif inicio == fim:
return print(... |
c3272194552f1f07cf75f55957373f2c2545289c | Matei-L/social_network_bfs | /social_network/Node.py | 193 | 3.5 | 4 | class Node:
def __init__(self):
self.neighbours = []
self.visited = False
self.parent = None
def add_neighbour(self, index):
self.neighbours += [index]
|
886f03b9799087f83a6eadfb05b1538d8059e79a | adhirajgupta/c98-homework | /swapping2.py | 353 | 3.6875 | 4 | def swap():
Input1 = input("Enter the name of file1 - ")
Input2 = input("Enter the name of file2 - ")
data1 = open(Input1)
content1 = data1.read()
data2 = open(Input2)
content2 = data2.read()
d1 = open(Input1,'w')
c1 = d1.write(content2)
d2 = open(Input2,'w')
c2 = d2.wr... |
8357c14185d747a30b9eadf452a6baf8180b48a7 | melihkurtaran/CS210_Data_Science | /python panda.py | 15,651 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
# Assignment Done By Melih Kurtaran
The aim of this assignment is to get used dataframe manipulations with Pandas library.
"""
from google.colab import drive
drive.mount("/content/gdrive", force_remount=True)
"""## Get to Know Your Data
#### Titanic Dataset
The dataset store the survi... |
3af030f7ca5eeed3f0e920263a12c6941d244c1a | GabrielClmcn/kholle_1.5_B2 | /CLEMENCON_Gabriel_kholle_1.py | 4,559 | 4.15625 | 4 | #!/usr/bin/python3.6
############################################################################################################################
# CLEMENCON_Gabriel_kholle_1.py #
# Ce programme fait de simple... |
0490cc497c609198e9a665f99f6d044f672b1bcd | RezisEwig/SWEA-codes | /최적화_advanced/5일차-그래프_색칠하기.py | 1,002 | 3.734375 | 4 | def paint(i) :
global result
color_set = set(range(1, M+1))
for k, v in enumerate(real_map[i]) :
if v == 1 :
color_set -= {color_map[k]}
if len(color_set) == 0 :
result = 0
return
color_map[i] = min(color_set)
T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을... |
32c7c5e081ac2b342f0fdeb3f1b94e2e81336860 | RezisEwig/SWEA-codes | /진수변환/1일차 - 이진수2.py | 705 | 3.8125 | 4 | T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
for test_case in range(1, T + 1):
# ///////////////////////////////////////////////////////////////////////////////////
num = float(input())
bi_num = ""
divide = 1
for i in range(12) :
divide = divide/2
if num >= divide :
... |
40bee67cf2dd2307024d7be4dd6adf3e83eec69c | phamand2/PYTHON101-INT-LESSONS | /Tip Caculator 2.py | 809 | 3.953125 | 4 | total_amount = float(input('Total bill amount? '))
service = input('Rate your level of service from good, fair or bad: ')
service = service.lower()
if service == 'good':
tip_amount = total_amount * .2
elif service == 'fair':
tip_amount = total_amount * .15
elif service == 'bad':
tip_amount = total_amount * .1
... |
cf733f8829931a5e403710b7a3b7248f2c82b045 | phamand2/PYTHON101-INT-LESSONS | /How many coins?.py | 276 | 4.0625 | 4 | ask_for_coin = int(input('How many coins do you want? '))
coin = 0
while coin <= ask_for_coin:
print(f'You have {coin} coins.')
ask_for_another= input('Do you want another? ')
if ask_for_another.lower() == 'yes':
coin = coin + 1
else:
print('Bye')
break
|
a8b34ed65ebc78cc4d1a2c9bac4dcf6575c085ad | phamand2/PYTHON101-INT-LESSONS | /Doing Exericse again/Celsius to Fahrenheit.py | 92 | 3.765625 | 4 | C = float(input('Give me a temperature in Celsius: '))
F = (C * 9/5) + 32
print(f'{F} F')
|
b10df9b25153a2e1020ee9f13c1da1153d5925cb | harrika/python-data | /part04-e07_subsetting_with_loc/src/subsetting_with_loc.py | 426 | 3.65625 | 4 | #!/usr/bin/env python3
import pandas as pd
def subsetting_with_loc():
df = pd.read_csv('src/municipal.tsv', sep="\t", index_col=0)
# df = df.iloc[1:312]
df = df.loc['Akaa':'Äänekoski']
cols = ['Population','Share of Swedish-speakers of the population, %',
'Share of foreign citizens of the population, %']
retu... |
1b9daa6e3f3e1f890f499a7b668e3bc1615421a3 | harrika/python-data | /part03-e02_first_half_second_half/src/first_half_second_half.py | 387 | 3.5625 | 4 | #!/usr/bin/env python3
import numpy as np
def first_half_second_half(a):
m,n = a.shape
k = int(n/2)
x1 = a[:,0:k]
x2 = a[:,k:]
sx1 = np.sum(x1, axis=1)
sx2 = np.sum(x2, axis=1)
tr = sx1>sx2
aa = a[tr]
return aa
def main():
np.random.seed(110)
ee = np.random.randint(1,50,(3,8))
print(ee)
print()
print(f... |
e0d7e1f489581427ed900ac77b644d04c14a90d5 | harrika/python-data | /part02-e12_row_and_column_vectors/src/row_and_column_vectors.py | 525 | 3.71875 | 4 | #!/usr/bin/env python3
import numpy as np
def get_row_vectors(a):
dd = []
m,n = a.shape
for e in range(m):
cc = a[e,:].reshape(1,n)
dd.append(cc)
return dd
def get_column_vectors(a):
ddx = []
m,n = a.shape
for p in range(n):
cc = a[:,p].reshape(m,1)
ddx.append(cc)
return ddx
def main():
np.ran... |
658b3fcc34d1693ec542910c75eff3908e0be70a | harrika/python-data | /part01-e20_usemodule/src/triangle.py | 360 | 3.546875 | 4 | # Enter you module contents here
'''has functions for area and hpothenuse'''
import math
def hypothenuse(a,b):
'''gives side of a triangle uses pythogras theorem'''
return math.sqrt(a**2 + b**2)
def area(a,b):
'''returns hte area of a rectangle of sides a and b'''
fg = 0.5*a*b
return fg
# return float(fg)
__a... |
8b9cb7474051d8b1695adc90503f27f78d102f48 | Pandock/Python_lessons_basic | /lesson03/home_work/hw03_normal.py | 1,987 | 3.703125 | 4 | # Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
fibo_list = [1, 1]
for i in range(m):
count = len(fibo_list) - 2
last = len(fibo_list) - 1
fibo_list.append(fibo_list[count] + fibo_li... |
de63fb851bf310b62c61a7064c6e32053a0d33f3 | iyan9/wee | /Version7.py | 22,584 | 3.546875 | 4 | '''
1. 開始介面完成了,之後可以再美化
2. 新增了restart鍵
- 遊戲失敗跟通過都可以restart(或按SPACE鍵)
3. 遊戲進行中也可以按SPACE鍵來restart
'''
import random
from collections import deque
import pygame
from pygame.locals import KEYDOWN, K_SPACE, MOUSEBUTTONUP, QUIT
Color = {
1: (0, 206, 209),
2: (179, 153, 255),
3: (255, 128, 191),
4: (255... |
ac57c453ae092a2616ec27b415d1a292486f624f | LauraJaneStevenson/remove-node | /remove-linked-list-node.py | 1,567 | 4.09375 | 4 | class Node(object):
"""Class in a linked list."""
def __init__(self, data, next=None):
self.data = data
self.next = next
def as_string(self):
"""Represent data for this node and it's successors as a string.
>>> Node(3).as_string()
'3'
>>> Node(3, Node(2, N... |
3fb30283b4aca903fac23c767582daa260a45b96 | BlisterB/L2-LS4 | /TP1/bisextile.py | 388 | 3.859375 | 4 | #!/usr/bin/python3.2
annee = input("Bonjour, quelle annee voulez vous tester ?\n")
estBisextile = False
if annee % 4 == 0 :
if annee % 100 == 0 :
if annee % 400 == 0 :
estBisextile = True
else :
estBisextile = True
#Affichage du resultat
if estBisextile :
print("L'annee est b... |
9e16e868981e7db6065dc582ed28b6e62ca15152 | BlisterB/L2-LS4 | /TP2/convertisseur.py | 1,353 | 3.8125 | 4 | #!/usr/bin/env python3
import sys
def celsius(nombre) :
return (nombre-32)*(5//9)
def fahrenheit(nombre) :
return nombre*(9//5)+32
def metre(nombre) :
return nombre//1.0936
def yard() :
return nombre*1.0936
def help() :
print("Convertit :\Celsius <=> Fahrenheit\nMetre <=> Yard")
def gestionPar... |
140453144218210956c1d07e7c4e86712fc69eda | BlisterB/L2-LS4 | /TP3/Test.py | 117 | 3.75 | 4 | #!/usr/bin/env python3
l = list()
i = 0
while i <= 10 :
l.append(i)
i = i + 1
print(l)
l[:] = [12]
print(l)
|
cc752812c2fcfbffd00a5bb9099575e04c120368 | stedy/misc | /count_barcode.py | 1,420 | 3.625 | 4 | """script to count named barcodes within a selection of target sequence"""
import string
import argparse
def main():
parser = argparse.ArgumentParser(description = """Generate summary stats
for barcodes within sequences""")
parser.add_argument('input_seqs', help = """input seq file as a raw .txt""")
... |
45954f5cb96653ebf296869be9691e75acdd782a | thalvadzhi/AI-for-Pac-Man | /ai/create_board.py | 1,211 | 3.515625 | 4 | from board import Board
Outside = 'o';
Path = 'p';
Dot = 'P';
Pill = 'H';
InnerWall = 'w';
OuterWall = 'W';
Cage = 'c'
TILE_SIZE = 15
OBSTACLES_REPR = [Outside, InnerWall, OuterWall, Cage]
def create_board(ghosts, pacman, map_size, map_repr, edible_ghosts, mitak_repr, lives):
''' ghosts is a list of tuples, pacma... |
9c0902b4f2462f906ce545355ec365ad0a73b06f | ambujverma/Basic-python-problems | /to check prime number.py | 666 | 4.0625 | 4 | #1
num = int(input('Insert a number: '))
a = [x for x in range(2, num-1) if num % x == 0]
def is_prime():
if num > 1:
if len(a) == 0:
print ('prime')
else:
print ('NOT prime')
else:
print('NOT prime')
is_prime()
print(a)
#2
import sys
number = input("Please enter a number" + "\n" + ">>>")
number... |
37b1dafa747ba88a452eaac61a5fc8976b8f434a | t7y/python_beyond_basics | /python-beyond-basics/08 iterables-and-iteration/demos/5filter.py | 196 | 3.59375 | 4 | positives = filter(lambda x: x > 0, [1, -5, 0, 6, -2, 8])
print(list(positives))
# filter 0, False, or empty
trues = filter(None, [0, 1, False, True, [], [1,2,3], '', 'hello'])
print(list(trues)) |
c9ff9605cdb0986fed5f97954813c6b6fb17ca57 | t7y/python_beyond_basics | /python-beyond-basics/08 iterables-and-iteration/demos/11ending_file.py | 135 | 3.65625 | 4 | with open('ending_file.txt', 'rt') as f:
# terminates on END
for line in iter(lambda: f.readline().strip(), 'END'):
print(line) |
cb945981d237f62176bc78dd63263f2c895ba2ce | lokesh1729/python-decorators-youtube | /Python Decorators Part 2/classes_as_decorators.py | 439 | 3.625 | 4 | import time
class Timeit:
def __init__(self, func):
self.func = func
self.initial = time.time()
def __call__(self, *args, **kwargs):
result = self.func(*args, **kwargs)
final = time.time()
print("total time it took is %s seconds" % (final - self.initial))
r... |
b1737a37b94f7c33ab3c99a8513c527f52d0fea0 | n-Holmes/deCryptid | /hextools.py | 7,557 | 3.671875 | 4 | """A library to allow easy manipulation of hexagonal grids"""
import numpy as np
# Square root of 3
_ROOT3 = np.sqrt(3)
# Transformation matrices to switch between coordinates.
# Hexagonal to Rectangular
HRTRANSFORM = np.array([[0.5, 0.5], [0, 1]])
# Rectangular to Hexagonal
RHTRANSFORM = np.array([[2, -1], [0, 1]]... |
a781fbff3e73f0fa9f4b9b60e13dbda7f02b3066 | Eslamhathout/SeleniumPythonOnPythonPrograms | /Calculator.py | 763 | 3.84375 | 4 |
try:
def add(x,y):
if type(x) == String:
try:
x = int(x)
except:
raise TypeError('You can not pass strings to add func')
elif type(y) == string:
try:
y = int(y)
exc... |
708c560f7cd388dac39c3cfd2f26a6c4088dc596 | a-phillips/misc | /ws_strat.py | 3,928 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:11:07 2020
@author: aphillips
Implementation of algorithm from GS interview.
Problem: You would like to bet on a team to win the world series with even odds.
The world series is won when either team reaches 4 wins, also called best of 7.
The... |
603c3cc34531bb3136f3869c204acf04907201f3 | CodeWorks21-Python/ciphers_solution | /atbash_cipher.py | 4,198 | 3.90625 | 4 | # author: elia deppe
# date: 7/28
# difficulty: easy
# Wikipedia: https://en.wikipedia.org/wiki/Atbash
# Read this for a better understanding of the cipher.
# Introduction
#
# Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.
#
# The Atbash cipher is a simple s... |
f2f955078acb680d524bd573fde982078cef0d47 | tusharbhatia2002/Code-in-Place-2021-final-project | /final-project.py | 3,588 | 4.1875 | 4 | '''
Welcome to the pre-screening test to check the eligibility of a candidate for job application.
the recruiter loads in a json file which contains the job requirements/parameters.
A series of questions is asked from the candidate for pre-screening/assessing the profile
'''
import json #importing json module
d... |
6e5d3388b082a90e99d3754db2642c234d579d53 | sidharth01g/Pricing | /pricing/src/common/utils.py | 1,679 | 4 | 4 | from passlib.hash import pbkdf2_sha512
import re
class Utils(object):
@staticmethod
def encrypt_password(password_hashed: str) -> str:
"""
Encrypts a hashed password string using pbkdf2_sha512
Args:
password_hashed: a hashed password
Returns:
A pbkdf2_... |
ee7f7b55f8606374e7f163723a2e017019bb36e7 | vicky299/praktikum-5 | /1.4.py | 217 | 3.921875 | 4 | a=-2
b=-7
if(a>0) and(b>0):
print("bilangan positif")
elif(a>0)or(b>0):
print("salah satunya positif")
elif(a<0) or (b<0):
print("salah satunya negatif")
elif(a<0) and (b<0):
print("keduanya negatif")
|
38ba18ef820315d1ff295785f6f4e8731dbf3dc4 | vicky299/praktikum-5 | /1.6.2.py | 158 | 3.765625 | 4 | a=-8
b=-3
if(a>0):
if(b>0):
print("keduanya positif")
else:
print("keduanya tidak positif")
else:
print("keduanya tidak positif")
|
39f18037b88bd51570d742e08301e5bc5d2a5d9c | dchaconoca/Ejercicios-B-sicos-de-Python | /ConversionNumerica.py | 3,331 | 3.921875 | 4 | """
##################################
EJERCICIOS CONVIRTIENDO NÚMEROS
EN DIFERENTES BASES DE 2 A 16
##################################
"""
from time import time
def esLetra(res):
letras = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F']
try:
res = str... |
1599733676592efbc334961011a4f6aaf2dd7e39 | hbkcad/Tic-Tac-Toe | /Tic-Tac-Toe.py | 9,497 | 4.09375 | 4 | from random import *
mat=[[9,9,9],[9,9,9],[9,9,9]]
player1=0
player2=0
check=0
lab=0
for row in mat:
print("\t",row)
print(""" The object of Tic Tac Toe is to get three in a row. You play on a three by three game board. The first player is known as 1 and the second is O.
Players alternate placing Xs and Os on the... |
6a1e3971fdb795bbab0ed2bb8254f88eb9a1f672 | lmp199198/yoyoketang | /lmp_file/lmp_3.py | 936 | 3.71875 | 4 | def ds(x):
return 2*x+5
print(ds(3))
a=lambda s:26*s-265+s/2-5
print(a(11))
def add(x,y):
return x*y
print(add(2,5))
b=lambda d:3556/d -23+5*d
print(b(6))
temp = filter(None,[1,2,3,0,12.2,False,True,'EQWE','a<b'])
print(tuple(temp))
c = filter(lambda x:x % 2, range(15)) #过滤
print(tuple(c))
c = map(... |
fd5b29fc783e9f02481bd48ab05b5f564aa8e288 | MonkeyDCode/Calculo-de-Metricas | /sample2.py | 266 | 3.6875 | 4 | #mario Alberto Gutierrez Corral
#Lista de numeros positivos que son la suma de ese numero
#funciones
def Suma(n,i):
if(i>n-i):
return 99
else:
print n ," = ",(n-i)," + ", i
return Suma(n,i+1)
#programa principal
x=int(raw_input("dame un numero"))
Suma(x,1)
|
bb8502d4ec527acb85c452504c36dcdfcd43863e | CodingPupper3033/Plants | /PathMaker.py | 866 | 3.640625 | 4 | class PathMaker:
def __init__(self, plant, distance, path = []):
self.current_plant = plant
self.can_be_next_to = []
self.distance = distance
self.pos_on = 0
self.path = path + [plant.name]
def is_end(self):
return self.pos_on == len(self.current_plant.plants_nex... |
81fee2d94d275af8830d6a78d2eac2cc81a386fa | katharine-atx/python-lpthw-35 | /hashmap.py | 1,765 | 3.921875 | 4 | # Version 2.7 to 3.5: print(), use {}/.format() instead of % foramtters.
# dicts (dictionaries) continued...
# for Exercise 39_test
# Creating a dictionary module
def new(num_buckets=256):
"""Initializes a Map with a given number of buckets."""
aMap = []
for i in range(0, num_buckets):
aMap.append([])
return aMa... |
60d399977527d4857f5e3ef63b8e7c850b63c4ed | katharine-atx/python-lpthw-35 | /ex44b_v35_override_inheritance.py | 325 | 4 | 4 | # Version 2.7 to 3.5: print()
# Explicit override example:
# Overriding a function in the parent for the child function
class Parent(object):
def override(self):
print("PARENT override()")
class Child(Parent):
def override(self):
print("CHILD override()")
dad = Parent()
son = Child()
dad.override()
son.overr... |
954c43b9d262d3b6bc8c896963d55a1548d67fa7 | Rutrle/udemy-django | /12-python-level-one/dictionaries.py | 132 | 3.546875 | 4 | my_stuff = {"key1": "value1", "key2": 'value2'}
print(my_stuff)
print(my_stuff['key2'])
my_stuff['new'] = 'thing'
print(my_stuff)
|
f9afa85718bbba21b1863ef35c05eaca7dd11e4d | Rutrle/udemy-django | /12-python-level-one/number_game.py | 1,323 | 3.921875 | 4 | from random import sample
nums = sample(range(1, 10), 3)
print('Welcome to the guessing game!')
print('You will be guessing three non repeating numbers')
game_running = True
def is_close(guess, real):
answer = []
for i in range(len(real)):
if int(guess[i]) in real:
answer.append(True)
... |
35a233eb79bb740164405dc9736972552266718c | yobee0304/algorithm_study | /algorithm/programmers_12904/longest palindrome.py | 749 | 3.53125 | 4 | def solution(s):
answer = 0
string = list(s)
# substring : string[i:j]
for i in range(len(string)):
for j in range(len(string), i, -1):
# substring의 길이
if j-i <= answer:
break
# substring의 길이가 palindrome인지 확인
if check_palindrome... |
4319566f18b96872655e8ac95426fd6a3406fafa | iamavailable/IneuronClassWork | /linear_search.py | 746 | 3.84375 | 4 |
# def linear_search(lst, n):
# pos = 0
# for i in range(len(lst)):
# if lst[i] == n:
# pos = i
# print("Found at",pos+1)
# return True
#
# return False
#
# arr = [12,2,1,34,23,65,31,98,36,122]
#
# n=31
# linear_search(arr, n)
# def binary_search(lst, n):
# ... |
d3b3c0036c2831c225c4ae07c05dbcdee2f44b9b | MathieuSylvestre/Insight | /scripts/make_predictions.py | 6,723 | 3.703125 | 4 | import joblib
from datetime import datetime , timedelta
from urllib.request import Request, urlopen
import time
import calendar
from dateutil.relativedelta import relativedelta
import pandas as pd
#Define city and latitude where predictions are to be made
city = 'japan/nagasaki'
df_latitudes = pd.read_csv('../data/raw... |
8581d259b82af97657b81cef557b13fbf82be456 | Nzparra/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 468 | 3.953125 | 4 | #!/usr/bin/python3
""" Minimum Operations """
def minOperations(n):
"""
Given a number n, write a method that calculates the fewest number
of operations needed to result in exactly n H characters in the file.
"""
n_ops = 0
summ = 1
aux = 0
while summ < n:
if (n % summ =... |
a2ebbe7a95c56145f67b5e46208e3bbced0c44d2 | Bokomoko/classes-and-operations-in-data-model-python | /main.py | 744 | 4.375 | 4 | class Polynomial:
# method to initialize the object with some values
def __init__(self, *coefs):
self.coefs = coefs
# function to represent the object (print)
# similar to __str__ but for debuging purposes
# it will be used if no __str__ method
def __repr__(self):
return 'Polynomial(*{!r})'.forma... |
5d4a3a535e2c1bdc753121d57053429ad651e182 | adawt/c100 | /c010.py | 306 | 3.984375 | 4 | """
【程序10】
题目:打印楼梯,同时在楼梯上方打印两个笑脸。
1.程序分析:用i控制行,j来控制列,j根据i的变化来控制输出黑方格的个数。
2.程序源代码:
"""
print(chr(1))
print('^^ ^^')
i = 0
for i in range(0, 10):
j = i + 1
print('MM' * j)
|
ae30f241c43d65237e05a103538865107ab11eed | adawt/c100 | /c057.py | 298 | 3.953125 | 4 | """
找到年龄最大的人,并输出。
"""
persons = {"a": 16, "b": 18, "c": 19, "d": 20}
current = ""
for key in persons:
if current == "":
current = key
else:
if persons[current] < persons[key]:
current = key
print("%s: %d" % (current, persons[current]))
|
b322c820d20d3d3de42258bdb7bdf43e78793300 | adawt/c100 | /c006.py | 263 | 4.09375 | 4 | """
【程序6】
题目:用*号输出字母C的图案。
1.程序分析:可先用'*'号在纸上写出字母C,再分行输出。
2.程序源代码:
"""
print(' * *')
print(' * *')
print(' *\n'*3, end='')
print(' * *')
print(' * *')
|
e08a9b64047b53872b12ee690cfa6cbbb3338c5a | adawt/c100 | /c004.py | 722 | 3.984375 | 4 | """题目:输入某年某月某日,判断这一天是这一年的第几天?
1.程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊
情况,闰年且输入月份大于3时需考虑多加一天。
2.程序源代码:
"""
year = int(input('Year:\n'))
month = int(input('Month:\n'))
day = int(input('Day:\n'))
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)
if 0 <= month <= 12:
sum = months[month... |
a8e62635edfc81ac1f1ecff27547532fe3918192 | adawt/c100 | /c034.py | 80 | 3.578125 | 4 | """
练习函数调用
"""
def add(a, b):
return a + b
print(add(1, 1))
|
45dbb4fe9f389dd29535895454f1179678ff5c99 | poppoerika/five-board | /FiveBoard.py | 8,055 | 4.15625 | 4 | # Author: Erika Tharp
# Date: 6/1/2020
# Description: This project includes a class called FiveBoard that represents .the board for a two-player game that is like tic-tac-toe, which is played on a 15 x 15 board.
# And each player is trying to get 5 in a row.
# The class has two private data m... |
e016eb42c4dfddfe2a7164ce439e896bd08efc53 | MichiMar/Python_excercises | /Enumeration-and-Iteration/BuildIncrementMatrix.py | 552 | 4.03125 | 4 | '''
[
[0,1,2,3,4],
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8]
]
'''
def manual_incrementing_matrix(n):
matrix = [ [ None for y in range(n) ] for x in range(n) ]
counter = 0
for idx, el in enumerate(matrix):
for nested_idx, nested_el in enumerate(el):
matrix... |
3ca81cce7fcf16010bd88b5fc94d932dd5834db0 | rodrigodata/learning | /pyhton/arithmetic_operations/arithmetic_operations.py | 434 | 4.1875 | 4 | # add
print(10 + 3) # 13
# subtract
print(10 - 4) # 6
#float
print(2.22 * 3) # 6.66
# multiplication
print(2 * 8) # 16
# division
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3 => Returns an integer from division
# modules
print(10 % 3) # 1 Returns the remaining
# exponation
print(10 ** 3) # 1000
####
#i... |
4aba544e4b2b5b8ef9f456b8acdf8461cc0157fe | esencgr/Programming_Contest_Solutions | /HackerRank/PYTHON/nested_list.py | 669 | 3.71875 | 4 | def func(lst):
mn = min(lst)
for val in lst:
if val > mn:
return val
if __name__ == '__main__':
py_students = list()
lst = list()
for _ in range(int(input())):
student = list()
name = input()
score = float(input())
student.append(name)
... |
f69b922883c61272175ca5b0a538106b2941a81a | esencgr/Programming_Contest_Solutions | /HackerRank/PYTHON/swap_case.py | 342 | 4.15625 | 4 | def swap_case(s):
temp = list()
st = ""
for i in s:
if i.islower():
temp.append(i.upper())
elif i.isupper():
temp.append(i.lower())
else:
temp.append(i)
return st.join(temp)
if __name__ == '__main__':
s = input()
result = swap_cas... |
03680f63e449badc106b0e374f85c9b74b3a0639 | batoulalkhatib/Facoders | /Python/week4-2.py | 168 | 3.859375 | 4 | print('Numbers from 1 to 10')
x= 5
while True :
y=float(input('Guess the number :'))
if y==x :
print('Great! You did it!')
break
else:
continue
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.