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 |
|---|---|---|---|---|---|---|
fc4f16786713f1bcc5710e70591ee3093b10e2ec | djohnson67/sPython3rd | /math/io/strip_newline.py | 512 | 3.875 | 4 | #reads file oneline at a time and strips \n from it
def main():
infile = open('philosophers.txt','r')
#read 3 lines
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
#striup \n from each line
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
... |
e0c4c2ea0fd3efd52e138b92ec59d3e98c668ad9 | djohnson67/sPython3rd | /math/io/read_sales.py | 457 | 3.6875 | 4 | #reads values from sales.txt
def main():
#opemn sales
sales_file = open('sales.txt','r')
#read first line then test for empty string ''
line = sales_file.readline()
#continue until empty string
while line != '':
#convert to float
amount = float(line)
#prin... |
8958ab69502d9caf3f359c6e61d08bb2e032404c | djohnson67/sPython3rd | /Classes/account_test.py | 819 | 4 | 4 | import bankaccount
def main():
#get starting balan
start_balance = float(input('Enter starting balance: '))
#create account
savings = bankaccount.BankAccount(start_balance)
#deposit check
pay = float(input('How much were you paid this week? '))
print('I will deposit this into... |
3c666ec9ea6dc2435257a4ac90ea0a117e8f70a9 | djohnson67/sPython3rd | /loan_qual2.py | 443 | 4.0625 | 4 | #determine if bank customer qualifies for loan
min_salary = 30000.0
min_years = 2
#get customers annual salary
salary = float(input('Enter annual salary: '))
#get number of yars on job
years_on_job = int(input('Enter number of years employed: '))
#determine if customer qualifes
if salary >= min_salary and... |
6194f3cadc0f1cccb768aa17d523b8e8448cc9c8 | berkercaner/pythonTraining | /Chap12/copy-text.py | 710 | 3.78125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main():
infile = open('lines.txt', 'rt') #it's default rt but better to specify
outfile = open('lines-copy.txt', 'wt')
for line in infile:
print(line.rstrip(), file=outfile)
#outfile.writelines(line) ==> it'll work the same... |
0c9567b722911116f27ed17fbc1129e8d900342f | berkercaner/pythonTraining | /Chap08/dict.py | 1,565 | 4.25 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# it's like hash map in C
# each pair seperated by ',' and left of the pair is 'key'
# right of the pair is 'value'
def main():
#one way of creating dictionary
animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': ... |
c25f095d3e297cd7467d0beed372077007d86ab6 | berkercaner/pythonTraining | /Chap02/while.py | 384 | 3.671875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
words = ['one', 'two', 'three', 'four', 'five']
n = 0
while(n < 5):
print(words[n])
n += 1
while 1:
try:
val = int(input("Enter pass: "))
if val == 321332:
print('successful')
break
print("try ... |
999462110e3248e304b4974f9d966ba5b0ff42bc | yuumi001/miniCTF2021_deploy | /crypto/history/source/chall.py | 3,546 | 3.703125 | 4 | from Crypto.Util.number import getRandomInteger
from string import *
import time
def stage1(): #caesar box
print('\n\n\n***\nFirst Stage: Written test')
intro = '\nGiven a ciphertext encrypted using the Roman method of cryptography...\n\n\n'
print(intro)
time.sleep(3)
# challenge
print('My c... |
ae6767f12a250449a4c1998b2c69058b9e90c5cd | Viniciusvaz77/Python-tests | /exs/fizzbuzz.py | 114 | 3.890625 | 4 | nmr= int(input("insira o número: "))
if nmr%5==0 and nmr%3==0:
print("FizzBuzz")
else:
print(nmr)
|
95cfff552392d91d7efa26b15beb7ce376547bad | hadesfranklyn/ProvaAb2EstruturaDeDadosPython | /Prova/q2.py | 1,002 | 3.703125 | 4 | class Pilha:
topo = None
tamanho = None
itens = None
def __init__(self,tamanho):
self.tamanho = tamanho
self.topo = 0
self.itens = [None] * tamanho
def estaVazia(self):
return True if self.topo == 0 else False
def estaCheia(self):
return True if ... |
49c2a767536d4af386dd3a35e8f0f59163659d93 | jocke45/adventofcode2020 | /day1/expense_report.py | 1,340 | 3.96875 | 4 | def expense_report(report, debug=False):
"""
Return the product of two integers that together add to 2020
Execution time: 0,02s
"""
report.sort(reverse=True)
for x in report:
for y in range(len(report) - 1, 0, -1):
# Iterate backwards. Since the list is sorted we might
... |
0b714eba32a384c37a3775bc0f208ee2289f6b70 | jocke45/adventofcode2020 | /day5/seat_finder.py | 1,600 | 3.84375 | 4 | def row_finder(boarding_pass, row_list):
"""
Find the correct row by recursing through a boarding pass' string
use the top half of the rows for F and bottom half for B
"""
if len(row_list) == 1:
row = row_list[0]
elif boarding_pass[0] == 'F':
row = row_finder(boarding_pass[1:], r... |
1931d2374059df352e19884dd37abcfcdeecb453 | quanglam2807/cs-160 | /chapter-3-problem-1.py | 246 | 3.828125 | 4 | # Quang Lam
def intpow(x, n):
if n == 0:
return 1
else:
return x * intpow(x, n - 1)
def main():
x = int(input("Enter x: "))
n = int(input("Enter n: "))
print(intpow(x, n))
if __name__ == "__main__":
main() |
c3e84cb63894cf3833da1350ea5bde5036dcac14 | quanglam2807/cs-160 | /binary-search.py | 2,121 | 3.9375 | 4 | # Quang Lam
class OrderedList(list):
def __init__(self,contents=[]):
super().__init__(contents)
self.sorted = False
def __iter__(self):
if not self.sorted:
self.sort()
self.sorted = True
return super().__iter__()
def binarySearch(self, l, r, item)... |
51cddfd4c599409a8da840342b8228b4d95eda8c | kacchan822/nlp100py2015 | /chapter1/section02.py | 463 | 3.5 | 4 | """
言語処理100本ノック 2015
http://www.cl.ecei.tohoku.ac.jp/nlp100/#ch1
第1章: 準備運動
02. 「パトカー」+「タクシー」=「パタトクカシーー」
「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.
"""
strings1 = 'パトカー'
strings2 = 'タクシー'
result_strings = ''.join([i+j for i,j in zip(strings1, strings2)])
print(result_strings) |
9a95a30df19a4e44d832394e8ad0f9cba941fe67 | jakedshaw/tictactoe | /player.py | 212 | 3.53125 | 4 | class Player:
"""Player Class"""
def __init__(self, name, tile, score):
"""initializes player class"""
self.name = name
self.tile = tile
self.score = score
def __str__(self):
return f'{self.name}'
|
8255173f44c84c0e835153098f8bcaa4293ca099 | iBug/pyGadgets | /object.py | 370 | 3.78125 | 4 | class Object:
"""
A simple Object class similar to JavaScript's "Object"
"""
def __init__(self):
self.__dict__['_Object__data'] = dict()
def __getattr__(self, attr):
try:
return self.__data[attr]
except KeyError:
return None
def __setattr__(self... |
973eb1247bc6f2172c1606219a8aff516fb41567 | earthobservations/wetterdienst | /wetterdienst/util/geo.py | 3,138 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2021, earthobservations developers.
# Distributed under the MIT License. See LICENSE for more info.
from typing import Tuple, Union
import numpy as np
import polars as pl
from sklearn.neighbors import BallTree
class Coordinates:
"""Class for storing and retrieving coo... |
88857ccbf8401936285a9aee2a842420dfdabc09 | nickzhq/leetcode-algorithm | /980. Unique Paths III.py | 1,485 | 3.5625 | 4 | # 980. Unique Paths III
# https://leetcode.com/problems/unique-paths-iii/
class Solution(object):
def uniquePathsIII(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
row, col = len(grid), len(grid[0])
# 迭代器,用来返回当前位置的上下左右四个方向且可访问的位置
def nei... |
f7ccd4b998572138d10fc5ac96fb12310341026f | nickzhq/leetcode-algorithm | /1314. Matrix Block Sum.py | 1,918 | 3.546875 | 4 | # 1314. Matrix Block Sum
# https://leetcode.com/problems/matrix-block-sum/
# https://leetcode.com/problems/matrix-block-sum/discuss/499970/Problem-explanation-in-Python-Step-by-Step-O(m*n)-98-speed-and-100-memory
class Solution(object):
def matrixBlockSum(self, mat, K):
"""
:type mat: List[List[int]... |
e203cabf7112e41dfaeef4ef7b775c575586f740 | nickzhq/leetcode-algorithm | /122. Best Time to Buy and Sell Stock II.py | 447 | 3.546875 | 4 | # 122. Best Time to Buy and Sell Stock II
#https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for idx in xrange( 1, len(prices) ):
i... |
0f63758468e28096b1ae65115a23577b611a119b | bssrdf/ands | /ands/algorithms/sorting/integer/radix_sort.py | 9,369 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 05/03/2022
Updated: 07/03/2022
# Description
## Short Description
Radix sort is a non-comparison sorting algorithm that uses the stable
counting sort as a subroutine. The stability of counting sort is essential for
ra... |
82c4d56cc267398e0365edf435b938aa67d5277d | bssrdf/ands | /ands/algorithms/dp/rod_cut.py | 7,047 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 30/08/2015
Updated: 07/03/2018
# Description
Given a rod of length u, and a table of prices pᵢ, for i = 0, 1, ..., where pᵢ
is the price for a rod of length i, determine the maximum revenue rᵤ obtainable
by cutting up ... |
90342388d68ad8d2c5df0015262c5c9d047361c7 | cyj907/snake | /Apple.py | 1,019 | 3.65625 | 4 | # -*- coding: cp936 -*-
#2016_6_27
#by cyj
from Const import *
import random
class Apple:
def __init__(self):
#self.x=random.randint(0,SCREEN_WITH-APPLE_WIDTH+1)
#self.y=random.randint(0,SCREEN_HEIGHT-APPLE_HEIGHT+1)
self.x = random.randint(0, Grid_X-1) * APPLE_WIDTH
self.y = ran... |
a7cb31e5a5fb69d44408740c9cb620d56c199ef3 | cyj907/snake | /old/Apple.py | 989 | 3.578125 | 4 | # -*- coding: cp936 -*-
#2016_6_22
#by zhs
from Const import *
import random
class Apple:
def __init__(self,pygame,screen,applePic):
self.pygame = pygame
self.screen = screen
self.x=random.randint(0,SCREEN_WITH-APPLE_WIDTH+1)
self.y=random.randint(0,SCREEN_HEIGHT-APPLE_... |
6023573a1cd2e9ec93af7bde69cc279781e8281a | sys-ryan/machine-learning-basic | /01. Data Preprocessing/01_Data_Preprocessing.py | 2,704 | 3.828125 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
x = dataset.iloc[:, :-1].values # [rows, columns]
y = dataset.iloc[:, -1].values
# Taking care of missing data - data preprocessing tools.
from sklearn.impute i... |
defaf80c7ae83d4a81d6eda52fbcb78e75a8eebc | liuhuijun11832/python-learning | /importandio.py | 2,692 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# 导入一个模块的某个方法,import *代表所有方法(但是_开头的名字不在此列),同时被导入模块中的可执行代码在第一次也会执行
from mynumbers import printme
import math
import pickle
import pprint
printme("哈哈哈哈哈哈")
"""dir函数可以找到模块内定义的所有名称,以一个字符串列表的形式返回,如果没有参数,那就是当前模块"""
print(dir())
"""当使用from package import item这种形式的时候,对应的item既可以是包里面的子模块(子包),或者包里面定义的其... |
49abc06f0104dcdcf9a949d040db84d2c98fde02 | liuhuijun11832/python-learning | /mythread.py | 1,722 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import time, threading
'''python的标准库内置了两个模块,_thread和threading,前者是低级模块,后者是高级模块,一般情况下,使用高级模块'''
def loop():
print('线程正在运行:{}'.format(threading.current_thread().name))
n = 0
while n < 5:
n += 1
print('线程 {} >>> {}'.format(threading.current_thread().name, n))
ti... |
ee4a2f8840f7f7471601eb338fc0197dddf36594 | char-n/python-cookbook-demo | /chapter-01/1.18-映射名称到序列元素.py | 577 | 4.09375 | 4 | #!usr/bin/env python
# encoding: utf-8
# @Author : niuzhifa 1944044667@qq.com
# @Time : 2018/2/24 20:28
# 命名元组
from collections import namedtuple
MyTuple = namedtuple('MyTuple', ['name', 'age'])
my_tuple = MyTuple('niuzhifa', '100')
print(my_tuple)
# 支持所有的普通元组操作
# 索引
print(len(my_tuple))
# 解压
name, age = my_tuple
pr... |
c6ca5bd01d03dcec7a9a68fb514ab269d2a93fe5 | Jularin/Codeforces-problems | /58A.py | 244 | 3.734375 | 4 | string = input()
List = ["h","e","l","l","o",]
counter = 0
for letter in List:
if string.find(letter)!=-1:
string = string[string.find(letter)+1:]
counter += 1
else:
counter-=1
if counter==5:
print("YES")
else:
print("NO") |
2c37670e2fd9f985c938dec3ff2aadc6e39febbb | Jularin/Codeforces-problems | /59A.py | 202 | 4.03125 | 4 | string = input()
up = 0
low = 0
for i in string:
if i.isupper():
up+=1
elif i.islower():
low+=1
if low>=up:
print(string.lower())
else:
print(string.upper())
|
3291814482c27d26ced5c20e783b4798a29db805 | Gusbell/CP3-Thitiwat-Srisawangpanyakul | /Exercise11_Thitiwat_S.py | 182 | 3.890625 | 4 | number = int(input("Number: "))
c = number
d = -1
for i in range(number):
c -= 1
d += 2
print(" "*(c) + "*"*(d))
#เป็นโจทย์ที่มันมาก
|
8f4b21a601c7e3a2da6c26971c7c7bb982d4a242 | hashncrash/IS211_Assignment13 | /recursion.py | 2,230 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 14 Assignment - Recursion"""
def fibonnaci(n):
"""Returns the nth element in the Fibonnaci sequence.
Args:
n (int): Number representing the nth element in a sequence.
Returns:
int: The number that is the given nth element in the fibonna... |
989886a9986ed963d661016e4d03f63c4cf93495 | mawrobel/database_test | /DB_Picle_test.py | 767 | 3.53125 | 4 | from initdata import db
import pickle
"i'm Pickling record from .txt file"
dbfile = open('people-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
"printing record in console"
dbfile = open('people-pickle', 'rb')
db = pickle.load(dbfile)
for key in db:
print(key, "=>\n", db[key])
dbfile.close()
"Make separat... |
7e50120d6e273dc64b440c847a7bfb4b2f8599da | PyladiesSthlm/study-group | /string_processing/elisabeth_anna.py | 1,377 | 4.34375 | 4 | #!/usr/bin/env python
import sys
import argparse
def palindrome_check(string_to_check):
letters_to_check = len(string_to_check)
if letters_to_check % 2 == 0:
letters_to_check = letters_to_check/2
else:
letters_to_check = (letters_to_check -1)/2
print letters_to_check
samma = 0
... |
7fa4bf9d6bda35cf52863bf075f0f5af79d6cc09 | nathanspang/spotifyClone | /main.py | 1,401 | 3.828125 | 4 | import datetime
from playlist import Playlist
from song import Song
nextAction = input(
'Welcome to Spotify, would like to create a new playlist (new) or exit (exit)?: ')
playlists = []
if nextAction.lower() == 'new':
songs = []
playlistName = input('What would you like to name your playlist? ')
pl... |
8d1de591706470db3bbcf26374ff958f393e85f7 | tungnc2012/learning-python | /if-else-elif.py | 275 | 4.21875 | 4 | name = input("Please enter your username ")
if len(name) <= 5:
print("Your name is too short.")
elif len(name) == 8:
# print("Your name is 8 characters.")
pass
elif len(name) >= 8:
print("Your name is 8 or more characters.")
else:
print("Your name is short.") |
9843199e0fa79cab66b2a51d5ced461e7adc385f | oneilk/data-structures | /python/queue.py | 468 | 3.6875 | 4 | from collections import deque
class Queue:
def __init__(self) -> None:
self.buffer = deque()
def enqueue(self, val):
self.buffer.appendleft(val)
def dequeue(self):
return self.buffer.pop()
def is_empty(self):
return len(self.buffer) == 0
def size(self):
... |
cf7d2340ccc1992e993c969f9be8adc88b2afd7f | rdr42/Artificial-Inteligence-CSCE-A405 | /Project/Assignment 1/MeetingSession/Node.py | 5,997 | 3.53125 | 4 | from Board import *
class Node:
def __init__(self):
self.parent = None
self.parentdirection = None
self.children = {} #Store node objects{up or left or down or right: node}
self.value = board #[0,1,2,3,4,4,5]
def populateChildren(self):
index = self.value.blank
if(index == 0):
if (sel... |
a990fb6d918b3f762ee78669ee18078b19853bb8 | rdr42/Artificial-Inteligence-CSCE-A405 | /Project/Assignment 3/Game/main.py | 10,105 | 3.921875 | 4 | # Assignment 3
# main.py
# EJ Rasmussen erasmussen3@alaska.edu
# Rafael Reis rrdosreis@alaska.edu
# Hunter Johnson huntergj2020@gmail.com
import math
import copy
from datetime import datetime
class Node():
def __init__(self):
self.children = {}
self.board = None
self.depth... |
58ccb45897ee8c15fa03151e021380635327c256 | rdr42/Artificial-Inteligence-CSCE-A405 | /Project/Assignment 1/Final Code/main.py | 1,955 | 4.09375 | 4 | from Heuristic import *
from Board import *
# This function accepts two 1d lists and will return true if the two lists have the same parity
def parity(start, end):
# Get parity of start state
startPairs = 0
for i in range(9):
for j in range(i+1, 9):
if start[i] > start[j] and start[i] and start[j]:
startPa... |
4f5802add04976a8c86e237e5792ebee29bbb08f | maxifo/posti_testit | /postitoimipaikka.py | 463 | 3.53125 | 4 | import urllib.request
import json
with urllib.request.urlopen('https://raw.githubusercontent.com/theikkila/postinumerot/master/postcode_map_light.json') as response:
data = response.read()
postinumerot = json.loads(data)
def main():
postinumero = (input("Kirjoita postinumero: "))
if postinumero in pos... |
ab716b0d941af3fbb5d0cb77e88c7f609a6bad2a | sekerez/Project-Euler | /Problem 7.py | 540 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 12:56:50 2020
@author: isakjones
"""
def find_nth_prime(n):
def is_prime(x, L = []):
"""
Classic function, but returns a list.
"""
if x in L:
return True
elif x == 1 or x % 2 == 0:
... |
68d2e8fa70e61ef9353974661bcb9df0823e1811 | mirokuxy/SFU_ACM_2016 | /oct29/F.py | 517 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
import math
def isPrim(n):
for i in xrange(2, int(math.sqrt(n)) ):
if n%i == 0:
return False
return True
def isCarm(n):
for i in xrange(2, n):
if pow(i, n, n) != i:
return False
return True
for line in sys.... |
7de4e99e276c3e0ba73fc82112b55f7ee8190d5c | ayazzy/Plotter | /searches.py | 1,673 | 4.1875 | 4 | '''
This module has two functions.
Linear Search --> does a linear search when given a collection and a target.
Binary Search --> does a binary search when given a collection and a target.
output for both functions are two element tuples.
Written by: Ayaz Vural
Student Number: 20105817
Date: March 22nd 2019
'''
def lin... |
2fd4e56f396cd5bc76e2ae42f9e166af2163720e | yi-ye-zhi-qiu/liamlab | /dsa_in_python/0826/ps2.py | 2,019 | 3.875 | 4 | import sys; print(sys.version)
'''
Remove all adjacent duplicates. Given a string S
of lowercase letters, a duplicated removal consists
of choosing two adjacent and equal letters
and removing them.
'''
def f(s: str) -> str:
l = []
for i in range(len(s)):
if i<len(s)-1 and s[i] == s[i+1]:
... |
3a07c999f55e027796c9e65625d5db3ab4c9024f | jake3991/mavsim_template_files | /mavsim_python/chap4/wind_simulation.py | 1,556 | 3.65625 | 4 | """
Class to determine wind velocity at any given moment,
calculates a steady wind speed and uses a stochastic
process to represent wind gusts. (Follows section 4.4 in uav book)
"""
import sys
sys.path.append('..')
import numpy as np
class wind_simulation:
def __init__(self, Ts):
# steady state wind define... |
22a8000dfe247162fd1ad7fc2a21190a2f9d0c32 | AsmaTouqir/TIC-TAC-TOE-GAME | /final1_projectlab.py | 4,005 | 3.765625 | 4 |
from tkinter import *
from tkinter import messagebox
import random as r
#add all main widgets for taking player information
def button(frame):#Function to define a button
Label(frame,text='Player 1 name:',font=('times 20 bold italic'),bg="#765751").grid(row=5,column=0) #label for planyer n... |
fdd3b067454c1c79902e5b55c924144ad1ddd2e7 | davideflo/Python_code | /StackExchangeClassifier.py | 3,183 | 3.65625 | 4 | # Stack Exchange Question Classifier
import pandas as pd
import numpy as np
import json
import codecs
def read_dataset(path):
with codecs.open(path, 'r', 'utf-8') as myFile:
content = myFile.read()
dataset = json.loads(content)
#dataset = pd.read_table(content)
return dataset
train = pd.read_table("in... |
fcccfab3841587604297a1e43f9ffb1d5710d3eb | Mohanibanez/Task-Generator | /app.py | 4,767 | 3.875 | 4 | #Importing Modules and the functions
#In line 11 you are making available the code you need to build web apps with flask.
#flask is the framework here(library), while Flask is a Python class datatype(specific class).
#In other words, Flask is the prototype used to create instances of web application or web application... |
71026e3df48bd93838388a0bfd170bd9a94a0a83 | AungTun1130/Daily-Planner-Assistant | /TkinterUI/Tkinter_calculatorUI.py | 3,913 | 4.09375 | 4 | from tkinter import *
root =Tk()
root.title("Simple Calculator")
number = Entry(root,width =35)
number.grid(row= 0,column =0,columnspan=3,padx = 10,pady=10)
math_func_type = ['add','subtract','multiply','divide']
def button_click(num):
#number.delete(0,END)
current = number.get()
number.delet... |
a4b22a4a32ffa1afb1508d232388d6bc759e0485 | avi651/PythonBasics | /ProgrammeWorkFlow/Tabs.py | 233 | 4.125 | 4 | name = input("Please enter your name: ")
age = int(input("Hi old are you, {0}? ".format(name))) #Adding type cast
print(age)
if age > 18:
print("You are old enough to vote")
else:
print("Please come back in {0}".format(18 - age)) |
8580b07e67a3498ed833fcf79689dd919aebe2b1 | avi651/PythonBasics | /HelloWorld/HelloWorld.py | 296 | 3.96875 | 4 | print("Hello World!")
print(1+2)
print(7+6)
print()
greeting = "Hello"
name = input("PlEASE ENTER YOUR NAME") #Its Like Scan f
print(greeting + " " + name)
splintString = "This string has been\nsplit over\nseveral\nlines"
print(splintString)
tabbedString = "1\t2\t3\t5\t6"
print(tabbedString)
|
9b2f359901f6a835563e878a9f103dec0b110a86 | nguiaSoren/Snake-game | /scoreboard.py | 1,123 | 4.3125 | 4 | from turtle import Turtle
FONT = ("Arial", 24, "normal")
#
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
# Set initials score to 0
self.score = 0
# Set colot to white
self.color("white")
# Hide the turtle, we wonly want to see the text
self... |
35f407f0a1398bd8588f0320bd6e63e79182eb66 | Yustynn/digital-world | /Past Exams/2016/Section C/QN7.py | 1,310 | 3.53125 | 4 | def maxProductThree(l):
'''
TEST CASE 1: 0 positive numbers
>>> maxProductThree([-5, -10, -12, -7])
-350
TEST CASE 2: 1 positive number
>>> maxProductThree([-5, 10, -12, -7])
840
TEST CASE 3: 2 positive numbers
>>> maxProductThree([-5, 10, -12, 7])
600
TE... |
61f811e7f51828634bbbecae0c29310d1018c579 | ruanmirandac/Python | /exercicios/ex005.py | 222 | 3.984375 | 4 | # Exercício Python #005 - Antecessor e Sucessor
print(40*'=')
num1 = int(input('Digite um número:'))
print(f'O antecessor do número {num1} é {num1-1}')
print(f'O sucessor do número {num1} é {num1+1}')
print(40*'=')
|
d9442feba85d179b29b482bd6e804ac30afb4c6d | manasbundele/computer-vision-projects | /modified-mnist/resnet_mnist.py | 5,003 | 4 | 4 | '''
By: Manas Bundele
Project Constraints:
The goal is to train a CNN to recognize images of digits from the MNIST dataset. This dataset consists of
gray level images of size 28x28. There is a standard partitioning of the dataset into training and testing.
The training has 60,000 examples and the testing has 10,000 ... |
a29cf36377da7f9ae513cd980c579aed1cd49ff1 | brianquinlan/learn-tensorflow | /positive-number-classifier/generatedata.py | 469 | 3.828125 | 4 | #!/usr/bin/env python3
"""Generate "data.csv", which is used as classifier training data.
The CSV file is formatted like:
value1,value2,positive
-3.12,4.23,True
-5,5,False
-4,-4.1,False
...
"""
import random
with open('data.csv', 'w') as f:
f.write('value1,value2,positive\n')
for _ in range(1000000):
... |
bf3b9963811de2b52415398c637f3c25f64c72b6 | NoValeria/organiser | /utility/note.py | 3,415 | 3.640625 | 4 | from exceptions import MyException
from utility.my_date import MyDate
from utility.my_time import MyTime
class Note(object):
"""класс описывает заметку(задание)"""
def __init__(self, start: MyTime = None, end: MyTime = None, date: MyDate = None, title: str = None, description: str = None, important: int = Non... |
c0157c828d7736f95776068bb06718c3a5005f1f | DAVIDnHANG/DS-Unit-3-Sprint-2-SQL-and-Databases | /module2-sql-for-analysis/eleaphantsql.py | 3,033 | 3.8125 | 4 | import psycopg2
#read docs use help()
#help(psycopg2.connect)
#setting up for psycopy2.connect
dbname = 'wbtaflae'
user = 'wbtaflae'
password = 'PrFRj3SJLlpPBhmG8I0SY3ogazL6bmGz'
host = 'salt.db.elephantsql.com'
rpg_conn = psycopg2.connect( dbname =dbname, user=user, password=password, host=host)
print... |
d088b276ca230b21476595bc9abc00086a211094 | pobingxiaoxiao/leopy | /leopy/algorithm/search.py | 477 | 3.953125 | 4 | '''
python implement of search algorithms.
'''
def binary_search(data, find):
'''
binary search of a sorted list.
'''
start = 0
stop = len(data)-1
while(stop>=start):
mid = int((start + stop)/2)
if(find == data[mid]):
print('the index is {}'.format(mid))
... |
6f15a358204db42647368f4b628e36ae08754e5d | yize11/suoxue | /python爬虫/05/requests_session.py | 903 | 3.5625 | 4 | import requests
# 创建session对象,支持跨请求访问
cus_session = requests.session()
url = 'https://passport.jiayuan.com/dologin.php?pre_url=http://www.jiayuan.com/usercp/'
formdata = {
'name': '18518753265',
'password': 'ljh123456',
'remem_pass': 'on',
'_s_x_id': '7a106b00170857e594da431080ae0761',
'ljg_login':... |
9f2629a5e6777831e577446199b8d78dee253b70 | gtenorio/Code-Eval-Challenges | /m_count_prime.py | 503 | 3.515625 | 4 | __author__ = 'Gio'
#Code Eval: Counting Primes
import sys
import math
def isPrime(ashton):
p = True
for j in range(2, int(math.sqrt(ashton))):
if (ashton % j == 0):
p = False
break
return(p)
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
a = ""
b = ""
c = 0
total = 0
temp = test.split(','... |
4ff70b598377f2c513acc184232346c497245da7 | kishoraen1/kishore-python | /Ex12.py | 275 | 3.84375 | 4 | x = float (input ("Enter 1st Number = "))
y = int (input ("Enter 2nd Number = "))
ch = input ('Enter a Char = ') [0]
result = eval(input('Enter An Expression = '))
print(type(x))
print(type(y))
print(type(ch))
print (type(result))
z = x+y
print (z)
print(ch)
print (result)
|
3256df7c7a7003cb7ffe86abd873c0b6cc65b6bf | kishoraen1/kishore-python | /ifstatements.py | 319 | 4 | 4 | import math
x = int(input('Enter First Number of your choice = '))
y = int(input('Enter Second Number of your choice = '))
z = int(input('Enter Third Number of your choice = '))
if (x > y) and (x >z) :
print('X is Greatest')
elif (y > x) and (y >z):
print('Y is Greatest')
else:
print ('Z is Greatest')
|
7df95e08944b6e7ce18ce4213d730e6861c37ddd | kishoraen1/kishore-python | /numpy_arrays_Operations.py | 342 | 3.734375 | 4 | from numpy import *
from array import *
# array
arr1 = array('i',[1,10,3,24,5])
arr2 = array('i',[1,2,3,4,5])
arr3 = array('i',[])
for e in range(0, len(arr1)):
arr3.append (arr1[e] + arr2[e])
print(arr3)
max = 0
for i in range(0,len(arr1)):
if max > arr1[i]:
continue
else:
max = arr1[i]... |
027440085636632a087c02a62ac9278ba94313cf | vuagieucot/pythoncorner | /Multi_Threading/threading1.py | 856 | 3.796875 | 4 | import threading
import time
class myThread(threading.Thread):
"""
Thread count down
"""
def __init__(self, threadId, name, count):
threading.Thread.__init__(self)
self._threadId = threadId
self._name = name
self._count = count
def run(self):
print('Starting... |
187aab7c76d32190b0ce030ad8487380bb435ab8 | vuagieucot/pythoncorner | /backtracking/sudoku_solver_base.py | 1,764 | 3.5 | 4 | from board import board
def solve(bo):
print_board(board)
print('='*25)
find = find_empty(bo)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if valid(bo, i, (row, col)):
bo[row][col] = i
if solve(bo):
return T... |
bb448e97ec6a500d46668660d1ee6007a4bfbd46 | kornel45/rocket_game | /text_styler.py | 1,905 | 3.671875 | 4 | from typing import Tuple, List
import pygame
def make_font(fonts: list, size: int) -> pygame.font.Font:
"""
Method responsible for making font of certain size. You can specify name of font, then it will
be searched in system fonts. If None then default font will be returned
:param fonts: list of font... |
4a1f6d688bff6f9fd75d547242a506ece1d4b22b | anshu3012/ENPM-661_Project-3_Phase_3-4_Group_38 | /Phase 3/Astar_rigid_nonholo.py | 14,872 | 3.546875 | 4 | # ENPM661
# Project 3 Phase 3
# Group 38
# ===== Libraries =====
import numpy as np
import cv2
import math
from math import pi
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.patches import Polygon
import time
# ===== User Inputs (Error-checking and robot dimensions) =====
print... |
b573b7b9a21a1d10bb188a792ed54a8c70726ffd | sca4cs/Data-Structures | /queue/queue.py | 517 | 3.6875 | 4 | import sys
sys.path.append('../linked_list')
from linked_list import LinkedList
class Queue:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def enqueue(self, item):
self.storage.add_to_tail(item)
self.size += 1
def dequeue(self):
if self.size > 0:
self.size -= 1
r... |
03b349b074f375a123a1dcb3446e13dee2276a79 | luzperdomo92/test_python | /for_loop.py | 101 | 3.5625 | 4 | prices =[10, 20, 20]
total = 0
for item in prices:
total += item
print("total {}".format(total))
|
ddfe13cbff04a326ed196b20beb8f1414364b086 | luzperdomo92/test_python | /hello.py | 209 | 4.25 | 4 | name = input("enter your name: ")
if len(name) < 3:
print("name must be al least 3 characters")
elif len(name) > 20:
print("name can be a maximun 50 characteres")
else:
print("name looks good!")
|
e0c9d64fc8ec7f496d330b1a54f415918ff9b176 | VakhoGeoLab/J_davalebebi | /Davaleba_3.py | 325 | 3.828125 | 4 |
def pyramid(number):
pyr_result = "a" * number
return pyr_result
def illuminati(number):
x = 0
space = 0
while x <= number:
space = int((number - x) / 2)
space_result = " " * space
print(space_result, pyramid(x))
x += 2
def main():
illuminati(14)
m... |
529d0a319ac6368dc8e5a8d3bf8b03aead86c409 | roadpilot/learning-python | /chap06/2-for.py | 148 | 3.875 | 4 | #!/usr/bin/env python3
animals = ('bear', 'bunny', 'swordfish', 'cat')
for pet in animals:
print(pet)
for pet in range(5):
print(pet) |
4263e428cb002dfcbae8d38c6be9e2c475805d53 | racheliWeiss/birthday-wishert | /main.py | 2,916 | 3.71875 | 4 | import smtplib
import pandas
import datetime as dt
import random
now = dt.datetime.now()
day = now.day
month = now.month
today = (month, day)
birthday = pandas.read_csv("birthdays.csv")
MY_EMAIL = "rhlywyyys@gmail.com"
MY_PASSWORD= "RACHELI200"
birthday_dict = {(data_row.month, data_row.day): data_row for (index, da... |
631b16127effc928bed56d0f9634b5fdd190795d | RashedNuman/Projects | /Russian Translator.py | 1,709 | 3.78125 | 4 | """
Russian Translator
Written in Python 3.8.1
requires words.txt document
"""
import io
import sys
import time
import os as system
def examples():
print("\n \n \n")
print('=' *25)
print("\n")
with open("words.txt", "... |
daf14930f91f00be998a203212c8932c495c94f2 | RashedNuman/Projects | /Ceaser Cipher Encryptor.py | 10,487 | 4.0625 | 4 | """
Ceaser Cipher Encryptor
Description: Python script that runs ceaser cipher on a txt document, encrypts
decrypts files, can also encrypt based on date
Language: python 3.8.1
Author : Rashed Alnuman
"""
# importing libraries at the start to use
... |
f2ff7a9d8dab2e486422394a1bac5b46ec84c986 | naoya7076/math_puzzle | /python/question1.py | 283 | 3.5625 | 4 | num = 11
while True:
num_str = str(num)
bin_str = format(num, 'b')
oct_str = format(num, 'o')
if num_str == num_str[::-1]\
and bin_str == bin_str[::-1]\
and oct_str == oct_str[::-1]:
print(num)
break
else:
num += 2
|
15b01864d211e3bd0010709f428df92c75f33e80 | ocoyoyix/cookieTest | /mutations.py | 4,205 | 3.78125 | 4 | """
Authors: Orlando Coyoy, Ya'Kuana Davis, Roger Trejo
Course Name: CSCI 3725
Assignment Name: PQ1
Date: September 25, 2020
Description: This file includes a collection of functions that will either assist or cause mutations on given recipe objects
"""
import random
from classes import Recipe, Ingredient
def ingr... |
8f2c41872f9b14089c2d2c6cfd7bcc458e1199ce | ste920ven/project2-pd7 | /Group_1/storage/factual-proof-trial2.py | 636 | 3.5 | 4 | #!/usr/bin/python
#based on Mr. Z's NYT rest code
import urllib
import json
import sys
class Rester:
def __init__(self,url):
self.url = url
def call(self,q):
urlstring = "%s?%s"%(self.url,q)
print urlstring
request = urllib.urlopen(urlstring)
#result = reques... |
96fc0c2e46fb4da7412b685df80924afc6737f65 | abr-98/Bus_stop_finder_unsupervised | /groundtruth/extract_lat_long.py | 663 | 3.96875 | 4 | import sys
def read_data(file_name):
"""
read the data from a csv file
"""
raw= open(file_name).read().split('\n')[1:]
data=[]
for line in raw:
if '\r' in line:
line=line.split('\r')[0]
line=line.split(',')
data.append(line)
while len(data[-1]) < 3:
data.pop()
return data
def write_file(data,f... |
77f9bef0cdf41261a0a3595d19720ef71757a9e8 | Nufuee/python | /list_comprehensions.py | 965 | 4.03125 | 4 | def fib(n):
assert n >= 0
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
# Construct a list of the fibonacci numbers from 1 to 10 using a loop
fibs = []
for i in range(1, 10):
fibs.append(fib(i))
print(fibs)
# List comprehension
[fib(i) for i in range(1, 10)]
# Dictionary comprehension
{i... |
988542e4616bff6a5cd81f01ea9134c95a9e42dd | rakhi26b/Assignments | /Milky_cookies.py | 1,717 | 4.0625 | 4 | import sys
import math
#Number of tests to be run through code
print ("Enter number of tests to be run for T: ")
Not1= int(sys.stdin.readline())
print (Not1)
#check the number of test
if Not1 < 1 or Not1> 1000:
print("ERROR: Incorrect NumberOfTests : ", Not1)
# Iterative Python program to check ... |
3a081791eeb4411c63d09f90206981556b94d7f2 | yunzhou/crack_code | /level_order_traversal.py | 1,068 | 3.640625 | 4 | class TreeNode:
def __init__(self, data,left=None,right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
#return "data {} --> [left : {} --- right : {}]".format(self.data,self.left,self.right)
return "data {}".format(self.data)
def leve... |
852f9a203fc6573361c9c2d81f11bfdceaaef442 | yunzhou/crack_code | /code_8_2.py | 665 | 3.75 | 4 | import numpy as np
N=8
board = np.zeros((N, N))
board[0,2]=1
board[1,2]=1
board[6,3]=1
board[4,4]=1
board[7,0]=1
print(board)
current_path = []
def is_free(x, y):
return board[x, y] == 0
def get_path(x, y):
p = (x, y)
current_path.append(p)
if (x == 0 and y == 0):
return True
success = F... |
fa6f2ec276230e1b909410fff13166f79a397efa | yunzhou/crack_code | /code_1_1.py | 333 | 3.859375 | 4 | '''
1.1 Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
'''
def isUniqueChars(s):
appears = [False]*256
for c in s:
idx = ord(c)
if appears[idx]:
return False
else:
appears[idx]=True
... |
93628cc03226430b588c561e6603679b5f243163 | yunzhou/crack_code | /code_3_5.py | 1,063 | 3.96875 | 4 | class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def deque(self):
if len(self.s2)==0 and len(self.s1)==0:
return None
else:
if len(self.s2)==0:
while(len(self.s1)!=0):
self.s2.append(self.s1.pop())
... |
a2ca7819f3d7302ad0dbe3a8b2c9dbc30d774f16 | colinmyrick/CalTrac | /FoodOpt.py | 512 | 3.578125 | 4 | from tkinter import *
import tkinter as tk
class FoodOpt:
def __init__(self, item, side, servingI, servingS):
self.item = item
self.side = side
self.servingI = servingI
self.servingS = servingS
foodList = {
"Chicken": 335,
"Rice": 205,
"Pizz... |
0167ee7ec16e1a9e69838b818848b0c01c3b5324 | maysuircut007/Numpy | /19.Reshape & Resize.py | 291 | 3.828125 | 4 | import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10])
# reshape
b = a.reshape(2, 5) # reshape ต้องเก็บค่าในตัวแปลใหม่
print(b)
a.resize(2, 5) # resize ไม่ต้องเก็บค่าในตัวเเปลใหม่
print(a) |
e827005bb137eb39d8d507178962a9aadf36dffe | maysuircut007/Numpy | /22.Array และค่าทางสถิติ.py | 647 | 3.578125 | 4 | import numpy as np
a = np.array([1, 2, 3, 4, 5, 6,])
print(a.sum())
print(a.prod())
print(a.max())
print(a.min())
print(a.mean())
print(a.argmax()) # index ที่ข้อมูลค่ามากที่สุด
print(a.argmin()) # index ที่ข้อมูลค่าน้อยที่สุด
x = np.array([[10,30,40],[100,88,50],[77,43,42]])
print(np.min(x,axis = 1)) # axis = 1 คื... |
dbf6efbca82317fe6db54b4328f64335603e4a9c | Muhammad-Elgendi/Machine-Learning-Notes | /Chapter 2 Regression/Section 2 Multiple Linear Regression/Multiple Linear Regression.py | 11,009 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
What is the P-value meaning ?
In plain english:
The p-value is actually the probability of getting a sample like ours,
or more extreme than ours IF the null hypothesis is true.
So, we assume the null hypothesis is true
and then determine how “strange” our sample real... |
450b68eb2689957ce61da69333d6a0588820339d | GTVanitha/PracticePython | /bday_dict.py | 1,003 | 4.34375 | 4 |
birthdays = {
'Vanitha' : '05/05/90',
'Som' : '02/04/84',
'Vino' : '08/08/91'
}
def b_days():
print "Welcome to birthday dictionary! We know the birthdays of:"
names = birthdays.keys()
print ',\n'.join(names)
whose = raw_input("Who's birthday do you wa... |
822e17a0fd1caa0782da452119f681ad52c61afe | GTVanitha/PracticePython | /char_input.py | 616 | 3.96875 | 4 | import datetime
while True:
try:
name = raw_input("Enter your name:")
age = int(input("Enter your age and I will tell you when you will turn 100 :"))
except:
print "Enter valid input"
continue
else:
break
print "Hello %s" %(name)
# Get current time
now = datetime... |
b7b3aa7bcf6cda1e31693370913753cb681a815e | GTVanitha/PracticePython | /rand.py | 383 | 4.09375 | 4 | import random
a= random.randint(1,9)
print "**You have enter a Guessing Game :) **"
user_inp = input("Enter a random number between 1 to 9.")
if (user_inp < a):
print "Your guess:%d is lesser than random number:%d" %(user_inp, a)
elif (user_inp > a):
print "Your guess:%d is greater than random number:%d" %(... |
216b4c8cf3ebb561618aecf3d3e6b87161598d55 | GTVanitha/PracticePython | /som_programs/list_palindrome.py | 199 | 4.28125 | 4 | a = raw_input("Enter a String to check if it is palidrome or not : ")
b = ''
b = ''.join(reversed(a))
print b
if b == a:
print("%s is a palidrome") %a
else:
print('%s is not a palidrome') %a
|
c7c527b7a199e64d3b190076b14aad9badf48429 | GTVanitha/PracticePython | /som_programs/age.py | 315 | 4.09375 | 4 | #! /usr/bin/env python
name = raw_input("Enter your name : ")
while 1:
try:
age = input("Enter your age : ")
except :
print("enter a valid age : ")
continue
else :
break
x = 100 - age
if ( age > 100):
print ( " You are more than 100 years old")
else :
print (" Your will turn 100 in %d years") %(x)
|
b728eb510e7de0b86a65ba7f82c93f7c58874c19 | Veronika988/Algorithms-on-Graphs | /week6/contraction_hierarchies_small_and_large_dist.py3 | 9,811 | 3.84375 | 4 | """
Coursera/Algorithms on Graphs/Week 6 (Advanced Shortest Paths)
- optional/Tasks 3-4 - contraction hierarchies (small and large road networks)
By Shostatskyi. Copyright 2017
Note Coursera Honor Code
"""
import sys
import queue
import time
# Maximum allowed edge length
maxlen = 2 * 10**7
c... |
02ca0bd1dab278230efee1d402618c35b1780996 | Oleh60/Education | /Les8Modules.py | 1,411 | 3.921875 | 4 | # import random
# from random import randint
#
# print("Відгадайте число від 0 - 100 використовуючи підказки")
# unknown = int(input("Ведіть число для відгадування: "))
# a = random.randint(0, 100)
#
# count = 0
#
#
# while a != unknown:
#
# count += 1
# if unknown > a:
# print("Введене число більше з... |
bdae14f047df34a78d7c1b5d1e03696f26327189 | htomeht/scripts | /nonascii.py | 449 | 3.703125 | 4 | #!/usr/bin/python
import os,string
chars={}
def nonascii(string):
for char in string:
if ord(char)>127 and char not in chars:
chars[char]=string
for root, dirs, files in os.walk(os.getcwd()):
for d in dirs:
nonascii(d)
for f in files:
nonascii(f)
print "These non-as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.