blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0ebfa784abeddd768186f99209602dd7ef870e56 | feleHaile/my-isc-work | /python_work_RW/6-input-output.py | 1,745 | 4.3125 | 4 | print
print "Input/Output Exercise"
print
# part 1 - opening weather.csv file
with open ('weather.csv', 'r') as rain: # opens the file as 'read-only'
data = rain.read() # calls out the file under variable rain and reads it
print data # prints the data
# part 2 - reading the file line by line
with open ('weather.... |
a40fd3e7668b013a356cfa8559e993e770cc7231 | feleHaile/my-isc-work | /python_work_RW/13-numpy-calculations.py | 2,314 | 4.3125 | 4 | print
print "Calculations and Operations on Numpy Arrays Exercise"
print
import numpy as np # importing the numpy library, with shortcut of np
# part 1 - array calculations
a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges
b = np.array([2, -1, 1, 0]) # creating an array from a list
# multip... |
51971384be9ec9e203ccfbea516624d8af552254 | TatyanaDovzhich/Project_25.01.2019 | /file_25.01.2019.py | 286 | 3.6875 | 4 | def addition(a, b):
return a+b
print (addition(25, 10))
def subtraction (a, b):
return a-b
print (subtraction(25, 10))
def multiplication (a, b):
return a*b
print (multiplication(25, 10))
def division(a, b):
return a/b
print (division (25, 10))
|
09db0244598717c41277e24f5036c951c11d40fb | jasonzzx/python-learning | /practice.py | 106 | 3.546875 | 4 | dict = {"key1": "value1", "key2": "value2"}
print(dict.keys())
print(dict.values())
print(dict.items())
|
7c572960ed2b5e510f74bd0c7078bc36ceacd320 | olliechick/sockets | /receiver.py | 3,168 | 3.8125 | 4 | #!/usr/bin/env python3
"""
A program to receive packets from a channel.
For a COSC264 assignment.
Author: Ollie Chick
Date modified: 29 August 2017
"""
import sys, socket, os, select
from packet import Packet, MAGIC_NO, PTYPE_DATA, PTYPE_ACK
from socket_generator import create_sending_socket, create_list... |
f175a5ed6a74560d9c4bafee94da753332691d6a | RobertsHenry/Pythonian | /StudentDiningClass.py | 3,584 | 3.59375 | 4 | # Author: Henry Roberts
# 4/16/2018
class studentDining(object):
# A Student at JMU who has punches, dining, and FLEX in an account.
# Attributes:
# Name: Their name.
# Punch Balance: How many punches they have left.
# Dining Balance: How much money they have left in dining dollars.
# FLEX Balance: How much... |
2927aa5e3bf5ac0fbd47f3d91c2581d4136451e2 | lewis1905/codecademy-challenges | /pokemon/pokemon.py | 3,808 | 3.875 | 4 | #creating a class for the pokemon.
class Pokemon:
def __init__(self, name, level, health, max_health, group, knocked_out = False):
self.name = name
self.level = level
self.health = health
self.max_health = max_health
self.group = group
self.knocked_out = knocked_out
#method for lo... |
278b100aef964098fce3aeb2fafad6d748b38889 | SunShineSeason/EnglishShuffledWord | /EnglishWord.py | 638 | 3.8125 | 4 | from itertools import permutations
import enchant
d = enchant.Dict("en_US") # Dict object defined in enchant module
list_a = list(input("please input a shuffled word:"))
a_length = len(list_a)
list_copy=[]
for permu in list(permutations(range(a_length), a_length)):
for i in permu:
list_copy.ap... |
f8323b264fbc205c5f10227d118dd5f606427ef9 | dcadavidzuleta/momento2nuevastecnologias | /Ejercicios con ciclos y estructuras de control/Ejcec07.py | 322 | 3.78125 | 4 | vocales = ["a", "e", "i", "o", "u"]
def dividirEnLetras(texto):
return [char for char in texto]
def contarVocales(texto):
lista = dividirEnLetras(texto)
dic = {}
for vocal in vocales:
dic[vocal] = lista.count(vocal)
return dic
texto = input("ingrese el texto")
print(contarVocales(texto... |
a61b28b6d392379fc71a057e452a08c4c450761f | dcadavidzuleta/momento2nuevastecnologias | /Ejercicios basicos para python/Ejbp03.py | 428 | 4.0625 | 4 | seguir = 1
estaturas = []
continuar = 1
def promediar(lista):
sum = 0
for item in lista:
sum += int(item)
return sum / len(lista)
while int(seguir) == 1:
estatura = input("Ingrese la estatura a evaluar\n")
estaturas.append(estatura)
seguir = input("Si desea ingresar otra ... |
fabdf9bef92c77a7d290249f53c92fb32270183e | raynerng/raspberrypi3 | /pushLED.py | 1,314 | 3.84375 | 4 | import threading
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(threading.Thread):
"""A Thread that monitors a GPIO button"""
def __init__(self, channel):
threading.Thread.__init__(self)
self._pressed = False
self.channel = channel
#set up pin as input
GPIO.setup(self.channel,GPI... |
fe9d692477b2fcde1e64b5c3a248f347d83abe90 | TestardR/Python_Fundamentals | /return_statement.py | 161 | 3.96875 | 4 | # return statements are necessary to get a value back from a function
def cube(num):
return num * num * num
result = cube(4)
print(cube(3))
print(result)
|
c6712fcb64227ba87d1bef13e85ff0a8f9163e00 | Alruk-art/mod_17 | /число и список.py | 1,658 | 3.984375 | 4 | def sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def find_position(arr, key):
left = -1
right = len(arr)
while right > left + 1:
mid = (left + right) /... |
5fc10a276f8505ceb89031b36fcd0f0c62557883 | Amanikashema/python-excercise-1 | /Conditionals ex.py | 1,113 | 3.90625 | 4 | print("************Salary employees Check***************")
annual_salary = int(input("Please enter your annual salary:R "))
contract_type = input("what is your contract type: ")
if contract_type == "full-time":
print("***Full time Employee***")
income_tax = float(input("Please enter your income tax without per... |
43d743a8305ec3018125f0589211a74bd61863d4 | Bucknell-ECE/Micromanipulator | /Joystick.py | 3,865 | 3.546875 | 4 | '''
This file contains the functions that the joytick uses.
Last Modified: R. Nance 5/15/2018
#####################DO NOT EDIT BELOW INFORMATION##################################
Originating Branch: Joystick
Originally Created: R. Nance 12/2017
'''
import pygame
from helper import *
#from helper import mapval
xAxis... |
12f3789e81a69e4daa75f9497dd94f382f5f0153 | zamunda68/python | /main.py | 507 | 4.21875 | 4 | # Python variable function example
# Basic example of the print() function with new line between the words
print("Hello \n Marin")
print("Bye!")
# Example of .islower method which returns true if letters in the variable value are lower
txt = "hello world" # the variable and its value
txt.islower() # using the .islow... |
1ef4a7869a5048f6d66fbdb56203fa2f0198fb22 | zamunda68/python | /dictionaries.py | 1,116 | 4.75 | 5 | """ Dictionary is a special structure, which allows us to store information in what is called
key value pairs (KVP). You can create one KVP and when you want to access specific information
inside of the dictionary, you can just refer to it by its key """
# Similar to actual dictionary, the word is the key and the mea... |
b87ff95c0c33ab60f41047922b83134b0621e3f2 | C-likethis123/adventOfCode | /2019/Day 6/part1.py | 1,250 | 3.71875 | 4 | '''
Some observations:
A)B
B)C
C)D
number of indirect orbits for p+1 is
number of direct orbits of planet p + number of indirect orbits of planet p
number of direct orbits can be calculated when input is read.
'''
class Planet:
def __init__(self, name):
self.name = name
self.planets_orbiting = []
self.orbits ... |
7f16d717ee4786370e5edc84df7f710ba0611486 | shin202j/find_the_site | /find_the_site/fw.py | 1,014 | 3.59375 | 4 | """Get a website from http://ddg.gg/ ."""
import requests
from bs4 import BeautifulSoup
from user_agent import generate_user_agent
def get_website(need_website=None):
"""Return a website."""
website = None
if need_website:
# Find website
find_website_ddg = "website " + need_website
... |
a95b3e4a2102e76c1a6b4932d6053a66b9593d5d | b-zhang93/CS50-Intro-to-Computer-Science-Harvard-Problem-Sets | /pset6 - Intro to Python/caesar/caesar.py | 1,022 | 4.21875 | 4 | from cs50 import get_string
from cs50 import get_int
from sys import argv
# check for CLA to be in order and return error message if so
if len(argv) != 2:
print("Usage: ./caesar key k")
exit(1)
# checks for integer and positive
elif not argv[1].isdigit():
print("Usage: ./caesar key k")
exit(1)
# defi... |
0dfe3bd5b3a5ff53b9c3950372415138caaea83f | sukruthananth/A-path-finding-with-obstruction | /ShortestPath.py | 5,904 | 3.59375 | 4 | import pygame
from queue import PriorityQueue
pygame.init()
width = 600
rows = 50
win = pygame.display.set_mode((width,width))
pygame.display.set_caption("Shortest Path with obstruction(A* Algorithm)")
class Node:
def __init__(self, i, j, width, rows):
self.width = width
self.x = i
self.y =... |
9dc9e3405a329105c9700b04146e0b814b3bbc5d | dkong3/pylearning | /practice5.py | 290 | 3.640625 | 4 | import datetime
import math
# help(datetime.date)
d1=datetime.date(2014, 7, 2)
d2=datetime.date(2014, 7, 11)
delta = d2-d1
print(delta.days)
print("%3.5f" %(math.pi*4/3*6**3))
def diff(n):
if n>17:
return 2*(n-17)
else:
return 17-n
print(diff(22))
print(diff(3))
|
cd316cf1233735f58c2926bf26a746ef2299dfc8 | castroandrew/cs114 | /random1.py | 189 | 3.9375 | 4 | import random
print('enter a number to see what it trully is')
base_number= len(input())
random_number = random.randint(1,15)
new_number= random_number + int(base_number)
print(new_number)
|
65a854c69f0817a2ee611efeec08a5b56620d740 | castroandrew/cs114 | /Castro_space_dungeon.py | 501 | 3.546875 | 4 | print("welcome to Space Dungeon")
print("Press Enter To Continue")
input()
print("Choose your Class")
print("Space Duck")
print("That One Human")
print("Sexy Alien")
classes = input()
print("Delegate Points. You have 100 to spend. ")
print("How Many points to magic")
magic = input()
print("How many points to attack")
a... |
71b2c28b3417017184b8b2719bef9d997b30673e | Mat-Nishi/labs-do-uri-2k21-python | /lab 5/Instruções do Robo.py | 431 | 3.59375 | 4 | n = int(input())
for i in range(n):
instrucoes = int(input())
movimentos = []
for i in range(instrucoes):
instrucao = input()
if instrucao == 'LEFT':
movimentos.append(-1)
elif instrucao == 'RIGHT':
movimentos.append(1)
else:
idx... |
fca00ca32bccf6122ce946e27382d9676477d574 | Mat-Nishi/labs-do-uri-2k21-python | /lab 2/Aposentar.py | 161 | 3.921875 | 4 | a = int(input())
b = int(input())
if (a >= 65 or b >= 30 or (a >= 60 and b >= 25)):
print('Apto a aposentadoria')
else:
print('Inapto a aposentadoria')
|
e8980b19bafa240bbfe5cfef4f9e7410d00cfe58 | Mat-Nishi/labs-do-uri-2k21-python | /lab 1/Media Ponderada.py | 132 | 3.875 | 4 | # -*- coding: utf-8 -*-
a = float(input())*3
b = float(input())*5
c = float(input())*2
print("Media = {:.2f}".format((a+b+c)/10))
|
5115af6bdbd754c100d544519146e51a0c9a6d96 | Mat-Nishi/labs-do-uri-2k21-python | /lab 4/Produto Escalar.py | 448 | 3.53125 | 4 | v1 = []
v2 = []
soma = 0
val = int(input())
while val >= 0:
v1.append(val)
val = int(input())
val = int(input())
while val >= 0:
v2.append(val)
val = int(input())
if len(v1) > len(v2):
for i in range(len(v1) - len(v2)):
v2.append(0)
else:
for i in range(len(v2) - l... |
7d6030f334900160ba8f969346b622b38667999d | Mat-Nishi/labs-do-uri-2k21-python | /lab 6.py | 2,308 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 13 19:44:10 2021
@author: Mateus
"""
# Conjunto de funções para uma calculadora.
def soma(x, y):
resultado = x+y
return resultado
def subtracao(x, y):
resultado = x-y
return resultado
def multiplicacao(x, y):
resultado = x*y
return resultado... |
1507b6a0ca2b69bca216644ffcabc281d4f446b3 | gmarler/courseware-tnl | /labs/py3/decorators/returns.py | 1,035 | 3.734375 | 4 | '''
>>> f(3,4)
7
>>> f(4,3)
Traceback (most recent call last):
...
TypeError: Incorrect return type
>>> a_to_upper("alpha")
'ALPHA'
>>> a_to_upper("Andrew")
'ANDREW'
>>> a_to_upper("Bart")
Traceback (most recent call last):
...
TypeError: Incorrect return type
>>> a_to_upper("Zed")
Traceback (most recent call last)... |
c891f23d90e49fa066d06e90fd5ad2d45c9afd7d | gmarler/courseware-tnl | /labs/py3/decorators/memoize.py | 1,122 | 4.1875 | 4 | '''
Your job in this lab is to implement a decorator called "memoize".
This decorator is already applied to the functions f, g, and h below.
You just need to write it.
HINT: The wrapper function only needs to accept non-keyword arguments
(i.e., *args). You don't need to accept keyword arguments in this lab.
(That is m... |
7a0db229f0af3b6ea99b7b0a8919c245233c3be0 | BigerWANG/pythoncookbook | /chapter1/pyck15.py | 1,039 | 3.84375 | 4 | # coding: utf-8
import heapq
"""
用py实现一个优先级队列, 每次pop都返回优先级最高的那个元素
"""
class PriorityQueue(object):
"""用py实现一个优先级队列, 每次pop都返回优先级最高的那个元素"""
def __init__(self):
self._queue = list()
self._index = 0
def push(self, iterm, priority):
# 优先级,元素的原始索引, 元素值, 按照数字越大优先级越大的规则
heapq.heappush(self._queue, (-priority, se... |
e665e98a3ee81dde5ec3f219258971339c703d33 | RXCORE/healthcare_twitter_analysis | /code/twitter_functions.py | 13,048 | 3.78125 | 4 | def twitterreq(url, method, parameters):
"""
Send twitter URL request
Utility function used by the others in this package
Note: calls a function twitter_credentials() contained in
a file named twitter_credentials.py which must be provided as follows:
api_key = " your cre... |
529b20dc528b3a96fa6ad7229e63cfd91328da17 | Snickers97/algoirthms | /algo2.py | 298 | 3.78125 | 4 | import math
import matplotlib.pyplot as plt
def T(n):
if n<1:
return 1
return T(n-1)+3*n+1
y1 = []
y2 = []
x = range(0,501)
for i in range (0,501):
y1.append(T(i))
y2.append(i**2)
#print(i,": ",T(i)," ",i**3)
plt.plot(y1,x)
plt.show()
|
240a99862d3fb48da26e6622d5fac4bd6856f88f | escovin/Delivery_Routing_System | /ReadCSV.py | 3,288 | 3.625 | 4 | import csv
from HashTable import HashMap
with open('WGUInputData.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
insert_into_hash_table = HashMap() # Calls the Hashmap class to create an object
first_truck = [] # first truck delivery list
second_truck = [] # second truck delivery list... |
f23af68d6156597af0f012338971efa70f524812 | kpetrone1/kpetrone1 | /s11_who_is_thief.py | 633 | 4.03125 | 4 | """
Four suspects; one of them is a thief. In interrogation
John said: I am not the thief.
Paul said: George is the thief.
George said: It must be Ringo.
Ringo said: George is lying.
Among them, three were telling the truth while one was lying.
Could you find out who is the thief?
"""
for thief in ['Jo... |
3f7a247198d94307902d20edec5016511a4343e6 | kpetrone1/kpetrone1 | /s7hw_mysqrt_final.py | 1,348 | 4.4375 | 4 | #23 Sept 2016 (Homework following Session 7)
#While a few adjustments have been made, the majority of the following code has been sourced from a blog titled "Random Thoughts" by Estevan Pequeno at https://epequeno.wordpress.com/2011/01/04/solutions-7-3/.
#function to test Newton's method vs. math.sqrt() to find squar... |
a046002c3988d9265c2e8095e592bed65e041a5f | kpetrone1/kpetrone1 | /s11hw_dict.py | 1,141 | 3.875 | 4 | # >> HOMEWORK: DICTIONARIES <<
# Exercise 1
# def histogram(s):
# d = {}
# for c in s:
# d[c] = s.get(c, 0) #? How does one add an entire item (that is, BOTH the key and its corresponding value) to a dictionary?
# return d
# name = 'kaija'
# print(histogram(name))
def check_if_word_is_in_... |
ce31d13f1220f58de9e54d501219344e4123eadd | ads2100/paython | /day10.py | 358 | 3.875 | 4 | age = 33
text ="my name bodour i am {}"
print(text.format(age))
qunantity = 77
itemno = 123
price= 78
myorder = "i want {} pieces of item {} for {} dollars."
print(myorder.format(qunantity,itemno,price))
qunantity = 77
itemno = 123
price= 78
myorder = "i want {2} pieces of item {0} for {1} dollars."
print(m... |
bec28c0850c9da9d478884a986ba990df8a16b37 | ads2100/paython | /day.17.2.py | 335 | 4 | 4 | thistuple = ("mohamed","ahmed","sarh")
if "mohamed" in thistuple:
print("yes,he is here")
thistuple = ("bodour amizing girl,")*4
print(thistuple)
x = (1,3,5,5)
q = (9,6,6)
v = x+q
print(v)
print (len(v))
i = (("hi","wlcome","sir"))
print(i)
thistuple =[2,4,4,"a","e"]
thistuple = tuple(thistuple)
p... |
17338eb251bf410b6b300ec7d34bbd80b1101041 | ads2100/paython | /day20.py | 274 | 3.890625 | 4 | thisset = {}
print(thisset)
thisset = {"a","h","y"}
print(thisset)
y = {"ahmed","bodour","asma","bodour",1,8,8}
print(y)
for x in y:
print(x)
print("bodour" in y)
y.add("soso")
print(y)
u = {"say","hi"}
u.update(["welcome"])
print(u) |
fd729bb04abad4f1467bc547006bc5efac30e373 | hliu1006/Python-Project | /Machine Learning/Predict Quality Of Wine/game-of-wines.py | 24,490 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Part 1: Using Data Science to Understand What Makes Wine Taste Good
# ## Section 1: Data Exploration
#
# In this section, we'll do some exploratory analysis to understand the nature of our data and the underlying distribution.
# ### First, import some necessary lib... |
72608782eca9e07321c885c499b88d168795cae4 | mrollins/ithelps | /ithelps/impl.py | 863 | 3.953125 | 4 | #!/usr/bin/env python3
import itertools as it
from typing import Iterable
def munch(iterable: Iterable, n: int):
"""
Consume an iterable in sequential n-length chunks.
>>> [list(x) for x in munch([1, 2, 3, 4], 2)]
[[1, 2], [3, 4]]
:param iterable: sequence to iterate.
:param n: int - Chunk le... |
dd6787ead793162ffc2fdca263fd49ba64611fa7 | AustinRivers100/exercises100 | /exercises7.py | 2,514 | 3.765625 | 4 | #第7次作业记录请朋友来玩
#step1 把文本文件读取进来
from random import randint
f = open('Record.txt') #打开文件
Record_lines = f.readlines() #用readlines把文件内容按行读取进来得到一个列表
#print(type(Record_lines), Record_lines ) #可以查看下处理效果
f.close()
#step2 因为读进来的是一个包含多项字符串的列表,需要还处理成可以直接使用的数据
game_dict = {}
for i in Record_lines:
Record = i.split()#去处空白符
... |
0797bf0cd9f567df436e5a6ee8842418c09863bf | TheChandaChen/github-upload | /Assignment_7.1.py | 162 | 4.0625 | 4 | # Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
cap = line.upper()
cap = cap.rstrip()
print(cap)
|
023879185123a87e7b9c8f6f949f93a66f417e77 | harsh52/Assignments-competitive_coding | /Algo_practice/MissingInterger.py | 813 | 3.6875 | 4 | '''
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the functi... |
195af12c76b90e4a16b44df8482e3a3cc2f65a64 | harsh52/Assignments-competitive_coding | /Algo_practice/link_list.py | 745 | 3.78125 | 4 | class node:
def __init__(self,data):
self.data = data
self.next = None;
class Link_list:
def __init__(self):
self.start = None;
def make_node(self,value):
if(self.start==None):
self.start = node(value)
else:
temp = self.start
while... |
5b1daf62fd1dd3b13617393cd23ce42ea58a08b4 | harsh52/Assignments-competitive_coding | /Amazon_question/function.py | 281 | 3.703125 | 4 | def f(x):
if abs(x)<=1:
if x==1:
return 1
if(x== -1):
return -1
if x==0:
return 0
else:
if x>0:
return f(x-1) + f(x-2)
if x<0:
return f(x+1) + f(x+2)
print (f(int(input()))) |
92297bb3778093c35679b32b2a1ffd22a3339403 | harsh52/Assignments-competitive_coding | /Algo_practice/LeetCode/Decode_Ways.py | 1,874 | 4.1875 | 4 | '''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" c... |
7acd01f6e13eb10829295829580ae63783583294 | harsh52/Assignments-competitive_coding | /Algo_practice/LeetCode/Minimum_Depth_of_Binary_Tree_leetcode.py | 918 | 4.09375 | 4 | '''
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None... |
0780b7873326cf08a41f744731aed432c6244c91 | Battleship-Potemkin-Village/RPN-Calculator | /rpn.py | 45,136 | 3.65625 | 4 | #! /usr/bin/env python3
# vim:fileencoding=utf-8
"""
Type in your equation using Reverse Polish Notation. Values (numbers) are
added to the stack. Operators act upon the values in the stack.
Values/operators can be input individually (pressing ENTER after every
number/operator) or by separating the tokens with... |
690e69c6d13e8bcb9ed1b787ff71e4269dde04ea | UzarKarz/PA1 | /Week3/Kontrollülesanne 3.1 - Mantra.py | 566 | 3.671875 | 4 | """Mantra on silp, sõna, lause või heli, mida kasutatakse paljudes idamaistes
religioonides mediteerimisel. Mantrat korratakse nii kaua kui vajalikuks
peetakse.
Koostada programm, mis
1. küsib kasutajalt lause, mida ta soovib mantrana kasutada,
2. küsib kasutajalt, mitu korda ta soovib mantrat korrata,
3. väl... |
4c98de9380eba70b40f0f14ad1a12e57c784aa30 | yunlum/Directions-Application-with-MapQuest-API | /P3_class.py | 7,757 | 3.53125 | 4 | # YUNLU MA ID: 28072206
class LATLONG:
'''
This class is used to get the useful data of LATLONG from the dictionary named "data_base"
and make some adjustments to let the data match the format of output requirements.
Finally, return a list of required data
'''
def __init__(self):
... |
f4913c5520d6ca539395680dbf13250466297843 | louizoslogic/mini_capstone | /atm.py | 1,974 | 3.84375 | 4 | import pickle
from datetime import datetime
class atm:
def __init__(self, user):
self.transaction = ''
self.user = user
self.balance = 0
self.pin = input('Create a 4 digit pin: ')
with open('user_data.txt', 'r') as file:
account_number = file.read()
... |
be9473d6a960a65afbcf112ee915cb3145ba3c36 | CAMcDonald/oc-cs240 | /Lab 1/flag.py | 3,751 | 3.546875 | 4 | import pygame
## Colors that need to be used for the program to draw a flag
white = pygame.Color(255, 255, 255)
blue = pygame.Color(0, 0, 205)
yellow = pygame.Color(255, 255, 0)
black = pygame.Color(0, 0, 0)
green = pygame.Color(0, 100, 0)
red = pygame.Color(255, 0, 0)
class Rect(object):
def __init__... |
91716b641f0ef3d030c23fbf3c48345c61eb1377 | PhoenixTAN/A-Vanilla-Neural-Network | /A naive nerual network/P1SkeletonDataset1.py | 13,495 | 3.90625 | 4 | import csv
import numpy as np
import random
import matplotlib.pyplot as plt
class NeuralNetwork:
def __init__(self, X, Y):
# Activate function has been define in this class
self.X = X
self.Y = Y
self.num_of_input = self.X.shape[1]
self.num_of_output = self.Y... |
fd47e93bd8b9eeb2cd56f4d165b5c6c19b7081db | sevenqwl/PythonProjects | /Learning/Python12期/day5/re模块.py | 589 | 3.59375 | 4 | import re
string = "192.168.2.2"
m = re.match("([0-9]{1,3}\.){3}\d{1,3}", string)
print(m.group())
string2 = "Alex li"
m = re.search("[a-z]", string2, flags=re.I) # flags=re.I不区分大小写
string2 = "alexi \nseven\bli"
m = re.search("^a.*$", string2, flags=re.M)
print(m.group())
# 匹配手机号
phone_str = "hey my name is alex, a... |
ed133799d812bb8f85473917e26c8639ce31a3ec | sevenqwl/PythonProjects | /Learning/Python12期/day4/二维数组90度旋转.py | 330 | 3.625 | 4 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Seven"
# 二维数组90度旋转
data = [[col for col in range(4,10)] for row in range(4,110)]
# print(len(data[0]))
for i in data:
print(i)
print('')
for r_index,row in enumerate(data[0]):
print([data[c_index][r_index] for c_index in range(len(data))]) |
bb62c720f28e25b1841b61f2207282ab225ef447 | Silvio622/Computational_Alogrithm | /Sorting3.py | 34,195 | 3.765625 | 4 | '''
import random
import time
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Create a Dataframe
df = pd.DataFrame({'Algoritms':["Bubble Sort","Selection Sort","Insertion Sort","Quick Sort","Merge Sort","Count Sort"]},index:=None)
samples = [100,200,500,1000,5000] #create an array with dif... |
5bfd688f204ec052eddb248a466c0df6918a1291 | RedChlorine/DeskOne | /cookBook.py | 1,803 | 3.65625 | 4 | #Decimals##################
import decimal
from decimal import Decimal
borderLine = "///"*10
taxRate = Decimal('7.25')/Decimal(100)
purchaseAmount = Decimal('2.95')
penny = Decimal('0.01')
totalAmount = purchaseAmount+taxRate*purchaseAmount
totalAmount.quantize(penny, decimal.ROUND_UP)
print(totalAmount)
print(bord... |
7153f3aae6742f8c118b6b69bce672eb388f1592 | someshmahule/DataStructures | /SimpleStk.py | 823 | 3.59375 | 4 | class Stk:
def __init__(self,size):
self.size = size
self.stk = []
def printStk(self):
print(self.stk)
def isEmpty(self):
if len(self.stk) == 0:
return "Empty"
else:
return "Not Empty"
def push(self,x):
self.stk.append(x)... |
2a7bfe5e36dd16489cd059749a3dead21d1b6016 | thehummingbird/Machine-Learning-and-Deep-Learning | /Logistic Regression/LogisticRegression.py | 1,238 | 3.5625 | 4 | import numpy as np
class LogisticRegression:
def __init__(self,lr=0.02,iter=10000):
self.lr = lr
self.iter = iter
def sigmoid(self, z):
return (1/(1 + np.exp(-z)))
def gradient_descent(self,y,x):
for i in range(self.iter):
yhat = self.sigmoid(np.dot(self.w.T,x)... |
c3cac605ba5a47da5cc7132d42a7976dc5fcdfa4 | teqn0x/Polynomial_Classes | /Python/polynomial.py | 2,880 | 3.578125 | 4 | import os,sys,math,cmath
class polynomial:
def __init__(self,lcoeffs):
self.lcoeffs = lcoeffs
#Making it floats because of the division by 0 when doing the ABC formula
for i in range(len(self.lcoeffs)):
self.lcoeffs[i] = float(self.lcoeffs[i])
def __str__(self):
outstring = ''
N = len(s... |
b7c7db07bc5758ab86b5c33967f2f62fd09a6bc6 | nishmaj/DSAN-Projects | /project2/problem5/problem_5.py | 1,542 | 3.796875 | 4 | """
problem_5.py - BlockChain
build a link list to store basic blockchain data
the data in this example is just a random integer
"""
import hashlib
import time
class Block:
def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash ... |
8d46c2db69ef57cce95058c8a484eb147fb82ab6 | andyqu94/homework | /python-challange/PyBank/main.ipynb.py | 850 | 3.515625 | 4 | import pandas as pd
import sys
filepath = "Resources/budget_data.csv"
df = pd.read_csv(filepath)
total_month = len(df["Date"].unique())
total = df["Profit/Losses"].sum()
df2 = df["Profit/Losses"].diff()
average_change = df2.mean()
greatest_increase = df2.max()
greatest_decrease = df2.min()
df3 = df2.sort_valu... |
137a5ddac366c0fefbbae211c75f4e9a6ac2206a | Muhammadshamel/Investigating-Texts-and-Calls | /Task2.py | 1,251 | 4.0625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the ... |
28f0e5637cd7ca7d5b47451e27e6e1d0ac7db093 | zlatnizmaj/GUI-app | /OOP/OOP-03-Variables.py | 642 | 4.40625 | 4 | # In python programming, we have three types of variables,
# They are: 1. Class variable 2. Instance variable 3. Global variable
# Class variable
class Test():
class_var = "Class Variable"
class_var2 = "Class Variable2"
# print(class_var) --> error, not defined
x = Test()
print(x.class_var)
print(x.class_var2... |
1e45cfd30735bc93f3341bb6bfdec05603fa77fc | pravsp/problem_solving | /Python/BinaryTree/solution/invert.py | 1,025 | 4.125 | 4 | '''Invert a binary tree.'''
import __init__
from binarytree import BinaryTree
from treenode import TreeNode
from util.btutil import BinaryTreeUtil
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Invert:
... |
1d2132b560e493b2d001cea3c158580f31730080 | pravsp/problem_solving | /Python/TrappingRainWater/TrapRainWater.py | 969 | 4.03125 | 4 | """Solution to trap the rain water."""
"""
Problem:
=======
Given n Non-negative integers representing an elevation map where the width of
each bar is 1, compute how much water it is able to trap after raining
"""
class TrapRainWater:
def trap(self, height):
left_hieghest = 0
right_hieghest = 0
... |
dd844a663563586ac649ede13dfe67b7472bbdba | pravsp/problem_solving | /Python/BinaryTree/solution/__init__.py | 654 | 3.6875 | 4 | import os
import sys
def AddSysPath(new_path):
""" AddSysPath(new_path): adds a directory to python's sys.path
Does not add the directory if it doesnt exists or if its already on
sys.path. Return 1 if OK, -1 if new_path doesnt exists, 0 if it was already
on sys.path
"""
# Avoid adding non exi... |
6d6bbd9a42a4e427aae9db99827299d396363b83 | pravsp/problem_solving | /Python/BinaryTree/util/btutil.py | 518 | 3.765625 | 4 | """Binary Tree util."""
from binarytree import BinaryTree
class BinaryTreeUtil:
def constructBinaryTree(self, btree: BinaryTree):
"""Construct the binary tree based on user input.
:param btree: Binary tree on which new nodes to be added
:type btree: BinaryTree
"""
while Tru... |
42b8d9a128a7a5345ba2d1fd820489f4a7d13f27 | BruceWang94/COMP9021-17S1 | /Assignment/Assignment_1/superpower.py | 2,245 | 3.6875 | 4 |
import sys
try:
superpower = input('Please input the heroes\' powers: ')
superpower = superpower.split(' ')
for i in range(len(superpower)):
if not int(superpower[i]):
raise ValueError
except ValueError:
print('Sorry, these are not valid power values.')
sys.exit()
try:
nb_... |
66409873b4b58ebc8cec53c0caecc03266efa3a8 | Arushi96/Python | /Recursions/multiply_rec.py | 124 | 3.96875 | 4 | def multiply(a,b):
m=0
if b == 1:
print a
return a
else:
m=a+ multiply(a,b-1)
print m
return m
multiply(6,3)
|
b6ff3bb38beaea248d13389d5246d449e8e8bf8a | Arushi96/Python | /Radical- Python Assignment Solutions/Loops and Conditions/Question 3.py | 367 | 4.15625 | 4 | #Assignment Questions
#Q: Write a program which calculates the summation of first N numbers except those which are divisible by 3 or 7.
n = int(input ("Enter the number till which you want to find summation: "))
s=0
i=0
while i<=n:
if (i%3==0)or(i%7==0):
#print(i)
i+=1
continue
else:
... |
069a8828e50772d06dacc74f25ec2a59ae4d4213 | songtoan0201/algorithm | /leetCode/digitTreeSum.py | 405 | 3.578125 | 4 | def digitTreeSum(t):
if not t:
return 0
stack = [(t, 0)]
sum = 0
while stack:
cur, v = stack.pop()
if cur.left or cur.right:
if cur.left:
stack.append((cur.left, cur.value + v * 10))
if cur.right:
stack.append((cur.right, cu... |
3f4c8365e98ee5b8558370e96d0a64ccdad2b1e2 | songtoan0201/algorithm | /leetCode/longestCommonPrefix.py | 460 | 4 | 4 | # Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
String sclicing
String1[3:12])
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
for i in range(len(strs) - 1):
... |
9c180882c5f24e44308eb281569ecc43556260f2 | AxisAngeles/election-analysis | /3-1-Student-Resources/07-Evr_HobbyBook-Dictionaries/Unsolved/HobbyBook_Unsolved.py | 490 | 3.53125 | 4 | # @TODO: Your code here
PetInfo = {
"name":"Puchy",
"age":8,
"hobby":["eating","walking","sleeping"],
"woke":{
"monday":"10am",
"tuesday":"9am",
"wednesday":"11am"
}
}
print(f'My pet´s name is {PetInfo["name"]} and he is {PetInfo["age"]} years old.')
print(f'My pet has {len... |
505449aa00c311562c2d9af0e9399f45d06476fd | kz-sera/python_study | /BMI.py | 455 | 4 | 4 | #BMI = 体重(kg) / 身長(m)^2
from decimal import Decimal as decimal
kg = float(input('あなたの体重を入力してください'))
height = (input('あなたの身長を入力してください'))
if '.' not in height:
height = int(height) / 100
elif '.' in height:
height = float(height)
print(kg)
print(height)
BMI = kg / (height ** 2)
BMI = decimal(BMI).quantize(deci... |
e59d24fe7367404e53d997df5af8ca9db84156f1 | kz-sera/python_study | /j_body_calculate.py | 2,601 | 3.890625 | 4 | from decimal import Decimal as decimal
def base_body_data():
while True:
try:
print('性別を入力してください')
gender = int(input('[0. 男性 1. 女性]'))
if gender != 0 and gender != 1:
print('適切な値を入力してください')
continue
break
except:
... |
35025370621c265eff6d02c68d4284525634f5e1 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/find_characters.py | 568 | 4.21875 | 4 | """
Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character.
Here's an example:
# input
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
# output
new_list = ['hello','world']
"""
def find_characters(lst... |
52469f19f3f2c6691408e89d341ea7041fa5a38c | mtjhartley/codingdojo | /dojoassignments/python/python_oop/car.py | 921 | 3.71875 | 4 | class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price > 10000:
self.tax = .15
else:
self.tax = .12
def displayAll(self):
print... |
ddef36fe897037d8094621e1a3bf6204cd34e334 | mtjhartley/codingdojo | /dojoassignments/python/python_oop/hospital.py | 1,896 | 3.53125 | 4 | import random
import itertools
id = 0
class Patient(object):
id_generator = itertools.count(1)
def __init__(self, name, allergies, bedNum=None):
self.id = next(self.id_generator)
self.name = name
self.allergies = allergies
self.bedNum = bedNum
class Hospital(object):
bed_n... |
ac0c500a62196c5bf29fe013f86a82946fdb65b2 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/list_example.py | 854 | 4.28125 | 4 | fruits = ['apple', 'banana', 'orange']
vegetables = ['corn', 'bok choy', 'lettuce']
fruits_and_vegetables = fruits + vegetables
print fruits_and_vegetables
salad = 3 * vegetables
print salad
print vegetables[0] #corn
print vegetables[1] #bok choy
print vegetables[2] #lettuce
vegetables.append('spinach')
print veget... |
3389a2cb84c667ada3e41ec096592cfdbf6c2e07 | mtjhartley/codingdojo | /dojoassignments/python/fundamentals/compare_array.py | 2,432 | 4.3125 | 4 | """
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two.
If both lists are identical print "The lists are the same".
If they are not identical print "The lists are not the same... |
cb31593423cb1972d4ab10cf798b4aeb70527719 | premraj234/CSPP-Project-001 | /tail.py | 1,610 | 4.0625 | 4 | """Implementing the tail shell command in python."""
"""The import statement the import sys imports the library sys from the module along with the functions and methods of the library system"""
import sys
"""... from the lib.helper module we are importing the built in functions tail and readfile of the lib-helper mod... |
9f0cc5968a6a9a9da8dbb826554c9ab15b7733ad | karybeca/Learning_Python | /Choosing a team.py | 1,332 | 4 | 4 | #!/bin/python3
from random import choice
players = []
#Here Should be a Loop!
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name of the Player:"))
pla... |
f0c2e0bd6418339b210f68efcf5f447e2baeea76 | ccarterlandis/mathproblems | /brownNumbers.py | 422 | 3.578125 | 4 | import math
allBrown = []
def brown(m,n):
brownMid = []
nResult = math.factorial(n) + 1
mResult = pow(m,2)
if mResult == nResult:
brownMid.append(m)
brownMid.append(n)
if brownMid:
allBrown.append(brownMid)
for x in range(100):
for y in range(100):
brown(x,y)
... |
20151461f8bfa4a1631fecd826518664bf00db41 | ccarterlandis/mathproblems | /primesBelow.py | 432 | 3.890625 | 4 | userInt = input("Pick a number. ")
counter, primality, lower = 0, 0, 0
primeList = []
for x in range(2, int(userInt)):
primality = 1
for y in range(2, x+1):
if (x % y == 0) & (x != y):
primality = 0
break
if (x == y) & (primality == 1):
print("{} is prime.".fo... |
ec6b49ccbfef3f26f082b17f4c6ea67e9e7c8611 | orlandod543/datalogger_filter | /pendrive.py | 1,649 | 3.609375 | 4 | __author__ = 'orlando'
import os
class pendrive():
filepath=''
def __init__(self,filepath):
self.filepath = filepath
def write_append(self,filename,data):
"""
method that append a string to a file
If there is an error, catches it and does nothing
Input: str filena... |
19aa6ef97da6fdbb4a2a11fd2e66060d8a04f72e | nmarriotti/PythonTutorials | /readfile.py | 659 | 4.125 | 4 | ################################################################################
# TITLE: Reading files in Python
# DESCRIPTION: Open a text file and read the contents of it.
################################################################################
def main():
# Call the openFile method and pass it F... |
6a6034e699003b4a4ab0f11f7b2a9e89f235dc92 | Eugene-Korneev/GB_01_Python_Basics | /lesson_03/task_01.py | 822 | 4.25 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def divide(number_1, number_2):
if number_2 == 0:
return None
return number_1 / number_2
# num_1 = input("Введите перво... |
3e38d9b9de1f9c09dfaea120317b09ff62e88bcf | Eugene-Korneev/GB_01_Python_Basics | /lesson_01/task_06.py | 1,534 | 3.84375 | 4 | # Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значения ... |
157c97530b288bb7fbee706fb0a71ef56a4dfaa4 | Eugene-Korneev/GB_01_Python_Basics | /lesson_05/task_02.py | 641 | 3.84375 | 4 | # Создать текстовый файл (не программно), сохранить в нем несколько строк,
# выполнить подсчет количества строк, количества слов в каждой строке.
import os
FILE_PATH = os.path.join(os.path.curdir, 'files', 'task_02.txt')
with open(FILE_PATH, 'r', encoding='utf-8') as f:
file_lines = f.readlines()
print(f"Количе... |
7b72749a9f1bbf33723e47ddd491529226a414d5 | Eugene-Korneev/GB_01_Python_Basics | /lesson_03/task_06.py | 1,205 | 4.4375 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в... |
1fa19b51df98ee3a68a0bf0838574d22a0cf39ba | Eugene-Korneev/GB_01_Python_Basics | /lesson_03/task_04.py | 1,152 | 3.75 | 4 | # Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
# Подсказка: попробуй... |
27307b91316cc3d130610aca1b0e3eecc6e74110 | longpdm-teko/project1 | /test intern 1.py | 4,142 | 3.640625 | 4 | class ChiTiet:
def __init__(self, name):
self.name = name
def get_price(self):
pass
def get_weight(self):
pass
def __repr__(self):
return "name: {0}, price: {1}, weight: {2} ".format(self.name, self.get_price(), self.get_weight())
class Chitietdon(ChiTiet):
def _... |
2ac21404da9fac2574459957e1252625ab9a6a9d | Ravi-Rsankar/datascience-base | /numpy/ndarray_basics_indexing.py | 1,995 | 3.921875 | 4 | import numpy as np
an_array = np.array([[3,33,333],[2,22,3]])
print("whole array ")
print(an_array)
print("elements ")
print(an_array[0,0])
print("fill the array with the given value")
ex1 = np.full((2,2), 9)
print(ex1)
print("create an array with ones in the diagonals")
ex2 = np.eye(2,2)
print(ex2)
print("create ... |
37caa40697854af77bae5e7e637f118d5b05918a | foreveryao/Leetcode | /leetcode/36/solution.py | 1,013 | 3.671875 | 4 | class Solution(object):
def isValidSudoku(self, board):
s=set()
list=board
for i in range(9):
for j in range(9):
if list[i][j] in s:
return False
if list[i][j]!='.':
s.add(... |
9ab7e4292c509b713daf778b97ad3f12433d6b9c | lasselb87/MC | /NeuralNet/NeuralNet_classification.py | 5,040 | 3.734375 | 4 | import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Give name to features and target
headers = ['age', 'sex','chest_pain','resting_blood_pressure',
'serum_cholestoral', 'fastin... |
63960b50812134ed7286b8288e51bbf90c46d011 | bovard/advent_of_code_2016 | /09/part_two.py | 859 | 3.859375 | 4 |
with open('input.txt') as f:
instructions = f.readlines()[0].strip()
def expand_string(string):
# base case
if string == '':
return 0
# find all the characters as the beginning of the string
chrs = 0
while chrs < len(string) and string[chrs] != '(':
chrs += 1
# if it's on... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.