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 |
|---|---|---|---|---|---|---|
c1d227e8cb67399a0457bb9b3a403d43f16febb3 | arielbendoy/python | /Pets.py | 179 | 4.15625 | 4 | Pets = ['Acey', 'Theodore', 'Fat-tail']
print('Enter a pet name: ')
name = input()
if name not in Pets:
print('Pet name not in list.')
else:
print(name + ' is in list.') |
d36fb6d2af48c2dda5c70dd434b96d03a9f87a32 | Sherlynchance/SherlynChance_ITP2017_ReviewFunction | /Exercise 6.py | 793 | 3.6875 | 4 | ADD, SUB, MUL, DIV = range(4)
def calculator (operation=ADD, output_format=float, *args):
result = args[0]
if len(args) < 2:
raise ValueError
for x in args[1:]:
if operation == ADD:
result += x
elif operation == SUB:
result -= x
elif operation == MUL:
... |
07f260a1465cb5877c9f7aead419eddcd2167ba7 | jbettaque/password-generator | /password-generator.py | 3,369 | 4.125 | 4 | import string
import random
import re
def request_len():
"""
Prompts the user for the password length and returns the length as an int or -1 if input was invalid
:rtype: int
"""
length = input("Type in your desired password length:\n")
# if the input cannot be converted to an integer, it th... |
39e4c560763e0e79ea9735fbd945467ca9b6754e | YiannisVasilas/Project | /p2_sol_genbank_file.py | 3,335 | 3.765625 | 4 | #!/usr/bin/env python3
"""
Author: Ioannis Vasials
Parsing, acc. numbers, organisms, seqs
"""
#imports
from sys import argv
from operator import itemgetter
#functions
def record_finder (lines):
""" take a list from first record in file
"""
record = []
for line in lines:
if not line.strip():
... |
18229511a38e304d0489a0d010ef1aa561c1efd0 | chrisyees/python-notes | /Projects/Func_Exercises/skyline.py | 379 | 3.859375 | 4 | def myfunc(my_string):
result = ""
for index, letter in enumerate(list(my_string)):
if index % 2 == 0:
result += (letter.lower())
else:
result += (letter.upper())
return result
# return "".join([letter.lower() if index % 2 == 0 else letter.upper() for index, lett... |
c48b8b4fb79c88e4990bd8fbb4aba0a1dc198cf3 | ellieleep/hackerrank | /resplit.py | 149 | 3.671875 | 4 | import re
s = input()
result = re.split(r'(^|,|\.)(\d*)', s)
for x in result:
if not x == '' and not x == ',' and not x == '.':
print(x) |
050bab261d6f9d502c796ea93e3052c081f1258c | ellieleep/hackerrank | /lists.py | 615 | 3.9375 | 4 | listObject = []
n = int(input())
for number in range(n):
command = list(x)
if command[0] == 'insert':
listObject.insert(int(command[1]), int(command[2]))
elif command[0] == 'print':
print(listObject)
elif command[0] == 'remove':
if int(command[1]) in listObject:
listO... |
8ec2891659570c07f8b9130cd18b8f01cc3d53a0 | ellieleep/hackerrank | /invalidregex.py | 235 | 3.71875 | 4 | import re
numRegex = int(input())
regexList = []
for x in range(numRegex):
regexList.append(input())
for regex in regexList:
try:
re.compile(regex)
print('True')
except Exception:
print('False')
|
f1d9667058f1fc7d1dfdf70c4bf7dad6bc195bf7 | ManSleen/Graphs | /projects/ancestor/ancestor.py | 2,980 | 4.15625 | 4 | from collections import deque
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
self.visited = set()
def __repr__(self):
for vertex in self.vertices:
return f"{vertex}"
def add_vertex(... |
7e999c2ddf89511d479e7ea71d76de9b6f717efb | Hyun-wook-Hong/For_TechInterview_Junior | /DataStructure/queue.py | 471 | 3.765625 | 4 | # 큐 구현을 위해 덱 모듈 import하여 사용 (list로 구현하는것 보다 5배정도 빠름)
# 데이터 선입선출(First in First Out) 자료구조로, 줄 서기와 같다.
from collections import deque
queue = deque()
queue.append(5)
queue.append(2)
queue.append(3)
queue.append(7)
queue.popleft()
queue.append(1)
queue.append(4)
queue.popleft()
print(queue) #먼저 들어온 순서대... |
0d01fd1017320f7266884ab3a3f0bfa8641a961f | jf-2020/chess | /chess_2.py | 15,186 | 3.671875 | 4 | # chess_2.py - this prgm will attempt to build the basic backbone
# to a chess game implemented via the pygame
# library.
#
# jf - 4/25
# --- Imports ---
import pygame
# debugging
from pprint import pprint
# --- Global Constants ---
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, ... |
e3760bd714d28c8b08cd6481cfe48ea3cfda0bff | dynamitechetan/Physical-Web-Prelims | /running_median.py | 959 | 4.0625 | 4 | """
Chetan Kaushik ( dynamitechetan@gmail.com | github.com/DynamiteChetan )
"""
def running_median(user_lst):
length = len(user_lst)
if length % 2 == 0:
# calculates median when number of elements in the list are even
print ((user_lst[(length // 2) - 1] + user_lst[length//2]) / 2)
else:
# calculates median... |
154465529088409fe56d1f90e82b654a866ed537 | joaompinto/kidsplay | /jumperball/simulation/world.py | 6,416 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@copyright:
(C) Copyright 2012, Open Source Game Seed <devs at osgameseed dot org>
@license:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, eith... |
f6a783e30b8f7e124ba62f4a11bc8743287e60ac | GitOnUp/ADACollateral | /boggle/trie.py | 1,713 | 3.921875 | 4 | class TrieNode(dict):
def __init__(self):
super(TrieNode, self).__init__()
self.isWord = False
class Iterator(object):
def __init__(self, parent):
self._parent = parent
self._node = parent._root
self._nodes = []
self._value = ''
def advance(self, char):
... |
085f9511c22d5c9ccc36f7d15931964bd83aeb06 | Defensiveacre2000/Credit-card-aunthentication | /Credit card aunthenticattion.py | 946 | 3.5625 | 4 | from tkinter import*
root = Tk()
root.title("Credit card aunthentication")
root.geometry("850x450")
root.configure(background = "yellow")
import random
from PIL import ImageTk , Image
credit_card = ImageTk.PhotoImage(Image.open("credit.jpg"))
pin_of_card = Entry(root , fg = "red")
pin_of_card.place(relx = ... |
9fb393bcc21e823f98b27244d94b0aa781649651 | sjwwjs/arts | /week1/review.py | 1,725 | 3.875 | 4 | Dataframe创建方式
1) 由数组列表组成的字典
data1 = {'four':np.arange(4,9), 'one':range(1,6), 'three':[3,4,5,6,7],'two':range(2,7)}
print('(1) 由列表组成的字典')
print(pd.DataFrame(data1, index=list('abcde')))
print('------------')
2) 由Series组成的字典
data2 = {'four':pd.Series(np.arange(4,9), index=list('abcde')),
'one':pd.Series(ra... |
5f5ec7b9a134c815559fffa458e7b39df4886ef2 | DJSanti/Rooms-2.0 | /rooms 2.0.py | 15,643 | 3.65625 | 4 | ###########################################################################################
# Names: Andre Aguillard, Samantha Santiago
# Date: 3/24/2017
# Description: Rooms 2.0, now with pictures!
###########################################################################################
from Tkinter import *
... |
6635b9b2744114746ca1e5992162291bb8b9b946 | sanjit961/Python-Code | /python/p_20_logical_operator.py | 671 | 4.34375 | 4 | #Logical Operator in Python:
#If applicant has high income AND good credit
#then he is eligible for loan
# Logical and operator ----> both condition should be true
# Logical or operator ----> at least one condition should be true.
# Logica not operator ----> it converses the value True ---> False, False ---> Tru... |
80e6cde8011efc47718bfba7869e30944a3cde3b | sanjit961/Python-Code | /python/p_03_type_conversion.py | 194 | 4.09375 | 4 | #Type Conversion >>>---->>>>
birth_year = input('Birth year: ')
print(type(birth_year)) #type of data function ---> type()
age = 2020 - int(birth_year)
print(type(age))
print(age)
|
0ac6446ca514c2308ac7db5a1db3f8ca268d44c6 | sanjit961/Python-Code | /python/p_13.Arithmetic_Operator.py | 647 | 4.6875 | 5 | #Arithmetic Operator in Python:
print(10 - 3) #Subtraction
print(10 + 4) #Addition
print( 10 / 5) #Division
print( 10 // 5) #This prints the Quotient with interger value only
print( 10 % 3) #This % (Modulo Operator) prints the remainder
print(10 * 5) #Mutltiplication operator * ("Asterisk")
print(1... |
4dc2212288fcda1d008a595fc33ff47ab6857ab2 | danluu/dump | /dasgupta/rosalind/hs.py | 2,046 | 3.859375 | 4 | def parent(i):
# print("p {}:{}".format(i, ((i+1) // 2) - 1))
return ((i+1) // 2) - 1
def children(i):
return [2*i + 1, 2*i + 2]
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def bubble_up(a, i):
# print(a)
while i > 0:
p = parent(i)
if a[p] < a[i]:
# prin... |
99cce567ebe1016b73d930b2a48dc33923604a7a | danluu/dump | /dasgupta/rosalind/par3.py | 1,040 | 3.6875 | 4 | def swap(arr, i, j):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
return arr
def rotate(arr, i, j, k):
tmp = arr[k]
arr[k] = arr[j]
arr[j] = arr[i]
arr[i] = tmp
return arr
def partition(arr):
low = 0
mid = 0
hgh = 1
while hgh < len(arr) - 1:
nxt = hgh + 1
... |
f4c66c7312983e0e669251890946b7d68c65f4fb | MrCQuinn/Homework-2014-15 | /CIS_211_CS_II/GUI turn in/flipper.py | 1,146 | 4.40625 | 4 | #Flippin' Cards program
#By Charlie Quinn
from tkinter import *
from random import randint
from CardLabel import *
side = ["back","front","blank"]
n = 0
a = 2
def flip():
"""
Function that runs when "Flip" button is pressed.
a is a value that starts at 0 and goes to 8 before going back to 0
w and n a... |
5154719e15bc8d70b5d1faf6eb4f8484955801ed | MrCQuinn/Homework-2014-15 | /CIS_210_CS_I/lab 4/Lab4-7.py | 779 | 4 | 4 | #Charlie Quinn if.py
#Check < in an 'if' statement
#use a 'while' loop to make testing easier
def take_float(prompt_message):
prompt = prompt_message + ' '
temp = input(prompt)
#get input from user
return float(temp)
do_again = 'y'
Z=0
C=0
B=0
A=0
S=0
while do_again =='y':
BMI = take_float("\... |
e4bc7b6b121c3119273fd3ba6f036e1f1642683d | MrCQuinn/Homework-2014-15 | /CIS_211_CS_II/BlackJack/Deck.py | 1,905 | 3.875 | 4 | #Charlie Quinn
#Deck class
from sys import argv
from Card import *
import random
class Deck(list):
"""
deck class, inherits from list class and constructor builds a list of
52 card objects. shuffle randomizes list, deal returns first n items, and
restore adds card items back into the list
"""
... |
788a7048bdd06001cce0cad9015db25647eda865 | MrCQuinn/Homework-2014-15 | /CIS_210_CS_I/lab 2/Lab2-4.py | 349 | 3.84375 | 4 | # by Charlie Quinn
# Lab2-2.py
def celsius_to_fahrenheit(celsius):
'''converts a given temperature in degrees celsius into degrees farenheit C100=F212, C34=F93.2, and C-40 = F-40 '''
fahrenheit = (celsius*1.8)+32
return fahrenheit
print(celsius_to_fahrenheit(100))
f = celsius_to_fahrenheit(34)
print(f)
... |
42d055881a04f5df384df72dcce42253e4466f40 | matibilkis/institute-gui-pyqt | /comanditos.py | 2,411 | 3.671875 | 4 | import sqlite3
class Tablota:
def __init__(self,db):
self.conn=sqlite3.connect(db)
self.cur=self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS cursosrainbow (id INTEGER PRIMARY KEY, curso text, teacher text, valor real, libro text, horario text)")
self.conn.commit()
... |
dc3f67c16338421eee39dd44dfa219138e7ac3fd | ricardo-fo/dicionario | /simple_tk_dict.py | 1,129 | 3.578125 | 4 | from tkinter import *
class Application:
def __init__(self, master=None):
self.font = ("Arial", "10")
self.widget1 = Frame(master)
self.widget1.pack()
self.msg = Label(self.widget1, text="Buscar")
self.msg.pack()
self.caixa = Entry(self.widget1, bd=7)
self.caixa.pack()
self.change_text = Button(se... |
7e301925699905d79d42759b89561270b34051e5 | geekskool/lispinterpretor | /Interpretor.py | 2,086 | 3.625 | 4 | import math
import operator as op
from Parser import parser
env = {'+':op.add, '-':op.sub, '*':op.mul, '/':op.floordiv, '%':op.mod,
'>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '==':op.eq,
'abs': abs,
'append': op.add,
#'apply': apply,
'begin': lambda *x: x[-1],
... |
c06e676609489425c5f00e15778a2acc831e37cf | Dvshah13/Machine-and-Deep-Learning-Code-Notes | /data_munging_basics-categorical.py | 1,701 | 4.28125 | 4 | ## You'll be working often with categorical data. A plus point is the values are Booleans, they can be seen as the presence or absence of a feature or on the other side the probability of a feature having an exhibit (has displayed, has not displayed). Since many ML algos don't allow the input to be categorical, boole... |
0dccd749805be53fa3f388a8377f9214e24e8c4e | Dvshah13/Machine-and-Deep-Learning-Code-Notes | /data_munging_basics_text.py | 6,408 | 3.546875 | 4 | ## Data muning basics with text data, using the 20 newsgroup dataset
from sklearn.datasets import fetch_20newsgroups ## this automatically downloads the dataset and places it in a default directory
categories = ['sci.med', 'sci.space']
twenty_sci_news = fetch_20newsgroups(categories=categories)
# You can now query the ... |
74dc10369d6fe7b58686918681963d30ad52d1e7 | Dvshah13/Machine-and-Deep-Learning-Code-Notes | /classification_tensorflow.py | 4,430 | 4.21875 | 4 | # Regression is to predict a continuous value, it's great to predict a house price, speed of a car, etc. While classification is a method to tell if something is different from something else. Whether something is a dog, cat, cow, etc. Regression problems will only output one result, while classification problems wi... |
11dba6eaf2ee85ca93c4e6a5a460f83691e7a564 | Dvshah13/Machine-and-Deep-Learning-Code-Notes | /data_munging_basics-loading-data.py | 3,363 | 4 | 4 | import pandas as pd
## Loading file into pandas DataFrame
df = pd.read_csv('Data Sets for Code/istanbul_market_data.csv', sep=',', decimal='.')
## Printing head and tail
print df.head(5)
print df.tail(5)
## Printing columns
cols = df.columns.values.tolist()
print cols
## Get specific column, in a pandas series
Y = ... |
93523f5d2ccfc1cbab10b776913a76ed6703460d | bharathi2606/codekata | /fact.py | 71 | 3.53125 | 4 | n=int(input())
fact=1
for i in range (n,1,-1):
fact=fact*i
print fact
|
e35dc3be29623ef16b59a25d6916233d644a1d86 | bharathi2606/codekata | /num.py | 119 | 3.71875 | 4 | n=int(raw_input());
if(n>0):
print " positive number";
elif(n==0):
print " zero";
else:
print "negative number";
|
1371b8e6def4f10ab84688066d0d1bd8b962c104 | RajatC13/Cracking-The-Coding-Interview | /Arrays and Strings/1_2.py | 236 | 3.578125 | 4 | def check_permutation(s1, s2):
if len(s1) != len(s2):
return('False')
sa = s1.split().sort()
sb = s2.split().sort()
return(sa == sb)
if __name__ == "__main__":
print(check_permutation("assign", "ssgain"))
|
4d40af2a0dff893117af973d17d8548c3bc51b8c | Giuzzilla/advent-of-code-2019 | /day-04/day-4.py | 883 | 3.578125 | 4 | #https://adventofcode.com/2019/day/4
from collections import Counter
def both_stars(psw_range, n_star):
matching = 0
for psw in range(psw_range[0], psw_range[1]):
exist_double = False
increasing = int(''.join(sorted([i for i in str(psw)]))) == psw
if not increasing:
continu... |
4e6e82ab25899111dfd6cd26a39eb210d3b032b7 | pandeyroshan/Tkinter-Work | /register_login.py | 6,418 | 3.6875 | 4 | from tkinter import *
import sqlite3
from tkinter import messagebox
root=Tk()
def registerRoot():
def resetRegister():
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
e4.delete(0,END)
def isEmpty(text):
if not text:
return 0
else:
return 1
def submit():
name=e1.get()
uname=e2.get()
pwd=e3.... |
aac50fb75ffe2aed9e5f328216609f6b2e308336 | arthurma2001/sci-testing | /btask2/points2affine.py | 691 | 3.671875 | 4 | # Continuing from Required Task 3 above,
# create a Python function that will find the affine transformation between two sets of 2D or 3D correspondence points.
# The affine transformation is a linear transformation and translation that can be expressed in a single matrix,
# 3x3 in the 2D case and 4x4 in the 3D case. S... |
662859fa8f3b2c7613b093a1eb2bae21b4a44b07 | stevenfisher22/python-exercises | /Homework 13 Nov 2018/13-nov-2018.py | 447 | 4 | 4 | # input()
# name = input('Tell me your name ')
# age = int(input('What is your age? '))
# if age >= 21:
# print('You are old.')
# elif age < 18:
# print('Why are you here?')
# else:
# print('You are still too young.')
# count = 0
# while count < 10:
# count += 1
# print("The count is", count)
# ... |
b4a49e0d08e0e8e0710f3014e2ccb28b6d9017e9 | stevenfisher22/python-exercises | /Homework 14 Nov 2018/guess-a-number.py | 1,645 | 4.125 | 4 | # STEP 1: GUESS A NUMBER
# secret_number = 2
# answer = 0
# while answer != secret_number:
# answer = int(input('I\'m thinking of a number between 1 and 10. What\'s the number? '))
# if answer != secret_number:
# print('Nope, try again ')
# print('You win!')
# STEP 2: GIVE A HIGH-LOW HINT
# secret_n... |
856d857096b1e3943c4fabb8e108b988de328a95 | rpolishetty/FarmersMarketRegister | /dataload/load_data.py | 661 | 3.65625 | 4 | '''
This Module loads the items to dictionary
It creates a dictionary items_list, reads the items/products from JSON file and load into dictionary
Written by Rohith K Polishetty
'''
import json
def load_items ():
try:
with open("./data/item.json", 'rb') as inputFile:
items_list... |
1a568b3702be13bf65d321e4d7d2a1e3559bfae1 | CodecoolGlobal/ideabank-rpajdak | /ideabank.py | 1,186 | 3.671875 | 4 | import sys
data = sys.argv[1:]
data = str(data)[1:][:-1]
arg = data
ideas = []
numer= sys.argv
print(numer[2])
def display_ideas():
file = open("ideas.txt", "r")
content =file.read()
print(content)
file.close()
def idea_bank():
i = 0
while i == 0:
new_idea = input("What is your new idea?... |
c7fbe8cb18637905db00b918b3c56f09532d0a72 | mrajancsr/Algorithms | /unittests/test_sum_pytest.py | 429 | 4.0625 | 4 | def test_sum():
"""tests if sum of numbers 1,2,3 is 6"""
assert sum([1,2,3]) == 6, "should be 6"
def test_sum_tuple():
assert sum((1,2,3)) == 6, "should be 6"
# Notice compared to test_sum_unittest.py which uses
# the unittest test runner, we convert test sum into
# classes and test it. using pytest, ... |
af79ef5d8da610655bfbece3fe6e44229d90536b | mrajancsr/Algorithms | /Home/python/lib/sort_search/sort_search.py | 3,215 | 4.21875 | 4 | # Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if th... |
44c331a5924ed2b8552ef73c275344f11970a32e | lvlFarrukh/Python-Work | /Core_python/Assignments/Assignment 1.py | 1,124 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
a = int(input("Enter 1st value :"))
b = int(input("Enter 2nd value :"))
c = a+b
print(c)
# In[2]:
a = ("MuhammadAsad , Roll#PY02860")
a
# In[3]:
import math
radius = float(input("Plaese enter the radius of the circle:"))
area = math.pi * radius * radius
print (... |
42d53ad1819b3745e98c845bdaa402b98e1566ca | nidhim12/DataStructuresAnd-Algorithms | /linked_list.py | 1,797 | 3.84375 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = Node()
def append(self, data):
new_node = Node(data)
current = self.head
while current.next!=None:
curren... |
cdfd4dc7fd79795b8371ebe9b9c788f2da1b6a54 | mrStasSmirnoff/Coding | /Hackerrank_Coding/Day_27_Unittests/test_circle_area.py | 725 | 3.96875 | 4 | # Write unit test
import unittest
from math import pi
from circles import circle_area
# Create a class that is a subclass of the test case class of the unittest module
class TestCircleArea(unittest.TestCase):
def test_area(self):
# Test areas when radius >= 0
self.assertAlmostEqual(circle_area(1), pi)
self.... |
ec2e9b9ffa1d0d4837f23698bd5bb2c024740e6f | Mohan-Zhang-u/From_UofT | /python_class_proj/assignment2/modified assignment2.1/solver.py | 3,691 | 4.1875 | 4 | # Assignment 2 - Puzzle Game
#
# CSC148 Fall 2015, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
"""This module contains functions responsible for solving a puzzle.
This module can be used to take a puzzle and generate one or all
possible solutions. It can also generate ... |
60d45067426464abb0f20b20a665dc3d6741b1a5 | Mohan-Zhang-u/From_UofT | /csc148/pycharm/csc148/labs/lab5/nested.py | 2,226 | 4.15625 | 4 | def nested_max(obj):
"""Return the maximum item stored in <obj>.
You may assume all the items are positive, and calling
nested_max on an empty list returns 0.
@type obj: int | list
@rtype: int
>>> nested_max(17)
17
>>> nested_max([1, 2, [1, 2, [3], 4, 5], 4])
5
>>> nested_max(... |
626b0404f2a8d9911e266ca01a8829528b26a142 | Mohan-Zhang-u/From_UofT | /csc148/pycharm/csc148/labs/lab8/bst.py | 9,899 | 4.40625 | 4 | class BinarySearchTree:
"""Binary Search Tree class.
This class represents a binary tree satisfying the Binary Search Tree
property: for every node, its value is >= all items stored in its left
subtree, and < all items stored in its right subtree.
"""
# === Private Attributes ===
# @type _... |
5e4f80dfecd0f8e128d44c8d76d1b9239459c86f | Mohan-Zhang-u/From_UofT | /csc148/pycharm/csc148/exercises/ex2/chain_test.py | 1,333 | 3.703125 | 4 | # Exercise 2 - A Chain of People
#
# CSC148 Fall 2015, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
"""Exercise 2, Task 2 TESTS.
Warning: This is an extremely incomplete set of tests!
Add your own to practice writing tests,
and to be confident your code is corr... |
6c0caec4dfcdddf5ede5715ebe01b1ac57042415 | mis700000/dawat | /floor.py | 229 | 3.578125 | 4 | #This method returns largest integer not greater than x.
import math
print "math.floor(-45.17) : ",math.floor(-45.17)
print "math.floor(100.12) : ", math.floor(100.12)
print "math.floor(100.72) : ", math.floor(100.72)
|
3224271a2814833baf271bcdda5ba615a3d29d8c | mis700000/dawat | /ifelse.py | 134 | 3.5625 | 4 | i=100
if i==100:
print "true"
else:
print "false"
x=200
if x==i:
print "true"
else:
print "false"
|
3ed15b373ee7c5dca3ddfe526cefdada87ac7e74 | tsemayeo/Python | /dictionary.py | 190 | 3.84375 | 4 | ages = {'Meg':24, 'Tsemaye':17, 'Caroline':19, 'Matt':29}
ages['Caroline'] = 20
ages['Carly'] = 16
for name in ages:
x = ages[name]
ages[name] = x + 1
print(x)
print(ages)
|
d67afd0c093187385a6c3c0a3f6620be5c019cd0 | tsemayeo/Python | /Twitter/tweetWordCloud.py | 765 | 3.65625 | 4 | '''
In this project, you will visualize the feelings and language used in a set of
Tweets. This starter code loads the appropriate libraries and the Twitter data you'll
need!
'''
import json
from textblob import TextBlob
from wordcloud import WordCloud
import matplotlib.pyplot as plt
#Get the JSON data
tweetFile = op... |
44301a75985fc05337dc58a0f2523e0bf81edb6f | tsemayeo/Python | /calculateTotal/agesAverage.py | 155 | 3.9375 | 4 | ages =[2, 13, 56, 78, 44, 27, 19, 11]
sum = 0
length = len(ages)
for number in range(len(ages)):
sum += ages[number]
average = sum/length
print(average)
|
e2cc53379ce0a067370cbc4f282ae85d8e37d6d6 | rodrigoferrazazevedo/dojo-python | /fruits.py | 546 | 3.75 | 4 | width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width,'Item',price_width, 'Price')
print '-' * width
print format % (item_width,'Apples',price_width,0.4)
print format % (item_width,'Pear... |
a284e5a510ad4f8bd72b38a8f64a4f92c0ac7252 | rodrigoferrazazevedo/dojo-python | /python-language/fibonacci/fibonacci.first.py | 216 | 3.9375 | 4 | def fibonacci(N):
result = [0]
next_n = 1
while next_n <= N:
result.append(next_n)
next_n = sum(result[-2:])
return result
print(fibonacci(0))
print(fibonacci(1))
print(fibonacci(50)) |
7f8e319c1f184c2fa5e014745d8c59995420a418 | rodrigoferrazazevedo/dojo-python | /simple.for.4.py | 247 | 3.859375 | 4 | surnames = ['Rivest', 'Shamir', 'Adleman']
print("Starting from 0")
for position, surname in enumerate(surnames):
print(position, surname)
print("Starting from 1")
for position, surname in enumerate(surnames, 1):
print(position, surname)
|
83b14bae7ac3ecb84638a994282a923fbfb4be91 | webclinic017/pyrh_redesign | /exceptions.py | 3,534 | 3.5625 | 4 | class OrderCancellationError(Exception):
"""An exception raised when a user tries to cancel an order in one of the following states:
* Already executed
* Already cancelled
"""
def __init__(self, error):
"""Creates a new OrderCancellationError.
Args:
error: an er... |
c4d51ddb61955c55a10ffbe79c83cce74ba0ebae | mostwelcome/python-dsa | /search/binary_search.py | 548 | 3.859375 | 4 | def binary_search(numbers_list,find):
left_index = 0
right_index = len(numbers_list)-1
while left_index<= right_index:
mid_index = (left_index+right_index)//2
mid_element = numbers_list[mid_index]
if mid_element == find:
return mid_index
elif mid_element > find:... |
94e3c4bc19f740a0e25b35c590e495184ccf848d | subakutty/char | /count.py | 105 | 3.625 | 4 | input_string=input()
count=0:
for c in input_string
if c.isspace()!=true:
count=count+1:
print(count)
|
d11a8e8ef17be4c8671bc9b39fa3f3d6398f492d | dhrp/dotTwitter | /workers/testwriter.py | 181 | 3.890625 | 4 | #!/usr/bin/env python
from datetime import datetime
now = str(datetime.now())
#print now
with open("output.txt", "a") as myfile:
myfile.write(now + " appended text \n")
|
1d192bc99cfe895165ad4190f538aef8e10aa8eb | spatel78745/python | /widgets.py | 656 | 3.578125 | 4 | from tkinter import *
from tkinter import ttk
#
# Frames
#
root = Tk()
frame = ttk.Frame(root)
frame.grid()
# see how a tuple is used to pass multiple figures
# (left, top, right, bottom)
# (all the way around)
# (horizontal, vertical)
frame['padding'] = (5, 10)
frame['borderwidth'] = 20
frame['relief'] = 'sunken'
#... |
239c903dca8d01bd0b2b09d07965ed766ae8b9ac | spatel78745/python | /lister.py | 1,232 | 3.71875 | 4 | class ListInstance:
"""
Mix-in class that provides a formatted print() or str() of
instances via inheritance of __str__, coded here; displays
instance attrs only; self is the instance of lowest class;
uses __X names to avoid clashing with client's attrs
"""
def __str__(self):
return ... |
ad8d93648cf1d21e32d18c7391770bbdb546efe3 | KuDikan/ustc-yjs-course | /models.py | 1,476 | 3.5625 | 4 | from collections import namedtuple
import pickle
file_name = "data.pickle"
Class = namedtuple("Class", ["location", "time"])
class Data:
def __init__(self):
self.all_courses = []
def save(self):
with open(file_name, "wb") as f:
pickle.dump(self.all_courses, f)
def load(self... |
d5c832a2ba77400e8e186b06555de535a41bb180 | siwoo281/python-study | /8day.py | 326 | 3.9375 | 4 | a = int(input("키를 입력하세요."))/100
b = int(input("몸무게를 입력하세요."))
bmi = b / ( a * a )
if bmi >= 25:
print("비만입니다.")
elif bmi >=23 and bmi<25:
print("과체중입니다.")
elif bmi >= 18.5 and bmi < 23:
print("정상체중입니다.")
else:
print("저체중입니다.") |
4c47d564c1c2a15edefb3e145ee5176572f50af3 | chasingegg/Data_Science | /CS109/hw/hw1/hw1_1.py | 3,211 | 3.671875 | 4 | #!/Users/dimon//anaconda2/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import requests
import StringIO
import zipfile
import scipy.stats
#extract all the text files from the web
#the zipfile model can create, read, write, append and list ZIP files
def getZ... |
3f0b740dc0a0d881af1346b6064f498e84f5f984 | servesh-chaturvedi/FunGames | /Rock, Paper, Scissors/Rock Paper Scissors.py | 1,003 | 4.1875 | 4 | import random
import time
options={1:"rock", 2:"paper", 3: "scissors"} #build list
try:
again="y"
while(again == "y"):
player=int(input("Enter:\n 1 for Rock\n 2 for Paper\n 3 for Scissors\n")) #take player input
print("You entered:", options[player])
comp=random.randint (1,... |
cc2c21b947fef4e84486c80eeb9207b54290505c | Ken-Alviola/python-exercises | /data_types_and_variables.py | 2,349 | 3.84375 | 4 | '''You have rented some movies for your kids: The little mermaid (for 3 days), Brother Bear (for 5 days, they love it),
and Hercules (1 day, you don't know yet if they're going to like it). If price for a movie per day is 3 dollars, how much will you have to pay?
'''
little_mermaid = 3
brother_bear = 5
Hercules = 1
pr... |
e6a9b58ebce9dd79b0c8a9e83ba451c51ccb9d8d | wesbasinger/aggregate-job-labor | /main.py | 963 | 3.578125 | 4 | import csv
# returns a list of dictionaries from csv file
def reader(fref):
rows = []
with open(fref) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
rows.append(row)
return rows
def filter_by_job(rows, job):
result = []
for row in rows:
... |
171cda2c1a05a95284179ceac0843d8248210a7f | hunterkepley/beautifulsoup-python3-tutorial | /multiple_sites.py | 1,719 | 4 | 4 | # This is an updated guide for Python 3.x from
# https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe
# Python 3 had urllib2 moved into several different modules
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
# for exporting as a csv
import csv
from ... |
2b73c68d6351727e559a6aaf0d320213a7fc327b | jnr-stickman33/Rock_Paper_Scissors_Lizard_Spock | /Rock_Paper_Scissors_Lizard_Spock.py | 3,543 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 11:08:13 2019
@author: derick
"""
import random
import time
moves = ["rock", "paper", "scissors", "lizard", "spock"]
def print_pause(text):
print(text)
time.sleep(1)
class Player:
def move(self):
return "rock"
moving... |
223608bba840a65ed2c953ede96c797f4ad9cd63 | SiddhartLapsiwala/Software_Testing_Assign2 | /TestTriangle.py | 1,990 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from Triangle import classifyTriangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html ha... |
f2f9f6491d3b2a681f61d0743667e7747863c270 | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise09/Tehtävä_L09T04.py | 486 | 4.09375 | 4 | etunimi = list(input("Kirjoita etunimesi "))
sukunimi = (input("Kirjoita sukunimesi "))
etunimi_list=[]
sukunimi_list=[]
etunimi_list.append(etunimi)
sukunimi_list.append(sukunimi)
ensimmäinen_krijain_lista=[]
ensimmäinen_kirjain= etunimi[0]
for etunimi in etunimi_list:
for char in etunimi:
ensimmäinen_kri... |
423843ed8f1ddfb604958138453d278db7a78464 | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise08/Tehtävä_L08T02.py | 167 | 4.09375 | 4 | number_list=[]
for i in range(3):
print(("please write one number"))
item=int(input())
number_list.append(item)
number_list.sort()
print(number_list[-1])
|
0bf34cfec95bf6ab35d4c1b80ec42ea73dfb61ef | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /examples/13-collections/set.py | 1,047 | 4.28125 | 4 | # declare set of names and print
nameset = {"Joe", "Sally", "Liam", "Robert", "Emma", "Isabella"}
print("Contents of nameset is: ", nameset)
# print contents of the set in for loop
for name in nameset:
print(name)
# check length of the set
print("Length of the set is: ", len(nameset))
# check if certain item is ... |
3f67cde4c53380cef68bcef4266939b647877e73 | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise07/Tehtävä_L07T03.py | 162 | 3.8125 | 4 | kysymys1=input("Enter a number: ")
kysymys2= input("Enter another number: ")
number1=int(kysymys1)
number2=int(kysymys2)
print(int(kysymys2) + (int(kysymys1)))
|
630365527b732db3247c863cac1a4a5a78f45c1d | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise11/Tehtävä_L11T02.py | 280 | 3.953125 | 4 | kysymys=input("Muutetaanko farenheitit celsiuksiksi vai celsiu-asteet fahrenheitiksi?")
asteet=float(input("Kirjoita asteet"))
if kysymys == "fahrenheitit celsiuksiksi":
celsius=(asteet-32)*5/9
print(celsius)
else:
fahrenheit=(asteet* 9/5) + 32
print(fahrenheit) |
c4cf9a9f53c34378bb0d0c29ecb5d7930cae1f45 | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise15/Tehtävä_L15T01.py | 682 | 3.671875 | 4 | sukunimet = []
while True:
sukunimi = input("Kirjoita sukunimi: ")
if sukunimi == "":
break
sukunimet.append(sukunimi)
#print(sukunimet)
filename = "sukunimet.txt"
try:
for i, name in enumerate(sukunimet):
if i==0:
mode='w'
else:
mode='a'
with... |
25c16ff3deb8922b8c80f1cd92e067134e627c3f | tyerq/checkio | /most-wanted-letter.py | 975 | 4.21875 | 4 | def checkio(text):
text = text.lower()
max_freq = 0
max_letter = ''
for letter in text:
if letter.isalpha():
num = text.count(letter)
if num > max_freq or num == max_freq and letter < max_letter:
max_freq = num
max_letter = l... |
20553735dafbf6143a566df4c43a5c22e6c8e2bc | Raptuno/OP-Ch10 | /main.py | 324 | 3.6875 | 4 | def cambia_car(cadena):
charlist = list(cadena)
opt = list()
for idx, c in enumerate(charlist):
if idx == 0:
opt.append(cadena[len(cadena)-1])
else:
opt.append(charlist[idx-1])
res = str()
return res.join(opt)
print(cambia_car(input("Ingrese una palabra: "... |
01e23b7f0334b2666a5fdff99edb449c0d87c768 | IharLobach/bunch-profile-monitor | /server_modules/output_formatting.py | 197 | 3.5 | 4 | def length_output(val):
if isinstance(val, float) or isinstance(val, int):
return "{:.3f}".format(val)
if isinstance(val, str):
return val
else:
raise TypeError
|
e02f9db4512aab24cd8b6dbed60025e944154ee8 | a87150/learnpy | /starred_expression.py | 1,439 | 3.9375 | 4 | def one(a,*b):
# a是一个普通传入参数,*b是一个非关键字星号参数
print(b)
one(1,2,3,4,5,6)
#--------
def two(a=1,**b):
# a是一个普通关键字参数,**b是一个关键字双星号参数
print(b)
two(a=1,b=2,c=3,d=4,e=5,f=6)
def three(*x):
# 输出传入的第一个参数
print(x[0])
lst={"a","b","c","d"}
stri="www.pythontab.com"
three(stri,lst)
three(lst)
three(*stri)
d... |
49206f9b68c41e7d0d837db4d924cb38d4f7d742 | a87150/learnpy | /Extension_Dict.py | 900 | 4.03125 | 4 | class MyDict(dict):
def __setitem__(self, key, value): # 该函数不做改动,只是为了输出
print("setitem:", key, value, self)
super().__setitem__(key, value)
return
def __getitem__(self, item): # 主要技巧在该函数
print("getitem:", item, self)
# 基本思路: a[1][2]赋值时 需要先取出a[1] 然后给a[1]的[... |
be15196f5211d56597839832ca0cd855355ed4f2 | a87150/learnpy | /threading_Lock.py | 649 | 3.546875 | 4 | import time, threading
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
lock = threading.Lock()
def run_thread(n):
for i in range(100000):
# 先要获取锁:
lock.acquire()
try:
# 放心地改吧:
ch... |
8336c2ce6d87cc7718a3b2af83d3bba7d7ab82b5 | KhadarRashid/2905-60-Lab5 | /sql_db.py | 2,844 | 4.28125 | 4 | import sqlite3
db = 'records_db.sqlite'
def main():
# calling functions in the order they should execute
menu()
drop_table()
create_table()
data()
def menu():
# Creating a super simple menu
choice = input('\nPlease choose one of the following here \n 1 to add \n 2 to delete\n 3 to show ... |
0e08b6ae3a98d7fb95cb811b4b112e4da05f6a7e | timueh/Project-Euler | /006-difference-of-squares.py | 404 | 3.953125 | 4 | """
# ProjectEuler.net - Problem 6
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
def my_sum(n: int):
return -n * (n + 1) * (2 + n - 3*n**2) // 12
if __name__ == "__main__":
n = 100
print(f"The difference between the sum of the ... |
f7454863e8e37e2c965fd93aa4a33ff429505c93 | saviorabelo/dfa | /main_dfa.py | 827 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 11:35:37 2019
@author: Savio Lopes Rabelo
"""
#Example of a simple DFA
#DFA only accepts odd-sized string
states = {0, 1}
alphabet = {'a','b'}
function_transition = {
(0, 'a'): 1,
(0, 'b'): 1,
(1, 'a'): 0,
(1, 'b'): 0,
}
start_state = 0
accep... |
17c140abc4ca3fb4026d2ce4d7e00653b4c273de | lovingBlue/python | /matrix_transpose.py | 310 | 4 | 4 | # encoding=utf-8
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
# 第一种方法:列表推导式
matrix_transpose = [[row[i] for row in matrix] for i in range(4)]
print matrix_transpose
# 第二种方法:利用 zip 方法
matrix_transpose2 = list(zip(*matrix))
print matrix_transpose2
|
33e9012023bf07526b24c2dd7ded927699814e17 | rlucana-tip/PRELIM_SKILLS_EXAM | /test_temp.py | 848 | 3.734375 | 4 | from temperature import Temperature
import unittest
celsius_test1 = Temperature(celsius=20)
fahrenheit_test1 = Temperature(fahrenheit=50)
celsius_test2 = Temperature(celsius=1)
fahrenheit_test2 = Temperature(fahrenheit=100)
class temp_test(unittest.TestCase):
def test_celsius(self):
self.assertEqual(cel... |
dfa7cd5ada3958a7ce3c980c86503ef771f2a3da | abdulelahxd/pythonic-garage-band | /band/band.py | 2,191 | 3.71875 | 4 |
class Band():
members = []
def __init__(self, name, band):
self.band = band
self.name = name
self.__class__.members.append(self)
@staticmethod
def making_da_band():
return "It's time to make the band"
def __repr__(self):
return f'{self.name}'
@classme... |
424d1d4a40d34097b15d71f502fdf5979d95d6c7 | jamesmmatt/Projects | /Python/FizzBuzz.py | 570 | 4.375 | 4 | """
Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the
number and for for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print
"FizzBuzz"
"""
def fizzBuz(lastNumber):
numRange = range(1, (lastNumber + 1))
for num ... |
aecaa6d1bcaa0b07899f78d1fb4e2b8ad11b7db5 | siddhantkushwaha/DeepLearning-Assignment-01 | /Q1/q1.py | 2,946 | 3.75 | 4 | # %% all important libraries
import numpy as np
import matplotlib.pyplot as plt
# %%: declaring the data variables
data = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]])
X = data[:, :-1]
X = np.insert(X, 0, 1, axis=1)
Y_true = data[:, len(data) - 2:]
# %% initializing the weights randomly
W1 = np.random.r... |
76d8835fcd660c54b580f890f089958a76347c70 | castle9611/pythonML | /Python/recurse.py | 1,806 | 4 | 4 | ### 1. 递归过程
# def f(n):
# print(n,'------递------')
# if n>0:
# f(n-1) ## 它以下的代码暂时不会执行,被暂停阻塞,会向下开辟新的内存积压(栈)这些指令,等到阻塞放开,指令逐个执行(自上而下)
# print(n,'------归------')
# f(2)
### 2. 汉诺塔问题
# i = []
# def hanoi(n,x,y,z):
# if n==1:
# print(x,'-->',z) ####直接从x移动到z
# i.append(1... |
c3f232bd8eca6a756d27360a35a3b992acc75fb2 | CorSar5/Python-Exercises-115-World3 | /exercícios 72-115/ex089.py | 941 | 3.703125 | 4 | ficha = list()
while True:
nome = str(input('Nome: ')).strip()
nota1 = float(input('1ª Nota: '))
nota2 = float(input('2ª Nota: '))
media = (nota1 + nota2) / 2
ficha.append([nome, [nota1, nota2], media])
resp = str(input('Deseja continuar? [S/N] ')).strip().upper()
while resp != 'S' and resp ... |
7b3fc2d0aaab2d13adbbb9cd08e6ebc9fcccc28d | CorSar5/Python-Exercises-115-World3 | /exercícios 72-115/ex094.py | 1,084 | 3.5 | 4 | info = dict()
pes = list()
cp = 0
ti = 0
soma = 0
while True:
info.clear()
info['Nome'] = str(input('Nome: '))
info['Sexo'] = str(input('Sexo: [M/F] ')).strip().upper()
while info['Sexo'] not in 'MF':
info['Sexo'] = str(input('Sexo: [M/F] ')).strip().upper()
info['Idade'] = int(input('Idade:... |
cd8957a1694695733b8c9955aa54f6778b851db6 | CorSar5/Python-Exercises-115-World3 | /exercícios 72-115/ex103.py | 323 | 3.734375 | 4 | def funcao(jog='<desconhecido>', gol = 0):
print(f'O jogador {jog} fez {gol} golo(s) no campeonato.')
n = str(input('Nome do Jogador(a): '))
golos = str(input('Número de Golos: '))
if golos.isnumeric():
golos= int(golos)
else:
golos = 0
if n.strip()== '':
funcao(gol=golos)
else:
funcao(n, golo... |
74d2a8ed9e9faf60f3a69f362a7d0d3a8279a79d | francisco-igor/ifpi-ads-algoritmos2020 | /Fabio01_Parte01/f1_q21_temperatura_F.py | 198 | 3.953125 | 4 | # ENTRADA
temperatura1 = int(input('Temperatura em °F: '))
# PROCESSAMENTO
temperatura2 = (5 * temperatura1 - 160) / 9
# SAÍDA
print('A temperatura é de {:.1f} °C'.format(temperatura2)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.