blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c62a92a9e9d3ac9829db7c400dd9744b669ee1af | sangm1n/problem-solving | /LeetCode/reverse_string.py | 731 | 4.125 | 4 | """
author : Lee Sang Min
github : https://github.com/sangm1n
e-mail : dltkd96als@naver.com
title : Reverse String
description : Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
"""
from typing import List
def reverseString(s: List[str]) -> None:
left, right = 0, len(s)-1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
if __name__ == '__main__':
ex1 = ['h', 'e', 'l', 'l', 'o']
ex2 = ['H', 'a', 'n', 'n', 'a', 'h']
reverseString(ex1)
reverseString(ex2)
print(ex1)
print(ex2)
|
eb4c3a67fbf77f6bd651b5a51360de28c0137416 | ericbollinger/AdventOfCode2020 | /day10/second.py | 1,061 | 3.71875 | 4 | #with open("demo2.txt", "r") as f:
with open("input.txt", "r") as f:
lines = f.readlines()
adapters = [int(l.strip()) for l in lines]
adapters.sort()
lo = adapters[0]
hi = adapters[len(adapters)-1]
# Add the outlet and your device to list
adapters.insert(0, 0)
adapters.append(hi+3)
# Work backward to determine how many possibilities there are from the back
# of the list. The last element obviously only has 1 option, so hardcode that.
possible = [0 for i in range(0, len(adapters))]
possible[len(possible)-1] = 1
# Iterate from the second-to-last element to the first element
for i in range(len(adapters)-1, -1, -1):
# For each element that can be jumped to, add its possiblities to the
# current element, as they are possible branches
for n in range(1,4):
if i+n in range(0, len(adapters)):
if 1 <= (adapters[i+n] - adapters[i]) <= 3:
possible[i] += possible[i+n]
# By the end, the first element will have all possibilities accounted for
print("{} arrangements possible".format(possible[0]))
|
01dc7da92797ddd9cd72b744c3fc0d67c5bc63db | sahiljajodia01/Competitive-Programming | /leet_code/kth_largest_element_in_an_array.py | 708 | 3.625 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/800/
###### Again a hashmap follwed with sorting that hashmap. Complexity: O(n) + O(klogk) where k is number of distinct elements #####
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
d = {}
for i in range(len(nums)):
if nums[i] in d.keys():
d[nums[i]] += 1
else:
d[nums[i]] = 1
d_sorted = sorted(d.items(), key=lambda v: v[0], reverse=True)
total = 0
for key, value in d_sorted:
total += value
if k <= total:
return key |
8bae3c27458e0fe4d6007ce206e001662439511d | the9sjeric/ProjectAioi | /Practice/No_10/10.3_error.py | 852 | 3.953125 | 4 | # try:
# print(5/0)
# except ZeroDivisionError:
# print("You can't divide by zero!!!")
# filename = "alice.txt"
# try:
# with open(filename) as f:
# text = f.read()
# except FileNotFoundError:
# print(f'{filename} is not exist!')
# title = "Alice in Wonderland"
# print(title.split())
# changdu = title.split()
#
# print(len(changdu))
# print(len(title))
while True:
try:
x = float(input("请输入第一个数字:"))
except NameError or ValueError:
print("请输入一个《数字》哦")
continue
else:
xx = int(x)
break
while True:
try:
y =float(input("请输入第二个数字:"))
except NameError or ValueError:
print("请输入一个《数字》哦")
continue
else:
yy = int(y)
break
z = xx + yy
print(z)
|
20f298a836fb35e5d2e4097d2af1f0f1b934e73d | HopeCheung/leetcode | /leetcode-second_time/stack/leetcode71(Simplify Path).py | 497 | 3.609375 | 4 | class Solution:
def simplifyPath(self, path: 'str') -> 'str':
ans = path.split("/")
i, stack = 0, []
while i < len(ans):
if ans[i] == "" or ans[i] == ".":
i = i + 1
elif ans[i] == "..":
if len(stack) != 0:
stack.pop()
i = i + 1
else:
stack.append(ans[i])
i = i + 1
ans = "/".join(stack)
return "/" + ans
|
5cbc4abc2dfffb61ca36dde9ebfbd756e203102b | manusoler/code-challenges | /projecteuler/pe_10_summation_of_primes.py | 465 | 3.5625 | 4 | from utils.decorators import timer
from .pe_3_largest_prime_factor import prime_iter
"""
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
def summation_of_primes_below(n):
summation = 0
for p in prime_iter():
if p > n:
break
summation += p
return summation
@timer
def main():
print(summation_of_primes_below(2000000))
if __name__ == "__main__":
main() |
493454fd6b6417be95cd9a85d62ff8915aa7417a | hutanugeorge/Data-Structures-Python | /LinkedList.py | 3,016 | 4 | 4 | class LinkedList:
class node:
def __init__(self, value = None):
self.value = value
self.next = None
def __init__(self):
self.head = None
self.tail = self.head
self.lenght = 0
def append(self, value):
new_node = self.node(value)
if not self.head:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.lenght += 1
return self
def prepend(self, value):
new_node = self.node(value)
new_node.next = self.head
self.head = new_node
self.lenght += 1
return self
def insert(self, index, value):
if isinstance(index, int):
if index >= self.lenght:
return self.append(value)
new_node = self.node(value)
leader = self.traverse_to_index(index - 1)
next_node = leader.next
leader.next = new_node
new_node.next = next_node
return self
else:
print('Index must be an integer!')
return
def remove(self, index):
if isinstance(index, int):
if self.lenght <= index or index < 0:
print('Index must be smaller than list lenght and greater than 0!')
return
elif index == 0:
self.head = self.head.next
self.lenght -= 1
return self
item = self.traverse_to_index(index - 1)
remove_item = item.next
item.next = remove_item.next
self.lenght -= 1
return self
else:
print('Index must be an integer!')
return
def lookup(self, value):
counter = 0
current_node = self.head
while counter < self.lenght:
if current_node.value == value:
return counter, value
counter += 1
current_node = current_node.next
return
def traverse_to_index(self, index):
counter = 0
current_node = self.head
while counter != index:
current_node = current_node.next
counter += 1
return current_node
def reverse(self):
first = self.head
self.tail = self.head
second = first.next
while second:
temp = second.next
second.next = first
first = second
second = temp
self.head.next = None
self.head = first
return self
def print(self):
if self.head is None:
print('Linked list is empty')
return
else:
array = []
current_node = self.head
while current_node:
array.append(current_node.value)
current_node = current_node.next
print(array)
def __len__(self):
return self.lenght
|
0d4bb9b3b2ceac7baab2929f12b42bf3ec6c374b | annazwiggelaar/LCPython_week3 | /3.4.4.7.py | 230 | 4.09375 | 4 | length_a = int(input("What is the length of side a?"))
length_b = int(input("What is the length of side b?"))
c_squared = (length_a ** 2) + (length_b ** 2)
c = c_squared ** 0.5
print("The length of the hypotenuse is", c)
|
24582fbdc6ca6e96c19134003e1b03aade82b4df | sourishjana/demopygit | /file_writing.py | 263 | 4.1875 | 4 | f=open('abc','w')
f.write("i love to code")
#now if we want to again write in the"abc" file then if we reuse f.write it will not work
#then i love to code will be replaced by the new line
#so we have to append the file
#run the code to write
#see at abc |
acf50aebdbd10132f2dbcbf0ae47b4cc43b681f3 | coparker/CST205Proj2 | /A2.py | 1,908 | 3.765625 | 4 | """
work on making a function that will take a black image
and put that into the GPU so that the graphics card can
do the work to make it faster. also make the function input
an image so that it doesnt have to be just a black image.
"""
import sys
import sdl2
import sdl2.ext
import time
import Audio
"""
@Author: Nathan Levis
@Date: 10/14/2016
This file includes everything necessary to create a window and change the color of the window surface.
"""
class SoftwareRenderer(sdl2.ext.SoftwareSpriteRenderSystem):
def __init__(self, window):
super(SoftwareRenderer, self).__init__(window)
def render(self, components):
sdl2.ext.fill(self.surface, (255, 255, 255)) # initial window will be white
super(SoftwareRenderer, self).render(components)
class SoftwareRen(sdl2.ext.SoftwareSpriteRenderSystem):
def render(self, components):
for x in Audio.myArray1:
color = sdl2.ext.Color(x, x, x)
# deems the color black to color the window.
sdl2.ext.fill(self.surface, color)
time.sleep(1)
super(SoftwareRen, self).render(components)
def run():
sdl2.ext.init() # Initializes SDL2
window = sdl2.ext.Window("Frequency Image", size=(600, 600))
# deems the window specs
window.show() # makes the window visible
world = sdl2.ext.World()
# deems the world environment
spriteRenderer = SoftwareRenderer(window)
# Renders the window
world.add_system(spriteRenderer)
# adds the world to the window environment
world.add_system(SoftwareRen(window))
running = True
while running:
events = sdl2.ext.get_events() # makes it so the window looks for events
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
world.process()
if __name__ == "__main__":
sys.exit(run())
|
0cd1d37841af39413b84b369e8493180637e2dd4 | devng/code-puzzles | /src/devng/adventofcode/day09/day09.py | 1,573 | 4 | 4 | #!/usr/bin/env python
# Make the script compatible with python 3.x
from __future__ import absolute_import, division, print_function, unicode_literals
import re
import itertools
line_regex = re.compile(r"(\w+) to (\w+) = (\d+)")
cities = set()
distances = dict()
def parse_line(line):
m = line_regex.match(line)
if m:
city1 = m.group(1)
city2 = m.group(2)
distance = int(m.group(3))
cities.add(city1)
cities.add(city2)
distances[(city1, city2)] = distance
else:
raise ValueError("Invalid line: " + line)
def find_route():
shortest = None
longest = None
for route in itertools.permutations(cities):
cur_lenght = 0
for i in range(len(route) - 1):
city1 = route[i]
city2 = route[i + 1]
if (city1, city2) in distances:
cur_lenght += distances[(city1, city2)]
elif (city2, city1) in distances:
cur_lenght += distances[(city2, city1)]
else:
print("Not path from", city1, "to", city2)
if not shortest or cur_lenght < shortest:
shortest = cur_lenght
if not longest or cur_lenght > longest:
longest = cur_lenght
return shortest, longest
def process_file(filename):
with open(filename, "r") as f:
for line in f:
parse_line(line)
return find_route()
def main():
r = process_file("input.txt")
print("Shortest route: %d\nLongest route: %d" % r)
if __name__ == "__main__":
main()
|
1aa83375bc92f392edf4b13218eb293fb6037337 | thaynagome/teste_python_junior | /teste_1020.py | 848 | 4.21875 | 4 | #!/usr/bin/env python
# -- coding: utf-8 --
#Solicita inserção de dias de idade do usuario
dias = int(input("Digite sua idade em dias: "))
#Divide dias por 365 e no resultado obtém apenas a parte inteira da divisão
anos = dias // 365
# Obtem o resto da operação e divide por 30 com objetivo de obter a parte inteira
meses = (dias % 365) // 30
#Esta parte obterá o resto da operaçao, depois resolverá a operação em
#parenteses que irá obter o resto da operação indicada, dividir por 30
#obtendo sua parte inteira, e depois e obter esse resultado irá multiplicar
#por 30, que por fim, resolverá os parenteses da direita e subtrairá da
#primeira operação
dias = (dias % 365) - (((dias % 365)//30) * 30)
print (.format(anos) ,"ano(s)")
print (.format(meses) ,"mes(es)")
print (.format(dias) ,"dia(s)")
|
ec1fe0b40f30b2da1f1b4f4626f72874497e478c | rafaellamgs/prog_comp2018.1 | /exercicios19_09/L06Q3.py | 210 | 4 | 4 |
valor = int(input('Informe um número para ver seu fatorial:'))
fatorial = 1
for numero in range(valor, 0, -1):
fatorial = numero * fatorial
print('O fatorial de {0} é {1}.'.format(valor,fatorial))
|
293abe21fc42001f4d8d8e7f4f3856b9003c422d | daisyzz/First-Program | /HangMan 2.py | 1,750 | 4.0625 | 4 | import random
import time
commands = ['start', 'easy', 'quit']
words = ['pizza', 'lemon', 'orange']
def start():
print("""
HangMan by Owen
Commands
start - to get a word
easy - play extra lives
quit - exit the game""")
if len(words) < 1:
print("You tried all of our word's congrats!!!!!")
print("Exiting in 10 second's! Thank you for playing")
time.sleep(10)
quit()
command = input(">").lower()
if command == commands[0]:
main(3)
elif command == commands[1]:
main(6)
elif command == commands[2]:
quit()
else:
print("I don't understand")
start()
def main(lives):
word = random.choice(words)
print(f'Your word is {len(word)} characters')
words.remove(word)
right_guess = ''
wrong_guess = ''
while lives > 0 and len(word) != len(right_guess):
player_input = input("Please enter your guess: ").lower()
if player_input is not type(str) and len(player_input) != 1:
print("Only single letter guesses please.")
elif player_input in right_guess or player_input in wrong_guess:
print("You already guessed that!")
elif player_input in word:
print("You got it right!")
for i in word:
if i == player_input:
right_guess += i
print(f'{i if i in right_guess else"_"} ', end='')
print()
else:
lives -= 1
wrong_guess += player_input
print(f"You guess is wrong and now have {lives} {'life' if lives == 1 else 'lives'} left.")
print(f"You {'won' if lives > 1 else 'lost'} with {lives} {'life' if lives == 1 else 'lives'} left")
start()
start()
|
c4caac9e5391b2b81451f070ce26f2dcdf2a3e0e | kartika14/data_incubator_April-2018 | /day5.py | 6,907 | 3.5625 | 4 | # All the images are on a public dropbox folder that is going to self destruct in 7 days.
# Use pythonanywhere's servers to host this folder, so the script can run on the cloud.
# Why is it going to self-destruct in 10 days? For one, I wanted to see if I can do it. For 2, incase some
# robot decides to download it over and over all day long, sapping my dropbox bandwidth.
# Convention for numpy use
import numpy as np
# Lets create an array
my_array = np.array( [0,1,2,3] )
# hit enter, you see the array printed
# learn some things about your array
my_array.dtype
len(my_array)
# integer, 64 bit is the data type of the objects in your array
# you can change those into strings, in case you use them as text or something
str_array = my_array.astype(str)
# to see the differences in these arrays
for i in my_array:
print i*4
for i in str_array:
print i*4
# This was basically a python list. Numpy is more useful for multidimensional arrays.
# Which sounds like a fancy word, but basically we just mean a table, dataset, rows/columns of values.
# I will stick to 1, 2 and 3 dimensional arrays. One just a list, or one row / column of data.
# 2 dimensions would be a table of data. And 3 dimensions is most often seen in an image like RGB, where you pixels, which are in rows / columns.
# But those pixels are themselves made of an array of 3 values R,G and B.
dim2_array = np.array([[0,1,2,3], [0,1,2,3], [0,1,2,4]])
dim2_array.ndim
dim2_array.shape
dim2_array.size
# When doing math on an array, you can choose to do the whole thing, or line by line.
np.mean(dim2_array)
np.mean(dim2_array, axis = 0)
np.mean(dim2_array, axis = 1)
# Easy to forget, but very important is indexing these arrays.
dim2_array[:]
dim2_array[:2]
dim2_array[:2,:]
dim2_array[:2,:2]
dim2_array[0][::-1]
# more dimensions and data get confusing to look at. And doing math, you get lots of sig figs.
dim2_array = np.array([[0.002002020203020,1,2.83893289239832,3.3243283293], [0.32323222,10000000000000,2,3], [0,1,2,300000000000000000000]])
# What is that again??
# So a little unix lesson is always helpful..
# Note to shane... try canopy on windows for this
ls
cd Desktop/Temps
# I do this a lot
# use numpy's ability to save your array as a csv file, then look at it in excel.
np.savetxt('lookatarray.csv', dim2_array, delimiter = ',')
# While were in excel, let me show you genfromtxt.
# Lets edit something in excel
# Show tab completion in iPython for np.gen
np.genfromtxt('lookatarray', delimiter = ',')
# NAs and NANs come up often when there is missing data.
arr = np.array([0,7,1,8, np.nan])
np.mean(arr)
# You have to make it into a masked array in order to do math with nans
# Show tab completion in iPython for np.ma.
arr2 = np.ma.masked_array(arr, np.isnan(arr))
np.mean(arr2)
#########################################################
#########################################################
#########################################################
# These scientific libraries have many function. Finance for example
from matplotlib.finance import quotes_historical_yahoo
from datetime import date
import numpy as np
today = date.today()
# Wait, what does this do again? How do you use it. You could go to google, or just:
?quotes_historical_yahoo
# Ok so it takes 2 dates and returns the info on the stock between that
# Oh see theres a function parse_yahoo_historical that will tell you how it works.
?parse_yahoo_historical
# Ok it is d, open, close, high, low, volume
# If thats not enough info and you wan't the source code.
??quotes_historical_yahoo
start_date = (today.year -1, today.month, today.day)
year_of_data = quotes_historical_yahoo('TICKER', start_date, today)
# try indexing it, you get some error. Oh its not a numpy array...weird.
COWyear = quotes_historical_yahoo('cow', start_date, today)
DOGyear = quotes_historical_yahoo('dog', start_date, today)
COWyear = np.array(COWyear)
DOGyear = np.array(DOGyear)
COWcloses = COWyear[:,2]
DOGcloses = DOGyear[:,2]
plt.clf()
plt.subplot(211)
plt.plot(COWcloses, 'ro')
plt.subplot(212)
plt.plot(DOGcloses, 'bo')
# Let's say you get this file back from the sequencing company.
# You did an experiment testing random peptides on some virus within your cell culture.
# You wanted to see which peptides bind most strongly to the virus because you
# want to make a new biological therapeutic that binds and disables the virus.
import numpy as np
my_seqs = np.genfromtxt('sequencereads.txt', delimiter = '\n', dtype = str)
print my_seqs.size, 'sequences in this file \n'
molecular_weight_dict = {"A":89.09, "R":174.2, "D":133.1, "N":132.12, "C":121.16, "E":147.13, "Q":146.14, "G":75.07, "H":155.15, "I":131.17, "L":131.17, "K":146.19, "M":149.21, "F":165.19, "P":115.13, "S":105.09, "T":119.12, "W":204.23, "Y":181.19, "V":117.15, "X":0.0}
def Calculate_molecular_weight(sequence):
mw = 0
for i in list(sequence):
mw += molecular_weight_dict[i]
return mw
##NumpyMW = np.vectorize(Calculate_molecular_weight)
##
##MWs = NumpyMW(my_seqs)
##
##print 'Average MW: ', np.mean(MWs)
##print 'Standard Dev. MW: ', np.std(MWs)
###################################################
###################################################
###################################################
# The non-vectorized version not that much slower
import time
time1 = time.time()
arr = []
for i in my_seqs:
mw = Calculate_molecular_weight(i)
arr.append(mw)
print np.mean(arr)
time2 = time.time()
print time2-time1, 'time'
#############################################################
#############################################################
#############################################################
# Where vectorization really counts is in multidimensional arrays, like images.
import time
import matplotlib.pyplot as plt
image = plt.imread("/Users/chimpsarehungry/Dropbox/RiceU/BrightworkClass/image_timeseries/img_0001.jpg")
# We think the low green values are actually non-specific, background noise.
# Lets look at the image without it.
# Make anything in the green channel less than 40 be a zero
time1 = time.time()
## Built in vectorized functions
image[ image[:,:,1] < 40 ] = 0
# ASIDE: INDEXING WITH TRUTH ARRAYS
#############################
# a = np.array([[1,2,3],[4,5,6]])
# a >=3
# a[ a>=3 ]
#############################
time2 = time.time()
timevec = (time2 - time1)
print 'time for vectorized: ', timevec
################ Loop ##########
time3 = time.time()
for i in xrange(0, image.shape[0]):
for k in xrange(0, image.shape[1]):
if image[i,k,1] < 40:
image[i,k,1] = 0
time4 = time.time()
timeloop = (time4 - time3)
print 'time for loops: ', timeloop
print 'vectorized is', (timeloop / timevec), 'times faster'
plt.imshow(image)
plt.show()
# thats the difference in your code taking a month to run, or a few hours.
|
74eb59a548373ab473e032aa72b7c032b01a607d | cionx/programming-methods-in-scientific-computing-ws-17-18 | /solutions/chapter_03/exercise_03_08.py | 428 | 4 | 4 | ### (1)
from trapeze import trapeze
### (2)
from math import sin, pi
n = 1
s = 0
while 2 - s >= 1.E-6: # sin is concave on [0,pi] -> estimate too small
n += 1 # can skip n = 1 because it results in 0
s = trapeze(sin, 0, pi, n)
print("Estimate for integral of sin from 0 to pi using trapeze:")
print(s)
### OUTPUT:
# Estimate for integral of sin from 0 to pi using trapeze:
# 1.9999990007015205
|
3649a8a88995fc1f0aeac7d004c21f9ef6f8948f | c-a-c/PythonStudy | /master/2019June26Wed/list2.py | 334 | 4.03125 | 4 | int_str = [1,"2",3,"4",5,"6",7,"8",9,]
# # Use Range Function
# print("Use Range Function")
# for i in range(len(int_str)):
# print(int_str[i], type(int_str[i]))
# print()
# Get One Element
print("Get One Element")
for i in int_str:
print(i, type(i))
print()
# # Print List
# print("Print List")
# print(int_str, type(int_str))
|
6ba3c9cd6d99269dcad040d14c5f5a3f3d491b38 | PatrickCHennessey/Data_Visualization_Project | /app.py | 3,918 | 3.578125 | 4 | from flask import Flask, render_template, request, redirect, url_for
import pymongo
import json
# create instance of Flask app
app = Flask(__name__)
# create route that renders index.html template
@app.route("/")
def index():
"""Main/default path that serves index.html from the templates folder"""
return render_template('index.html')
'''
XXXXX SAMPLE CODE FROM PAST PROJECT XXXXXX
# Connect to MongoDB connection/collection
# myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# Connects to MONGO mydb = myclient["create_db"]
# Connects to a specific database in MONGO
# mycol = db["mars_dictionary"]
# Accesses a specific collection/table within the database in MONGO
print("Records in collection: ", mycol.count_documents({}))
# Retrieve the dictionary record
results_dict = mycol.find_one() # retrieve everything in the collection
# Have Flask serve the index.html template file, passing data from the dictionary to the file;
return render_template('index.html', results=results_dict)
'''
@app.route("/create_db")
def create_db():
# load the source data (genre_year.json)
# CHANGE TO CSV SOURCE XXXXXXXX
with open("genre_year_df.json","r") as fp:
json_data = json.load(fp)
print(json_data) # to test if json_data prints into terminal
return(json_data) # prints genre_year_df.json/json_data to Chrome live server
# parse it (genre_year.json) so that I grab only the year from the data
# store in MongoDB (genre_year.json)
# What will be the structure of the table/collection in MongoDB (for each record)
# Suggestion: Use the headings from the source csv
# Headings from genre_year_df.csv: Year,top_genre,Peak Position,Danceability,Duration,Energy,Liveness,Loudness,Mode,Popularity,Tempo,Valence
#return "<p>Create DB route/process completed</p>"
@app.route("/api")
def api():
print("API Call received")
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mycol = myclient["GT_Data_Visualization"]
# receive a search query from the website (js-fetch)
# search Mongo DB for all records matching the year
year = request.args.get('year')
# Default year
if year == None:
year = 1999
find_mongoDB = mycol.GT_Data_Visualization_cn.find({},{ "Year": year })
new_var = []
for entry in find_mongoDB:
new_var.append(entry)
print(new_var)
return str(new_var)
# return matching records to js-fetch for processing by the JS on the web site
#"Records in collection: ", mycol.GT_Data_Visualization_cn
#TypeError: 'Collection' object is not callable. If you meant to call the
# 'GT_Data_Visualization_cn' method on a 'Database' object it is failing
# because no such method exists. The view function did not return a valid response.
# The return type must be a string, dict, tuple, Response instance, or WSGI callable,
# but it was a Collection.
'''
@app.route("/scrape")
def scrape_route():
print("Starting the scrape process")
from scrape_mars import scrape
my_dict = scrape()
# Get python to connect to existing mongoDB
# store my_dict in MongoDB
print("Scrape process complete.")
print(my_dict)
print("Storing dictionary in MongoDB.")
# Create MongoDB connection/collection
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mars_db"]
mycol = mydb["mars_dictionary"]
# clear any old data from the collection
mycol.delete_many({})
# insert scraped dictionary
x = mycol.insert_one(my_dict)
the_id = x.inserted_id # get id of inserted record (optional)
print("Created record ID: ", the_id)
#return "<h1>Process Complete</h1>"
return redirect(url_for('index'))
'''
if __name__ == "__main__":
app.run(debug=True) |
e238cf956d6ea59e80770b83fa92c781497b3dcb | AngryGrizzlyBear/PythonCrashCourseRedux | /Part 1/Ch.8 Functions/Passing an Arbitrary Number of Arguments/Try_it_yourself_5.py | 2,078 | 4.34375 | 4 | # 8-12. Sandwiches: Write a function that accepts a list of items a person wants
# on a sandwich. The function should have one parameter that collects as many
# items as the function call provides, and it should print a summary of the sandwich
# that is being ordered. Call the function three times, using a different number
# of arguments each time.
def make_sandwhich(*items):
"""Make a sandwhich with the given items."""
print("\nI'll make you a great sandwich:")
for item in items:
print("......adding " + item + " to your sandwich.")
print("Your sandwich is ready!")
make_sandwhich('roast beef', 'cheddar cheese', 'lettuce', 'honey dijon')
make_sandwhich('turkey', 'apple slices', 'honey mustard')
make_sandwhich('peanut butter', 'strawberry jam')
# 8-13. User Profile: Start with a copy of user_profile.py from page 153. Build
# a profile of yourself by calling build_profile(), using your first and last names
# and three other key-value pairs that describe you.
# 8-14. Cars: Write a function that stores information about a car in a dictionary.
# The function should always receive a manufacturer and a model name. It
# should then accept an arbitrary number of keyword arguments. Call the function
# with the required information and two other name-value pairs, such as a
# color or an optional feature. Your function should work for a call like this one:
# car = make_car('subaru', 'outback', color='blue', tow_package=True)
# Print the dictionary that’s returned to make sure all the information was
# stored correctly
def make_car(manufacturer, model, **options):
"""Make a dictionary representing a car."""
car_dict = {
'manufacturer': manufacturer.title(),
'model': model.title(),
}
for option, value in options.items():
car_dict[option] = value
return car_dict
my_outback = make_car('subaru', 'outback', color = 'blue', tow_package=True)
print(my_outback)
my_accord = make_car('honda', 'accord', year = 1991, color = 'white',
headlights = 'popup')
print(my_accord)
|
fec6c1430762e599a85f98344c9ba9b2eea56f76 | ekjellman/interview_practice | /epi/5_2.py | 959 | 3.953125 | 4 | ###
# Problem
###
# Swap two given bits in a given number. (Assume it's 64 bit)
###
# Work
###
# Questions:
# Can we assume the numbers are positive, since it's Python? (Yes, we're
# them as a bitvector)
def swap_bits(num, a, b):
a_value = num & (1 << a)
b_value = num & (1 << b)
if a_value == b_value: return num
if a_value != 0:
num -= a_value # Don't rememeber how to clear
num |= 1 << b
else:
num -= b_value
num |= 1 << a
return num
# Tests:
num = 0b10110101
print bin(swap_bits(num, 0, 3)), "0b10111100"
num = 0b10110101
print bin(swap_bits(num, 1, 5)), "0b10010111"
num = 0b10101010
print bin(swap_bits(num, 0, 4)), "0b10101010"
num = 0b10101010
print bin(swap_bits(num, 1, 5)), "0b10101010"
# Time: 11 minutes
###
# Mistakes / Bugs / Misses
###
# Didn't remember how to clear a bit.
# Line 23 had b instead of a
# Didn't think of using XOR for a bit flip. TODO: card
# Checking a bit using >> is also interesting
|
230b56d6d2a771ed45a5c0b2835b88c5a65c0756 | edu-athensoft/ceit4101python | /stem1400_modules/module_10_gui/s06_layout/s062_grid/tk_6_grid.py | 481 | 4.28125 | 4 | """
Tkinter
rewrite last program
using grid layout
relative position
ref: #2
"""
from tkinter import *
root = Tk()
# create a label widget
label1 = Label(root, text='Athensoft').grid(row=0, column=0)
label2 = Label(root, text='Python Programming').grid(row=1, column=5)
label3 = Label(root, text='III').grid(row=1, column=1)
# show on screen
# relative position
# label1.grid(row=0, column=0)
# label2.grid(row=1, column=5)
# label3.grid(row=2, column=1)
root.mainloop() |
efced363b92d2ca7c92212da7184bbf9f258b5f8 | ruthiler/Python_Exercicios | /Desafio062.py | 619 | 4.0625 | 4 | # Desafio 062: Melhore o DESAFIO 061, perguntando para o usuário se ele
# quer mostrar mais alguns termos. O programa encerrará quando ele disser
# que quer mostrar 0 termos.
print('-*-' *10)
termo = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razao: '))
cont = 10
contador = 0
total = 0
while cont != 0:
total += cont
while contador <= total:
print('{} -> '.format(termo), end='')
termo += razao
contador += 1
print('PAUSA')
cont = int(input('Quantos termos vc quer mostrar a mais? '))
print('PA finalizada com {} termos mostrados.'.format(total))
|
08b6baae3cc698edb3d8e3ff992e31ada5f240c8 | Sreekanthrshekar/Verified | /01_python_basics/class_oop.py | 3,894 | 4.4375 | 4 | #GEOMETRIC CLASSES
''' This document is all about creation of geometric classes '''
import math
# Create a class named 'Cylinder' which takes in height and radius and
# has the following methods: volume of the cylinder, surface area of the cylinder
class Cylinder():
''' This class takes in radius and height and
can be used to obtain volume and surface area of the cylinder'''
def __init__(self,height=1,radius=1):
self.height = height
self.radius = radius
def volume(self):
''' volume = pi.r^2.h'''
vol = (math.pi)*(self.radius**2)*(self.height)
return f" volume of cylinder: {vol} "
def surface_area(self):
'''surface area = 2*pi*r*h + 2*pi*r^2'''
sa_top_bottom = (math.pi)*(self.radius)**2
sur_area = (2*(math.pi)*(self.radius)*(self.height)) + (2*sa_top_bottom)
return f" surface area of cylinder: {sur_area} "
# create a class named Line which takes in coordinates in the form of tuples and
# has the following methods: distance between coordinates, slope of line formed
class Line():
''' This class takes in coordinates of two points and
can be used to obtain the distance between points and slope of the line formed'''
def __init__(self,coor1,coor2):
self.coor1 =coor1
self.coor2 =coor2
def distance(self):
'''distance is given by: sqrt((x2-x1)^2 |+ (y2-y1)^2))'''
x_1,y_1 = self.coor1
x_2,y_2 = self.coor2
dis = math.sqrt((x_2-x_1)**2 + (y_2-y_1)**2)
return f"distance between coordinates: {dis} "
def slope(self):
'''slope is given by: (y2-y1)/(x2-x1)'''
x_1,y_1 = self.coor1
x_2,y_2 = self.coor2
slop = (y_2-y_1)/(x_2-x_1)
return f"slope of the line formed: {slop}"
#create a class named 'Cone' which takes in radius and height as aguments and
# has the following methods: volume of a cone, surface area of the cone
class Cone():
''' This class takes in radius and height and
can be used to obtain volume and surface area of the cone'''
def __init__(self, radius, height):
self.radius = radius
self.height = height
def volume(self):
''' Volume of the cone is given by:
pi*(r^2)*(h/3) '''
vol = (math.pi)*(self.radius**2)*(self.height/3)
return f"volume of cone: {vol}"
def surface_area(self):
''' Surface area of cone is given by:
pi*r*(r + sqrt(h^2 + r^2))
part_1 = pi*r
part_2 = (r + sqrt(h^2 + r^2))'''
part_1 = (math.pi*self.radius)
part_2 = (self.radius + (math.sqrt(self.height**2 + self.radius**2)))
sur_area = part_1*part_2
return f'surface area of cone: {sur_area}'
class Circle():
'''Takes in radius as argument and has methods to calculate
diameter, circumference and area of the circle'''
def __init__(self,radius):
self.radius = radius
def diameter(self):
'''diameter of a circle = 2*r'''
dia = 2*self.radius
return f"diameter of the circle for the given radius: {dia}"
def circumference(self):
''' circumference of circle: 2*pi*r'''
circum = 2*math.pi*self.radius
return f"circumference of circle for the given radius: {circum}"
def area(self):
'''area of circle: pi*r^2'''
area = math.pi*(self.radius**2)
return f"area of the circle for the given radius: {area}"
if __name__ == '__main__':
c = Cylinder(2,3)
print(c.volume())
print(c.surface_area())
li = Line((3,2),(8,10))
print(li.distance())
print(li.slope())
cone = Cone(radius=1, height=3)
print(cone.volume())
print(cone.surface_area())
circle1 = Circle(10)
print(circle1.diameter())
print(circle1.circumference())
print(circle1.area())
|
a1ae7b89b29feda2b052ba87516cd20554a22ef1 | Anz131/luminarpython | /Functions/var length args.py | 1,552 | 3.640625 | 4 | #variable length arguments
#accept any no of args in same method
#using * and return as tuple
#** for key value pair amnd return as dictionary
# def add(*args):
# print(args)
# add(10)
# add(10,20)
# add(10,20,30)
# def add(*args):
# res=0
# for num in args:
# res+=num
# return res
# print(add(10,20,30,40))
# arr=[4,3,7,5,9]
# # arr.sort(reverse=True) #sort the current list
# # print(arr)
# sorted(arr) #sort into new list
# print(arr)
# def mysortfn():
# print("Inside sort fn")
#
# class MyList:
# def mysortmeth(self):
# print("Inside sort method")
#
# mysortfn()
#
# obj=MyList()
# obj.mysortmeth()
# def print_employee(**kwargs):
# print(kwargs)
# print_employee(id=100,name="Anu",salary="50000")
employees={
1000:{"eid":1000,"name":"ajay","salary":25000,"designation":"developer"},
1001: {"eid": 1001, "name": "vjay", "salary": 22000, "designation": "developer"},
1002: {"eid": 1002, "name": "arun", "salary": 26000, "designation": "qa"},
1003: {"eid": 1003, "name": "varun", "salary": 27000, "designation": "ba"},
1004: {"eid": 1004, "name": "ram", "salary": 20000, "designation": "mrkt"},
}
def print_employee(**kwargs): #kwargs={id:1003,prop="salary"
id=kwargs["id"] #1000
prop=kwargs["prop"] #salary
if id in employees: #1000 in employees
print(employees[id]["name"]) #employees[1000]
print(employees[id][prop]) #employees[1000]
else:
print("Invalid id")
print_employee(id=1000,prop="salary")
|
aa10f4bdc7ab3340ed500c1b87a4da8b522375ef | yrao104/2018-Summer-Python | /Unit3/ChangeTendered.py | 1,526 | 4.15625 | 4 | '''
Yamuna Rao
6/25
Directions: Write an application that reads the purchase price and the amount paid. Display the change in dollars, quarters,
dimes, nickels, and pennies. The input value has to be in decimal value (exclude the dollar sign). You are not allowed to use
if statements or loops! Note: You may be off a penny, just sig fig issue.
'''
price = input("Enter the purchase price of an item (Exclude the dollar sign):")
given = input("Enter the money that you paid the cashier (Exclude the dollar sign): ")
print("The purchase price was $" + str(price))
print("You paid $" + str(given))
change = float(given) - float(price)
print("You recieved $" + str(change) + " as change.")
dollar100 = change// 100
dollar50 = change%100 // 50
dollar20 = change%100%50 // 20
dollar10 = change%100%50%20 // 10
dollar5 = change%100%50%20%10 // 5
dollar1 = change%100%50%20%10%5 // 1
quarters = change%100%50%20%10%5%1*100 // 25
dimes = change%100%50%20%10%5%1*100%25 // 10
nickels = change%100%50%20%10%5%1*100%25%10 // 5
pennies = change%100%50%20%10%5%1*100%25%10%5 // 1
print(str(int(dollar100)) + " one hundred dollar bill(s)")
print(str(int(dollar50)) + " fifty dollar bill(s)")
print(str(int(dollar20)) + " twenty dollar bills")
print(str(int(dollar10)) + " ten dollar bill(s)")
print(str(int(dollar5)) + " five dollar bill(s)")
print(str(int(dollar1)) + " one dollar bill(s)")
print(str(int(quarters)) + " quarters")
print(str(int(dimes)) + " dimes")
print(str(int(nickels)) + " nickels")
print(str(int(pennies)) + " pennies")
|
5c9a4ea1c4311bf6b24326beee02a8e40bce514a | DerekTeed/python-challenge | /PyBank/main.py | 1,822 | 3.6875 | 4 | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
import pandas as pd
import numpy as np
# Module for reading CSV files
import csv
df = pd.read_csv("excelBank.csv")
print(df)
something1 = df.sum(axis = 1)
print(df['Profit/Losses'])
profitChange = df['Profit/Losses']
profitChange1 = profitChange.diff().values
print("new Hope")
gtIncrease = max(profitChange1[1:])
gtDecrease = min(profitChange1[1:])
print(max(profitChange1))
newhope1 = max(profitChange1)
print(type(newhope1))
totalProfit = sum(something1)
csvpath = os.path.join('excelBank.csv')
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
data = list(csvreader)
row_count = len(data)
rowcount = row_count - 1
for line in csvreader:
print("printing line 1")
print(line[1])
print(f"Number of Months: {rowcount} months")
print(f"Total Profits over time: ${totalProfit}")
avgProfit = round(totalProfit/rowcount, 2)
print(f"Average Profits: ${avgProfit}")
print(f"Greatest Increase in Profits: ${gtIncrease}")
print(f"Greatest Decrease in Profits: ${gtDecrease}")
# with open(csvpath, 'w') as wf:
# for line in wf:
# wf.write(line)
# print("printing line 1")
summary_df = pd.DataFrame({ "Total Months": [rowcount],
"Total Profits": [totalProfit],
"Average profit": avgProfit,
"Greatest Increase": gtIncrease,
"Greatest Decrease": gtDecrease})
print(summary_df)
summary_df.to_csv("outputPracticelist.csv", index=False)
#print(summary_df,file=open("something.txt","w"))
|
561d45623fc3f1cae045c17dc8098ae678d2bf51 | LucianErick/URI | /matematica/Area.py | 374 | 3.8125 | 4 | a, b, c = input().split(" ")
a = float (a)
b = float (b)
c = float (c)
pi=float (3.14159)
aTriangulo=(a*c)/2
aCirculo=pi*(c*c)
aTrapezio=((a+b)*c)/2
aQuadrado=b*b
aRetangulo=a*b
print("TRIANGULO: ""%.3f"%(aTriangulo))
print("CIRCULO: ""%.3f"%(aCirculo))
print("TRAPEZIO: ""%.3f"%(aTrapezio))
print("QUADRADO: ""%.3f"%(aQuadrado))
print("RETANGULO: ""%.3f"%(aRetangulo))
|
1733473895bfd9f927d1b50eb194e02ba115181f | Abhipsanayak92/Python--Support-Vector-Machine-SVM- | /Risk Analytics-SVM - Revised.py | 5,382 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
# In[2]:
#loading training and test data
train_data=pd.read_csv(r'D:\DATA SCIENCE DOCS\Python docs\risk_analytics_train.csv',header=0)
test_data=pd.read_csv(r'D:\DATA SCIENCE DOCS\Python docs\risk_analytics_test.csv', header=0)
# **Preprocessing the training dataset**
# In[3]:
print(train_data.shape)
train_data.head()
# In[4]:
#finding the missing values
print(train_data.isnull().sum())
#print(train_data.shape)
# In[5]:
#imputing categorical missing data with mode value
colname1=["Gender","Married","Dependents","Self_Employed", "Loan_Amount_Term"]
for x in colname1:
train_data[x].fillna(train_data[x].mode()[0],inplace=True)
# In[6]:
print(train_data.isnull().sum())
# In[7]:
#imputing numerical missing data with mean value
train_data["LoanAmount"].fillna(train_data["LoanAmount"].mean(),inplace=True)
print(train_data.isnull().sum())
# In[8]:
#imputing values for credit_history column differently
train_data['Credit_History'].fillna(value=0, inplace=True)
#train_data['Credit_History']=train_data['Credit_History'].fillna(value=0)
print(train_data.isnull().sum())
# In[9]:
train_data.Credit_History.mode()
# In[10]:
#transforming categorical data to numerical
from sklearn import preprocessing
colname=['Gender','Married','Education','Self_Employed','Property_Area',
'Loan_Status']
#le={}
le=preprocessing.LabelEncoder()
for x in colname:
train_data[x]=le.fit_transform(train_data[x])
#converted Loan status as Y-->1 and N-->0
# In[11]:
train_data.head()
# **Preprocessing the testing dataset**
# In[12]:
test_data.head()
# In[13]:
#finding the missing values
print(test_data.isnull().sum())
print(test_data.shape)
# In[14]:
#imputing missing data with mode value
colname1=["Gender","Dependents","Self_Employed", "Loan_Amount_Term"]
for x in colname1:
test_data[x].fillna(test_data[x].mode()[0],inplace=True)
# In[15]:
print(test_data.isnull().sum())
# In[16]:
#imputing numerical missing data with mean value
test_data["LoanAmount"].fillna(test_data["LoanAmount"].mean(),inplace=True)
print(test_data.isnull().sum())
# In[17]:
#imputing values for credit_history column differently
test_data['Credit_History'].fillna(value=0, inplace=True)
print(test_data.isnull().sum())
# In[18]:
#transforming categorical data to numerical
from sklearn import preprocessing
colname=['Gender','Married','Education','Self_Employed','Property_Area']
#le={}
le=preprocessing.LabelEncoder()
for x in colname:
test_data[x]=le.fit_transform(test_data[x])
# In[19]:
test_data.head()
# **Creating training and testing datasets and running the model**
# In[23]:
X_train=train_data.values[:,1:-1]
Y_train=train_data.values[:,-1]
Y_train=Y_train.astype(int)
# In[24]:
#test_data.head()
X_test=test_data.values[:,1:]
# In[25]:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train) #fit() should be used on training data only
#transform() should be used on both training and testing data
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# In[26]:
from sklearn import svm
svc_model=svm.SVC(kernel='rbf',C=1.0,gamma=0.1)
#svc- support vector classifier
#svr- support vector regression
#from sklearn.linear_model import LogisticRegression
#svc_model=LogisticRegression()
svc_model.fit(X_train, Y_train)
Y_pred=svc_model.predict(X_test)
print(list(Y_pred))
# In[27]:
Y_pred_col=list(Y_pred)
#print(Y_pred_col)
# In[28]:
test_data=pd.read_csv(r'D:\DATA SCIENCE DOCS\Python docs\risk_analytics_test.csv',header=0)
test_data["Y_predictions"]=Y_pred_col
test_data.head()
# In[ ]:
test_data.to_csv('test_data.csv')
# In[35]:
#Using cross validation
from sklearn.linear_model import LogisticRegression
classifier=(LogisticRegression()) #output is 77.2%
#here logistic reg gave best accuracy than svm
#svm gave accuracy 75% without any tuning and using default value
#but after tuning it gave 77.02% which is less than log regression accuracy
#hence log regression outperforms for binary values
#we cant keep on increasing C and gamma value drastically bcz it may lead to misclassification
#classifier=svm.SVC(kernel="rbf",C=1.0,gamma=0.1) #output is 75.89% #default value of gamma and C
#classifier=svm.SVC(kernel="rbf",C=10.0,gamma=0.001) # output is 77.03
#classifier=svm.SVC(kernel="linear",C=10.0,gamma=0.001) # output is 77.03
#classifier=svm.SVC(kernel="poly",C=10.0,gamma=0.001) # output is 68.73
#performing kfold_cross_validation
from sklearn.model_selection import KFold
kfold_cv=KFold(n_splits=10)
print(kfold_cv)
from sklearn.model_selection import cross_val_score
#running the model using scoring metric as accuracy
kfold_cv_result=cross_val_score(estimator=classifier,X=X_train, y=Y_train, cv=kfold_cv)
print(kfold_cv_result)
#finding the mean
print(kfold_cv_result.mean())
"""
for train_value, test_value in kfold_cv.split(X_train):
classifier.fit(X_train[train_value], Y_train[train_value]).predict(X_train[test_value])
Y_pred=classifier.predict(X_test)
#print(list(zip(Y_test,Y_pred)))
"""
# In[ ]:
# In[ ]:
for x in range(0,len(Y_pred_col)):
if Y_pred_col[x]==0:
Y_pred_col[x]= "N"
else:
Y_pred_col[x]="Y"
print(Y_pred_col)
|
3570b65aefcb633ceac9492ade3684753136754b | andreboa-sorte/Python-aula-2 | /ex2.py | 699 | 3.9375 | 4 | class Extenso():
def chama_extenso(self):
num=int(input('digite um numero entre 1 a 5, para se tornar extenso: '))
if num==1:
print("Um")
elif num==2:
print("Dois")
elif num==3:
print("Tres")
elif num==4:
print("Quatro")
elif num==5:
print("Cinco")
elif num>5:
print('numero invalido')
elif num<1:
print('numero invalido')
chama=Extenso()
menu=True
while menu:
op=int(input('\n1- digitar numero \n'
'2- sair \n'
'opção: '))
if op==1:
chama.chama_extenso()
elif op==2:
menu=False
|
2ca59c63aa5f64b6e36046013a714031423e4073 | fagan2888/personal_learning | /coursera_interactive_python/03 Assignment.py | 1,620 | 3.734375 | 4 | """ Template for 'Stopwatch: The Game' """
import simplegui
# define global variables
t = 0
position_timer = [60, 100]
position_score = [210, 30]
width = 250
height = 200
x = 0
y = 0
# define helper function format that converts time split
# into minutes, seconds and tenths of a second.
# Formatted string in the form A:BC.D
def format(t):
A = 0
B = 0
C = 0
D = t
if t >= 10:
C = t / 10
D = t % 10
elif C >= 10:
B = C / 10
C = C % 10
elif B >= 6:
A = B / 6
B = B % 6
return "0" + str(A) + ":" + str(B) + str(C) + "." + str(D)
# define event handlers for buttons; "Start", "Stop", "Reset"
def output():
global t
t += 1
return format(t)
def start():
timer.start()
output()
def stop():
timer.stop()
global x
global y
if t % 10 == 0:
x = x + 1
y = y + 1
else:
x
y = y + 1
def reset():
timer.stop()
global t
global x
global y
x = 0
y = 0
t = 0
return format(t)
# define event handler for timer with 0.1 sec interval
timer = simplegui.create_timer(100, output)
# define draw handler
def draw(canvas):
canvas.draw_text(format(t), position_timer, 50, "Yellow")
canvas.draw_text(str(x) + "/" + str(y), position_score, 30, "Orange")
# create frame
frame = simplegui.create_frame("Stopwatch: The Game", width, height)
frame.set_draw_handler(draw)
frame.add_button("Start", start, 100)
frame.add_button("Stop", stop, 100)
frame.add_button("Reset", reset, 100)
#frame.set_draw_handler(draw)
frame.start()
|
14df96169cb902b42e309adc428e246b49e28a40 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/837.py | 575 | 3.546875 | 4 | def flip(pancake, start, size):
for j in xrange(start, start + size):
pancake[j] = 1 - pancake[j]
def countflip(pancake, size):
pancake = [(1 if p == "+" else 0) for p in pancake]
N = len(pancake) - size
flips = 0
for i in xrange(0, N + 1):
if pancake[i] == 0:
flip(pancake, i, size)
flips += 1
if all(p for p in pancake[N:]):
return str(flips)
return "IMPOSSIBLE"
for t in xrange(input()):
pancake, size = raw_input().split()
print "Case #%d: %s" % (t + 1, countflip(pancake, int(size)))
|
4d29b62a0345545285ce369be3530de0481e61b4 | JoaoPedroBarros/exercicios-antigos-de-python | /Exercícios/Exercícios Mundo 1/ex032.py | 162 | 3.921875 | 4 | a = int(input('Digite um número:'))
if a%4 == 0 and a%400 == 0 or a%100 != 0:
print('Esse é um ano bissexto.')
else:
print('Esse ano não é bissexto')
|
cbd5d31d33f171e19aea751ab40380f8b35fb058 | lobzison/python-stuff | /PoC/fiftheen_puzzle.py | 17,701 | 3.546875 | 4 | """
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
# import poc_fifteen_gui
class Puzzle:
"""
Class representation for the Fifteen puzzle
"""
def __init__(self, puzzle_height, puzzle_width, initial_grid=None):
"""
Initialize puzzle with default height and width
Returns a Puzzle object
"""
self._height = puzzle_height
self._width = puzzle_width
self._grid = [[col + puzzle_width * row
for col in range(self._width)]
for row in range(self._height)]
if initial_grid is not None:
for row in range(puzzle_height):
for col in range(puzzle_width):
self._grid[row][col] = initial_grid[row][col]
self._moves_dict = {"down": {"down": "u", "right": "ullddru",
"left": "dru", "up": "lddru"},
"left": {"down": "lur", "right": "ulldr",
"left": "r", "up": "ldr"},
"right": {"down": "luurrdl", "right": "l",
"left": "urrdl", "up": "rdl"}}
self._moves_dict_row0 = {"down": {"down": "u", "right": "dlu",
"left": "dru", "up": "lddru"},
"left": {"down": "lur", "right": "ulldr",
"left": "r", "up": "ldr"},
"right": {"down": "rul", "right": "l",
"left": "drrul", "up": "rdl"}}
def __str__(self):
"""
Generate string representaion for puzzle
Returns a string
"""
ans = ""
for row in range(self._height):
ans += str(self._grid[row])
ans += "\n"
return ans
#####################################
# GUI methods
def get_height(self):
"""
Getter for puzzle height
Returns an integer
"""
return self._height
def get_width(self):
"""
Getter for puzzle width
Returns an integer
"""
return self._width
def get_number(self, row, col):
"""
Getter for the number at tile position pos
Returns an integer
"""
return self._grid[row][col]
def set_number(self, row, col, value):
"""
Setter for the number at tile position pos
"""
self._grid[row][col] = value
def clone(self):
"""
Make a copy of the puzzle to update during solving
Returns a Puzzle object
"""
new_puzzle = Puzzle(self._height, self._width, self._grid)
return new_puzzle
########################################################
# Core puzzle methods
def current_position(self, solved_row, solved_col):
"""
Locate the current position of the tile that will be at
position (solved_row, solved_col) when the puzzle is solved
Returns a tuple of two integers
"""
solved_value = (solved_col + self._width * solved_row)
for row in range(self._height):
for col in range(self._width):
if self._grid[row][col] == solved_value:
return (row, col)
assert False, "Value " + str(solved_value) + " not found"
def update_puzzle(self, move_string):
"""
Updates the puzzle state based on the provided move string
"""
zero_row, zero_col = self.current_position(0, 0)
for direction in move_string:
if direction == "l":
assert zero_col > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col - 1]
self._grid[zero_row][zero_col - 1] = 0
zero_col -= 1
elif direction == "r":
assert zero_col < self._width - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col + 1]
self._grid[zero_row][zero_col + 1] = 0
zero_col += 1
elif direction == "u":
assert zero_row > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row - 1][zero_col]
self._grid[zero_row - 1][zero_col] = 0
zero_row -= 1
elif direction == "d":
assert zero_row < self._height - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row + 1][zero_col]
self._grid[zero_row + 1][zero_col] = 0
zero_row += 1
else:
assert False, "invalid direction: " + direction
##################################################################
# Phase one methods
def lower_row_invariant(self, target_row, target_col, ignore_zero=False):
"""
Check whether the puzzle satisfies the specified invariant
at the given position in the bottom rows of the puzzle (target_row > 1)
Returns a boolean
"""
if not ignore_zero:
zero_in_pos = self.get_number(target_row, target_col) == 0
else:
zero_in_pos = True
lower_rows = True
righter_cells = True
if target_row != self.get_height() - 1:
for rows in range(target_row + 1, self.get_height()):
for cols in range(self.get_width()):
check = self.current_position(rows, cols) == (rows, cols)
lower_rows = lower_rows and check
if target_col != self.get_width() - 1:
for cols in range(target_col, self.get_width()):
check = self.current_position(target_row, cols) == (target_row,
cols)
righter_cells = righter_cells and check
return zero_in_pos and lower_rows
def solve_interior_tile(self, target_row, target_col):
"""
Place correct tile at target position
Updates puzzle and returns a move string
"""
assert self.lower_row_invariant(target_row, target_col), (
"lower_row_invariant failed at %d %d" % (target_row, target_col))
# find where the target tail is, move zero to that position
target_pos = self.current_position(target_row, target_col)
res = self.move_to_target_out((target_row, target_col), target_pos)
current_pos, z_diff = self.update_data(target_row,
target_col)
while not (current_pos[0] == target_row and
current_pos[1] == target_col):
# move to left first, set correct column, set correct row
res += self.position_tile(current_pos, z_diff, target_row,
target_col)
current_pos, z_diff = self.update_data(target_row,
target_col)
# move 0 to correct position
if self.zero_to_target(z_diff) == "up":
res += "ld"
self.update_puzzle("ld")
assert self.lower_row_invariant(target_row, target_col - 1), (
"lower_row_invariant failed at %d %d" % (target_row,
target_col - 1))
return res
def move_to_target_out(self, zero_coord, target_coord):
"""
Moves zero tile to target tile.
Returns stirng with moves
"""
res = ""
ups = zero_coord[0] - target_coord[0]
lefts = zero_coord[1] - target_coord[1]
if target_coord[1] > zero_coord[1] and ups > 0:
res += "u"
ups -= 1
if lefts > 0:
res += "l" * lefts
else:
res += "r" * -lefts
res += "u" * ups
self.update_puzzle(res)
return res
def position_tile(self, current_pos, z_diff, target_row,
target_col, row0=False):
"""
Do one step in direction of target
"""
res = ""
if row0:
moves = self._moves_dict_row0
else:
moves = self._moves_dict
if current_pos[1] == 0:
res += moves["right"][self.zero_to_target(z_diff)]
elif current_pos[1] != target_col:
if current_pos[1] > target_col:
# print "moving to left"
print z_diff
res += moves["left"][self.zero_to_target(z_diff)]
else:
# print "moving to right"
res += moves["right"][self.zero_to_target(z_diff)]
else:
# print "moving down"
res += moves["down"][self.zero_to_target(z_diff)]
print self, res
self.update_puzzle(res)
return res
def zero_to_target(self, z_diff):
"""
Returns where zero tile is
with respect to target tile
"""
res = None
if z_diff[0] == 0:
if z_diff[1] == 1:
res = "right"
if z_diff[1] == -1:
res = "left"
elif z_diff[1] == 0:
if z_diff[0] == -1:
res = "up"
if z_diff[0] == 1:
res = "down"
return res
def update_data(self, target_row, target_col, current=None):
"""
Updates data about tiles, and returns curren position and difference
"""
if current is None:
current_pos = self.current_position(target_row, target_col)
else:
current_pos = current
zero_pos = self.current_position(0, 0)
z_row_diff = zero_pos[0] - current_pos[0]
z_col_diff = zero_pos[1] - current_pos[1]
z_diff = [z_row_diff, z_col_diff]
return current_pos, z_diff
def solve_col0_tile(self, target_row):
"""
Solve tile in column zero on specified row (> 1)
Updates puzzle and returns a move string
"""
assert self.lower_row_invariant(target_row, 0), (
"lower_row_invariant failed at %d %d" % (target_row, 0))
target_pos = self.current_position(target_row, 0)
res = self.move_to_target_out((target_row, 0), target_pos)
print self
# sould check different way
if not self.lower_row_invariant(target_row - 1,
self.get_width() - 1, True):
target_pos = self.current_position(target_row, 0)
current_pos, z_diff = self.update_data(target_row, 0)
while not (current_pos[0] == target_row - 1 and
current_pos[1] == 1):
# move to left first, set correct column, set correct row
res += self.position_tile(current_pos, z_diff,
target_row - 1, 1)
current_pos, z_diff = self.update_data(target_row, 0)
if self.zero_to_target(z_diff) == "up":
res += "ld"
self.update_puzzle("ld")
elif self.zero_to_target(z_diff) == "right":
res += "ulld"
self.update_puzzle("ulld")
# res += self.position_tile(target_row - 1, 1)
res += "ruldrdlurdluurddlur"
self.update_puzzle("ruldrdlurdluurddlur")
res += self.move_to_target_out(self.current_position(0, 0),
(target_row - 1, self.get_width() - 1))
assert self.lower_row_invariant(target_row - 1,
self.get_width() - 1), (
"lower_row_invariant failed at %d %d" % (target_row, 0))
print self, res
return res
#############################################################
# Phase two methods
def row0_invariant(self, target_col):
"""
Check whether the puzzle satisfies the row zero invariant
at the given column (col > 1)
Returns a boolean
"""
zero_in_pos = self.get_number(0, target_col) == 0
cell_check = self.current_position(1, target_col) == (1, target_col)
check_rows = self.lower_row_invariant(1, target_col, True)
return zero_in_pos and cell_check and check_rows
def row1_invariant(self, target_col):
"""
Check whether the puzzle satisfies the row one invariant
at the given column (col > 1)
Returns a boolean
"""
return self.lower_row_invariant(1, target_col)
def solve_row0_tile(self, target_col):
"""
Solve the tile in row zero at the specified column
Updates puzzle and returns a move string
"""
assert self.row0_invariant(target_col), (
"lower_row_invariant failed at %d %d" % (0, target_col))
target_pos = self.current_position(0, target_col)
res = self.move_to_target_out((0, target_col), target_pos)
# sould check different way
if not (0, target_col) == self.current_position(0, target_col):
target_pos = self.current_position(0, target_col)
current_pos, z_diff = self.update_data(0, target_col)
while not (current_pos[0] == 1 and
current_pos[1] == target_col - 1):
# move to left first, set correct column, set correct row
print self
if current_pos[0] == 0:
row0 = True
else:
row0 = False
res += self.position_tile(current_pos, z_diff,
1, target_col - 1, row0)
current_pos, z_diff = self.update_data(0, target_col)
if self.zero_to_target(z_diff) == "up":
res += "ld"
self.update_puzzle("ld")
# res += self.position_tile(target_row - 1, 1)
res += "urdlurrdluldrruld"
self.update_puzzle("urdlurrdluldrruld")
else:
res += 'd'
self.update_puzzle("d")
print self
assert self.row1_invariant(target_col - 1), (
"lower_row_invariant failed at %d %d" % (1, target_col - 1))
return res
def solve_row1_tile(self, target_col):
"""
Solve the tile in row one at the specified column
Updates puzzle and returns a move string
"""
assert self.row1_invariant(target_col), (
"lower_row_invariant failed at %d %d" % (1, target_col))
target_pos = self.current_position(1, target_col)
res = self.move_to_target_out((1, target_col), target_pos)
current_pos, z_diff = self.update_data(1, target_col)
if not (1, target_col) == self.current_position(1, target_col):
target_pos = self.current_position(1, target_col)
current_pos, z_diff = self.update_data(1, target_col)
while not (current_pos[0] == 1 and
current_pos[1] == target_col):
# move to left first, set correct column, set correct row
res += self.position_tile(current_pos, z_diff,
1, target_col)
current_pos, z_diff = self.update_data(1, target_col)
if self.zero_to_target(z_diff) != "up":
if self.zero_to_target(z_diff) == "left":
res += "ur"
self.update_puzzle("ur")
return res
###########################################################
# Phase 3 methods
def solve_2x2(self):
"""
Solve the upper left 2x2 part of the puzzle
Updates the puzzle and returns a move string
"""
assert self.row1_invariant(1), (
"row1_invariant failed at %d" % (1))
res = "lu"
self.update_puzzle("lu")
print self, res
while not ((0, 1) == self.current_position(0, 1) and
(1, 0) == self.current_position(1, 0) and
(1, 1) == self.current_position(1, 1)):
res += 'rdlu'
self.update_puzzle("rdlu")
return res
def solve_puzzle(self):
"""
Generate a solution string for a puzzle
Updates the puzzle and returns a move string
"""
# solve all but top 2 rows
res = ""
zero_coord = self.current_position(0, 0)
z_diff0 = (self.get_height() - 1) - zero_coord[0]
z_diff1 = (self.get_width() - 1) - zero_coord[1]
if z_diff0 > 0:
res += "d" * z_diff0
else:
res += "u" * -z_diff0
if z_diff1 > 0:
res += "r" * z_diff1
else:
res += "l" * -z_diff1
self.update_puzzle(res)
for row in range(self.get_height() - 1, 1, -1):
for col in range(self.get_width() - 1, -1, -1):
if col != 0:
res += self.solve_interior_tile(row, col)
else:
res += self.solve_col0_tile(row)
for col in range(self.get_width() - 1, 1, -1):
for row in range(1, -1, -1):
if row != 0:
res += self.solve_row1_tile(col)
else:
res += self.solve_row0_tile(col)
res += self.solve_2x2()
return res
# Start interactive simulation
# poc_fifteen_gui.FifteenGUI(Puzzle(4, 4))
|
6776d476626f4e22c46a3f88f690cd43afb5f4ba | MarceloFilipchuk/CS50-PSET6-Cash | /cash.py | 1,143 | 4.3125 | 4 | # Prints the minimum possible ammount of coins needed to give in change
def main():
# Prompts the user for change
try:
change = float(input("Change owed:"))
while change <= 0:
change = float(input("Change owed:"))
except ValueError as err1:
print(err1)
print("Insert only float numbers!")
main()
# Performs the 'greedy' program
coins = 0
# Turns the change into cents
cents = change * 100
cents = int(round(cents))
# Checks if the change is major or equal than 25 cents
if cents >= 25:
coins = coins + int(cents / 25)
cents = cents % 25
# Checks if the change is major or equal than 10 cents
if cents >= 10:
coins = coins + int(cents / 10)
cents = cents % 10
# Checks if the change is major or equal than 5 cents
if cents >= 5:
coins = coins + int(cents / 5)
cents = cents % 5
# Checks if the change is major or equal than 5 cents
if cents >= 1:
coins = coins + int(cents / 1)
cents = cents % 1
return print(coins)
if __name__ == "__main__":
main() |
2ae2cab47c90f804b8790a777de864eb00cff7e5 | malvina-s/Daily-Python-Challenges | /Day 11_option2 | 426 | 3.796875 | 4 | #!/python3
#Maximum integer
import random as r
list = []
for i in range(1,101):
list.append(i)
number = r.choice(list)
counter = 0
print (number)
for i in range(1,100):
x = r.choice(list)
if x>number:
number = x
counter += 1
print (x, ' <== Update')
else:
print (x)
print ("The maximun value found was ",number)
print ("The maximum value was updated ",counter, 'times')
|
914ac56e5ca7fe4b61b38bb64faa34b6802fa3f8 | samyhkim/algorithms | /498 - diagonal traverse.py | 856 | 4.21875 | 4 | def find_diagonal_order(mat):
if not mat:
return
diagonal_order = []
lookup = {}
# Step 1: Numbers are grouped by the diagonals.
# Numbers in same diagonal have same value of row+col
for i in range(len(mat)):
for j in range(len(mat[0])):
if i + j in lookup:
lookup[i + j].append(mat[i][j])
else:
lookup[i + j] = [mat[i][j]]
# Step 2: Place diagonals in the result list.
# But remember to reverse numbers in even keys
for key in sorted(lookup.keys()):
if key % 2 == 0:
lookup[key].reverse()
# append(lookup[key]) returns [[1], [2, 4], [7, 5, 3], [6, 8], [9]]
diagonal_order += lookup[key]
return diagonal_order
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(find_diagonal_order(matrix))
|
60de6873ed44aced92b27254dcdec42512aceacc | nagask/leetcode-1 | /30 Substring with Concatenation of All Words/sol.py | 2,592 | 3.890625 | 4 | """
String not empty, words can be repeated.
Brute force: create all the permutations of the words array, and check if any of them is a substring.
Use a sliding window and two data structure to support the algorithm:
- a dictionary to count the appearances of each item of words
- another dictionary to count the appearances of each item of words in the current substring.
Let N be the number of strings in words, and k the length of each string, left the left part of the window and right the right part.
The window can start at any point of the string, so left will try all the indexes between 0 and len(s) - number_of_words * single_word_size (after that there would be no space for a substring).
For every left index, we try to build a substring containing all the words:
- if we meet a word in the string that is not part of the array of words, we can abort the current iteration and go to the next left index
- if we find too many times a word, we can abort the current iteration and go to the next left index
- if we arrive to consume all the words in the words array, we found a solution!
O(N + M) space, where M is the lenght of the main string (the size of the result can be O(M))
O(N * M * k)
"""
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
def get_counters(words):
counters = {}
for word in words:
if word not in counters:
counters[word] = 0
counters[word] += 1
return counters
def add_to_solution(word, current_solution):
if word not in current_solution:
current_solution[word] = 0
current_solution[word] += 1
counters = get_counters(words)
number_of_words = len(words)
single_word_size = len(words[0])
result = []
left = 0
right = single_word_size
for left in range(len(s) - number_of_words * single_word_size + 1):
current_solution = {} # keeps the counters of the current solution
for right in range(number_of_words):
next_word_index = left + right * single_word_size
word = s[next_word_index: next_word_index + single_word_size]
if word not in counters:
break
add_to_solution(word, current_solution)
if current_solution[word] > counters[word]:
break
if right + 1 == number_of_words:
result.append(left)
return result |
3467326f13cc02c121b7ecc9984002dff0ddbd05 | KatherineSandys/Python | /Web Page Reloader/auto time.py | 3,240 | 4.125 | 4 | """
Program to auto fill in time sheets
Ideas
-Add Task Number to Questions
-Add Project number to the Questions
-Change order of questions.
-Questions on a form instead of indiviual
-Save the pervious answers to a file
-load those pervious answers when starting program so you can just skip items with the correct answer
-Look at the screen to make sure the right box is up before clicking. Sometimes the computer is slower then the delays allow.
"""
import pyautogui, sys
import time
#DEFULTS
year = 2020
hours = 8
task_number = '386'
projectID = 'INP-1528'
#get month
month = pyautogui.prompt(text='Enter what month you want(1-12): ', title='Month' , default='')
#month = int(input("Enter what month you want(1-12): "))
#day that the month starts on
start = int(pyautogui.prompt(text="Enter the day to start with: ", title="Starting Day"))
#get how many days
days = int(pyautogui.prompt(text="Enter the number of days to fill in: ", title='Days'))
#get the task number
#task_number = pyautogui.prompt(text="Enter the task number: ", title='Task #')
#get the projectID
#projectID = pyautogui.prompt(text="Enter the project ID: ", title='Project ID')
time.sleep(5) #time to get back to screen
#repeat for the number of days in the month
for nextday in range(start, (start+days)):
pyautogui.moveTo(16,185) # opens new tracking
time.sleep(0.1)
pyautogui.click()
time.sleep(4)
pyautogui.moveTo(230,275) #click on place to fill date
time.sleep(.1)
pyautogui.click()
time.sleep(.1)
#set date - month + "/" + 1 + "/" + year
pyautogui.write(str(month) +"/"+ str(nextday) +"/"+ str(year))
pyautogui.press('tab')
time.sleep(.1)
pyautogui.moveTo(214,481) #click on place to create new task
pyautogui.click()
time.sleep(1)
#set the task number
pyautogui.write(task_number)
time.sleep(.1)
#tab to get to hours- 6 times
for i in range(0, 4):
pyautogui.press('tab')
time.sleep(0.5)
#set the hours- 8
pyautogui.write('8')
time.sleep(.1)
#tab to get to project ID - 3 times
for i in range(0, 2):
pyautogui.press('tab')
time.sleep(0.5)
#set project ID
pyautogui.write(projectID)
time.sleep(.1)
#to save changes - 2 times
pyautogui.moveTo(51,189) #click on place to save
time.sleep(.1)
pyautogui.click()
time.sleep(.1)
pyautogui.click()
#aprove part
time.sleep(2)
pyautogui.moveTo(280,189) #click to unlock
pyautogui.click()
time.sleep(1)
pyautogui.moveTo(110,450) #click to signoff
pyautogui.click()
time.sleep(.5)
pyautogui.moveTo(520,620) #click to Vote Now
pyautogui.click()
time.sleep(2)
pyautogui.moveTo(1235,445) #click to Complete check box
pyautogui.click()
time.sleep(.1)
pyautogui.moveTo(750,660) #click to Vote
pyautogui.click()
time.sleep(.1)
pyautogui.write('c')
pyautogui.press('enter')
time.sleep(.1)
pyautogui.moveTo(860,815) #click to Complete
pyautogui.click()
time.sleep(5)
pyautogui.alert(text = 'Done!', title='Complete')
|
4500116c792db03d0996c438cdfc745586619055 | Divisekara/Python-Codes-First-sem | /PA2/PA2 2013/PA2-3/2013 - CA - 03 - Vowels/2013 - CA - 03 - Vowels.py | 809 | 3.765625 | 4 | #CA -
def getText():
#To get text from input and check for any errors.
try:
fileOpen=open("FileIn.txt","r")
words=fileOpen.read().plit()
fileOpen.close()
except IOError:
print "File Error!"
else:
def show(output):
#To print the output on screen as well as write to a file.
print output
try:
fileWrite=open("Result.txt","w")
fileWrite.write(output)
fileWrite.close()
except IOError:
print "File Error!"
run = getText() #To call functions in a global level
if run!=None:
show(run)
|
31ac1276e9a1517e0e5a47300c2c77b66f03c315 | janakimeena/Python_Code | /Ganesha_Papa.py | 2,338 | 3.859375 | 4 | import turtle
screen = turtle.Screen()
screen.setup(width=1.0, height=1.0)
def move_To(x,y):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
turtle.speed(15)
turtle.pensize(7)
turtle.showturtle()
turtle.bgcolor("black")
# three lines
turtle.pencolor("white")
move_To(-36,200)
turtle.forward(30)
move_To(-36,190)
turtle.forward(30)
move_To(-36,180)
turtle.forward(30)
#Fore head
turtle.pencolor("white")
move_To(-60,165)
turtle.right(90)
turtle.left(15)
turtle.forward(10)
turtle.right(15)
turtle.forward(15)
turtle.right(15)
turtle.forward(10)
turtle.left(15)
turtle.right(165)
turtle.forward(10)
turtle.right(15)
turtle.forward(15)
turtle.right(15)
turtle.forward(10)
turtle.left(15)
turtle.pencolor('red')
move_To(5,188)
for i in range(12):
turtle.forward(2)
turtle.left(30)
turtle.pencolor("white")
move_To(-20,-180)
turtle.left(90)
for i in range(7):
turtle.right(20)
turtle.forward(20)
turtle.forward(10)
turtle.left(5)
turtle.forward(5)
turtle.left(5)
turtle.forward(10)
turtle.left(5)
turtle.forward(15)
turtle.left(30)
turtle.forward(10)
turtle.left(5)
turtle.forward(10)
for i in range(2):
turtle.left(20)
turtle.forward(6)
turtle.right(20)
turtle.forward(60)
turtle.left(100)
turtle.forward(20)
for i in range(8):
turtle.right(20)
turtle.forward(1)
turtle.forward(20)
turtle.left(50)
turtle.forward(30)
for i in range(4):
turtle.left(20)
turtle.forward(10)
turtle.forward(20)
turtle.left(95)
turtle.forward(50)
turtle.right(155)
###
turtle.forward(200)
turtle.right(120)
turtle.forward(160)
for i in range(4):
turtle.right(20)
turtle.forward(15)
turtle.forward(25)
turtle.right(30)
turtle.forward(5)
turtle.left(72)
#turtle.forward(150)
move_To(47,-130)
turtle.left(15)
for i in range(7):
turtle.right(30)
turtle.forward(10)
turtle.left(8)
for i in range(4):
turtle.right(24)
turtle.forward(20)
for i in range(3):
turtle.left(20)
turtle.forward(25)
turtle.left(10)
turtle.forward(173)
'''crown'''
turtle.pencolor('orange')
turtle.pensize(10)
move_To(-100, 243)
turtle.left(70)
turtle.forward(60)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(120)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(60)
move_To(-110, 286)
turtle.pensize(32)
turtle.left(60)
turtle.forward(40)
turtle.left(120)
turtle.forward(60)
turtle.left(120)
turtle.forward(60)
turtle.done() |
57b45bdd16157db291bf39ebfdb1f6ba52eb464b | SerhiiDemydov/HomeWork | /HW4/HW4_class.py | 1,943 | 4.125 | 4 | # 1. Create a Vehicle class with max_speed and mileage instance attributes
class Venicle:
def __init__(self, max_speed, mile):
self.max_speed = max_speed
self.mile = mile
# 2. Create a child class Bus that will inherit all of the variables and methods of the Vehicle class and will have seating_capacity own method
class Bus(Venicle):
def __init__(self, max_speed, mile, seating_capacity):
self.seating_capacity = seating_capacity
self.max_speed = max_speed
self.mile = mile
super().__init__(max_speed, mile)
def bus_capacity(self):
print(f'Capacity in bus = {self.seating_capacity}')
# 3. Determine which class a given Bus object belongs to (Check type of an object)
School_bus = Bus(30, 100, 36)
print(type(School_bus.max_speed))
print(type(School_bus.mile))
print(type(School_bus))
School_bus.bus_capacity()
print(issubclass(Bus, Venicle))
# 4. Determine if School_bus is also an instance of the Vehicle class
print(f'School_bus is an instance of Vehicle class - {isinstance(School_bus,Venicle)}')
# 5. Create a new class School with get_school_id and number_of_students instance attributes
class School:
def __init__(self, get_school_id, number_of_students):
self.get_school_id = get_school_id
self.number_of_students = number_of_students
#6*. Create a new class SchoolBus that will inherit all of the methods from School and Bus and will have its own - bus_school_color
class SchoolBus(School,Bus):
def __init__(self, get_school_id, number_of_students, max_speed, mile, seating_capacity, bus_school_color):
School.__init__(self, get_school_id, number_of_students)
Bus.__init__(self, max_speed, mile, seating_capacity)
self.bus_school_color = bus_school_color
Bus_number1 = SchoolBus(1235, 200, 90, 240, 35, 'yellow')
print(f'School number {Bus_number1.get_school_id} has {Bus_number1.bus_school_color} bus.')
|
90d6b6625832d09641bcb6f79063375e71d7275b | matey97/Programacion | /Boletín1/Ejercicio6.py | 191 | 3.921875 | 4 | '''
Created on 1 de oct. de 2015
@author: al341802
'''
from math import sqrt
a=float(input("Dame un número:"))
raiz= sqrt(a)
print("La raíz cuadrada del número es:{0:.3f}".format(raiz)) |
598f37dfae073811c1b0661ab036e591ca3a1954 | wabscale/bigsql | /bigsql/Query.py | 1,284 | 3.546875 | 4 | from . import Sql
class Query(object):
session=None
def __init__(self, table_name):
self.table_name = table_name if isinstance(table_name, str) else table_name.__name__
def all(self):
"""
Return all models for table
:return:
"""
return Sql.Sql.SELECTFROM(self.table_name).all()
def find(self, **conditions):
"""
similar to sqlalchemy's Sql.filter_by function
:param conditions: list of conditions to find objects
:return: Sql object
"""
return Sql.Sql.SELECTFROM(self.table_name).WHERE(**conditions)
def new(self, **values):
"""
creates and inserts new element of type self.table_name
:param values: key value dict for obj
:return: new instance of table model
"""
return Sql.Sql.INSERT(**values).INTO(self.table_name).do(raw=False)
def delete(self, **values):
"""
deletes object from dateabase
:param values:
:return:
"""
return Sql.Sql.DELETE(self.table_name).WHERE(**values).do()
def __getattr__(self, item):
"""
Gives back raw sql object
:return:
"""
return getattr(Sql.Sql.SELECTFROM(self.table_name), item)
|
6d73006fe0837bd02f31c1c052a805b911501374 | MaxIsWell42/CS-1.2-Intro-Data-Structures | /Code/histogram.py | 3,020 | 4.0625 | 4 | from pprint import pprint
import sys
import random
# histogram = {'one': 1, 'blue': 1, 'two': 1, 'fish': 4, 'red': 1}
# Helped by github.com/ysawiris
def stripWordPunctuation(word):
return word.strip("&.,()<>\"}{'~?!;*:[]-+/&—\n ")
def open_file(source_text):
#open and read file
f = open(source_text, 'r')
lines = f.read().split()
#split each word to be seperate
for line in lines:
line = stripWordPunctuation(line)
f.close()
#print(lines)
#print(line)
return lines
def histogram_dictionary(source_text):
#define our histogram
histogram = {}
#loop though our file_text and add text to our histogram
for text in source_text:
if text in histogram.keys():
histogram[text] += 1
else:
histogram[text] = 1
print(histogram)
return histogram
def unique_words(histogram):
unique_words = []
for word in histogram:
if word not in unique_words:
unique_words.append(word)
return unique_words
def frequency(word, histogram):
frequency = 0
for _ in histogram:
if _ == word:
frequency += 1
return frequency
# Attempt at optimization, trying to search by first letter so the code doesn't have to analyze every word
# for _ in histogram:
# word.split()
# if word[0] == _[0]:
# if _ == word:
# frequency += 1
# else:
# continue
if __name__ == "__main__":
source_text = 'harry_potterb1.txt'
histogram = histogram_dictionary(source_text)
text = open_file(source_text)
histogram_dictionary(text)
# Extra functions for different data structures, helped by github.com/anikamorris
# def file_or_string(source_text):
# file_data = ''
# if '.txt' in source_text:
# file = open(source_text, 'r')
# file_data = file.read()
# file.close()
# else:
# file_data = source_text
# return file_data
# def list_of_lists_histogram(source_text):
# words = []
# file_data = file_or_string(source_text)
# words = file_data.split()
# histogram = []
# for word in words:
# is_in_histogram = False
# for i in range(len(histogram)):
# if word == histogram[i][0]:
# histogram[i][1] += 1
# is_in_histogram = True
# if is_in_histogram == False:
# histogram.append([word, 1])
# return histogram
# def list_of_tuples_histogram(source_text):
# words = []
# file_data = file_or_string(source_text)
# words = file_data.split()
# histogram = []
# for word in words:
# is_in_histogram = False
# for i in range(len(histogram)):
# if word == histogram[i][0]:
# histogram[i] = (word, (histogram[i][1])+1)
# is_in_histogram = True
# if is_in_histogram == False:
# histogram.append((word, 1))
# return histogram
|
d6ef25a312ed55fbcb8221c11b810de412441501 | btv/project_euler | /problem_7/python/problem7_4.py | 456 | 3.984375 | 4 | #!/usr/bin/python3
import math
def is_prime(divided):
divisor = [3]
sqrt_divided = int(math.sqrt(divided))
while divisor[0] <= sqrt_divided:
if divided % divisor[0] == 0:
return False
divisor[0] += 2
return True
if __name__ == "__main__":
# using a list to store each int value
data = [1,0,3]
while data[0] < 10001:
if is_prime(data[2]):
data[0] += 1
data[1] = data[2]
data[2] += 2
print(data[1])
|
64273b94f1c92bd78849962e2ba04edea530cb20 | elanorigby/LoveYouLikeXO | /board.py | 1,500 | 3.734375 | 4 | # just draw the board
class Board:
def __init__(self):
self.wall = "+---+---+---+"
self.cells = "| {a} | {b} | {c} |"
self.rows = [
{'a': 1, 'b': 2, 'c': 3},
{'a': 4, 'b': 5, 'c': 6},
{'a': 7, 'b': 8, 'c': 9}]
def _part(self, row):
print(self.wall)
print(self.cells.format(**row))
def _edit(self, move, player):
for idx, row in enumerate(self.rows):
for key, val in row.items():
if val == move:
self.rows[idx][key] = player
def check(self):
# horizontal combos
for row in self.rows:
if all(val == row['a'] for val in row.values()):
return row['a']
# vertical combos
for char in 'abc':
if self.rows[0][char] == self.rows[1][char] == self.rows[2][char]:
return self.rows[0][char]
# diagonal combos \ & /
if (self.rows[0]['a'] == self.rows[1]['b'] == self.rows[2]['c']) or (self.rows[0]['c'] == self.rows[1]['b'] == self.rows[2]['a']):
return self.rows[1]['b']
else:
return None
def draw(self, *args):
if args:
move, player = args
self._edit(move, player)
for row in self.rows:
self._part(row)
print(self.wall)
if __name__=="__main__":
board = Board()
board.draw()
board.draw(2, 'X')
print(board.rows)
|
b45cec7d28e1e13ecf94d112343a56dbc9d2bc8e | creageng/lc2016 | /59_Spiral_Matrix_II.py | 1,229 | 3.8125 | 4 | # Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
# For example,
# Given n = 3,
# You should return the following matrix:
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n <= 0:
return []
matrix = [row[:] for row in [[0]*n] *n]
row_st = 0
row_end = n-1
col_st = 0
col_end = n-1
curr = 1
while True:
if curr > n*n:
break
for c in range(col_st, col_end+1):
matrix[row_st][c] = curr
curr += 1
row_st += 1
for r in range(row_st, row_end+1):
matrix[r][col_end] = curr
curr += 1
col_end -= 1
for c in range(col_end, col_st-1, -1):
matrix[row_end][c] = curr
curr += 1
row_end -= 1
for r in range(row_end, row_st-1, -1):
matrix[r][col_st] = curr
curr += 1
col_st += 1
return matrix
|
63273ade42c6ec0eb2136ef1e366bf5de8faf251 | prajwal60/ListQuestions | /learning/BasicQuestions/Qsn83.py | 405 | 4.125 | 4 | # Write a Python program to test whether all numbers of a list is greater than a certain number.
sample = [4,5,6,7,8,9,10]
mini = min(sample)
n = int(input('Enter any number '))
if mini > n:
print("All of them in list are greater")
else:
print('Some of them in list are smaller')
#Another Approach
sample2 = [4,5,6,7,8,9,10]
m = int(input('Enter any number'))
print(all(x>m for x in sample2)) |
e92d5f4f575c0162194b5914c436ba1fc94f5eda | SkaTommy/Pythongeek | /Lesson3/example3.py | 798 | 4.125 | 4 | # 3. Реализовать функцию my_func(),
# которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
#1.Принимает на ввод 3 позиционных аргумента
#2.Сравнивает между собой находя 2 наибольшие
#3.Возвращает сумму наибольших
arg1 = int(input("Введите первый аргумент: "))
arg2 = int(input("Введите второй аргумент: "))
arg3 = int(input("Введите третий аргумент: "))
def mySum(arg1, arg2, arg3):
nums = [arg1, arg2, arg3]
nums.sort(reverse=True)
return sum(nums[0:2])
print(mySum(arg1, arg2, arg3)) |
965d1b9e658e9c34347c447afb8edaed1f6486a7 | hammadhaleem/parser | /v3/TimeParser/classes/dayAndTime.py | 2,044 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils import *
class OpenTimesByDay(object):
"""Process the day. """
def __init__(self, day, lis):
self.day = day
self.times = lis
self.day_vector = [day]
def __str__(self):
return self.day
def __repr__(self):
return "<"+Utils().listToString(self.day_vector,",")[1:] + ":" + Utils().listToString(self.times,",")[1:] +">"
def sorted_times(self):
return sorted(self.times)
def add_day(self, day):
self.day_vector.append(day)
self.day_vector = sorted(self.day_vector)
def __eq__(self, other):
return sorted(self.times) == other.sorted_times()
def __lt__(self, other):
return int(self.day) < int(other.day)
def __gt__(self, other):
return int(self.day) > int(other.day)
def generate_day_sequence(self):
days = self.day_vector
day_set = []
for day in self.day_vector:
day_set.append(int(day))
day_set.append(7+ int(day))
day_set = list(set(day_set))
interval = []
old = day_set[0]
prev = None
for item in day_set:
if prev is not None and item - prev != 1 :
interval.append(range(old ,prev+1))
old = item
prev = item
prev = item
interval.append( range(old ,day_set.pop()+1))
day_set = []
for elem in interval:
day_set.append((len(elem), elem))
return sorted(day_set, reverse = True)
def minus_7(self, lis):
ret =[]
for i in lis:
if i - 7 >= 0 :
ret.append(i-7)
else:
ret.append(i)
return ret
def get_unique_days(self):
day_set = self.generate_day_sequence()
done = []
sets = []
for elem in day_set:
set_1 = set(done)
set_2 = set(self.minus_7(elem[1]))
if set_1.intersection(set_2):
pass
else:
done = done + self.minus_7(elem[1])
sets.append(self.minus_7(elem[1]))
return (sets , self.times)
class OpenTimes(object):
def __init__(self, time, days):
self.time = time
self.days = days
def __str__(self):
return self.time
def __repr__(self):
return "<" + self.time + + ":" + Utils().listToString(self.days,",")[1:] +">"
|
92862ae98c5d734a2677997a49b6d0a02f4e826a | fayyozbekk/Python-projects | /guessing_game/main.py | 3,296 | 3.5 | 4 | import csv
from random import randint
from os import path
def update_leaderboard(attempts, user_name):
if path.exists("leaderboard.csv"):
leaderboard_data_list = []
new_sorted_leaders = []
with open("leaderboard.csv", "r") as leaderboard:
leaderboard_data_list = [leader for leader in csv.DictReader(leaderboard)]
leaderboard_data_list.append({"user_name": user_name, "attempts": attempts})
users_with_scores = [(leader_data["user_name"], int(leader_data["attempts"])) for leader_data in
leaderboard_data_list]
users_with_scores.sort(key=lambda x: x[1])
for item in users_with_scores:
new_sorted_leaders.append({"user_name": item[0], "attempts": item[1]})
with open("leaderboard.csv", "w") as csv_data:
field_names = ["user_name", "attempts"]
leaderboard_writer = csv.DictWriter(csv_data, fieldnames=field_names)
leaderboard_writer.writeheader()
for leader_data in new_sorted_leaders[:10]:
leaderboard_writer.writerow(leader_data)
else:
with open("leaderboard.csv", "w") as csv_file:
field_names = ["user_name", "attempts"]
writer = csv.DictWriter(csv_file, fieldnames=field_names)
writer.writeheader()
writer.writerow({"user_name": user_name, "attempts": attempts})
def wants_play_again():
user_input = input("Do you want to play again type yes/no: ").strip().lower()
if user_input == "yes":
return True
else:
return False
def print_leaders():
if path.exists("leaderboard.csv"):
with open("leaderboard.csv", "r") as data_file:
leaders_data = csv.DictReader(data_file)
for item in leaders_data:
print(f"{item['user_name']} - {item['attempts']}")
def guess_number_game():
print_leaders()
random_number = randint(1, 100)
user_attempts = 0
print("-----------------------------")
print("Welcome to the guessing game!")
print("-----------------------------")
user_name = input("Enter your Name: ")
while user_attempts < 5:
print(random_number)
try:
user_guess = int(input("Guess an integer: "))
except ValueError:
print("Invalid input. Please enter only numbers")
continue
if user_guess == random_number:
update_leaderboard(user_attempts + 1, user_name)
print("You nailed it!")
if wants_play_again():
guess_number_game()
else:
break
elif user_guess > random_number:
print("Your guess is bigger than the answer")
user_attempts += 1
print(f"You have attempted {user_attempts} times \n")
elif user_guess < random_number:
print("Your guess is lower than the answer")
user_attempts += 1
print(f"You have attempted {user_attempts} times \n")
if user_attempts == 5:
update_leaderboard(user_attempts, user_name)
print("You lose :( \n You run out of your attempts")
if wants_play_again():
guess_number_game()
guess_number_game()
|
fb49c63e057ecc0a5f59f7bc9921f93cae05372b | bfish83/Python | /searchEngine.py | 3,670 | 3.734375 | 4 | # Barret Fisher
# barret.fisher@uky.edu
# CS115 Section 5
# 11-19-12
# Program 4: Search engine
# Purpose: Search database file to find URL's that match user search, and output
# results to webpage, and record data in secret file
# Preconditions: Inputs from user(name, database, search, case setting, webpage)
# Postconditions: Number of hits output, webpage created, name and search added
# to secret file
# secret
# Purpose: open secret.txt and output to secret.txt userids and searches
# Preconditions: Parameters userid, search
# Postconditions: outputs to secret.txt userids and searches
def secret(name, search):
outfile = open("secret.txt", "a")
print(name, file=outfile)
print(search, file=outfile)
outfile.close()
# outputline
# Purpose: To output to html file search hits with URL and hits bolded
# Preconditions: hits, database keywords, URL with keywords,
# search phrase, outputfile
# Postconditions: HTML file has table created/appended
def outputline(hits, tags, url, search, outfile):
if hits == 1:
print("<p align=center>", file=outfile)
print("<table border>", file=outfile)
print("<tr><th>Hit<th>URL</tr>", file=outfile)
print("<tr><td>", file=outfile)
tags = tags.replace(search, "<b>"+search+"</b>")
print(tags, file=outfile)
print("<td><a href=\"", url, "\" align=center>", url, "</a></tr>", file=outfile)
def main():
# get user inputs
print("Big Blue Search Engine")
name = input("Your user name? ")
data = input("Enter name of database file (.txt will be added): ")
search = input("Keyword string to search for: ")
results = input("Enter name for web page of results (extension of .htm will be added): ")
case = input("Do you want search to be case sensitive? (y or n) ")
# append name/search to secret file
secret(name, search)
# check database file
temp = data + ".txt"
try:
infile = open(temp, "r")
except IOError:
print("Cannot open", temp)
return
data = infile.readlines()
infile.close()
# create output html file
temp = results + ".htm"
outfile = open(temp, "w")
print(temp, "created")
print("<html>", file=outfile)
print("<title>Search Findings</title>", file=outfile)
print("<body>", file=outfile)
# make lowercase if user specified, put appropriate header on page
if case != "y":
search = search.lower()
data = [i.lower() for i in data]
print("<h2><p align=center>Search for \"", search, "\"</h2>", sep="", file=outfile)
else:
print("<h2><p align=center>Case Sensitive Search for \"", search, "\"</h2>", sep="", file=outfile)
# call outputline function for every search hit
hits = 0
for i in range(0, len(data), 2):
if search in data[i]:
hits += 1
outputline(hits, data[i], data[i + 1], search, outfile)
# if no hits (finish and close file)
if hits == 0:
print("0 hits")
print("<p align=center>", file=outfile)
print("<table border>", file=outfile)
print("<tr><td>", search, "<td> not found! </tr>", file=outfile)
print("</table>", file=outfile)
print("</body>", file=outfile)
print("</html>", file=outfile)
outfile.close()
# if hits (finish and close file)
else:
print(hits, "hit(s)")
print("</table>", file=outfile)
print("</body>", file=outfile)
print("</html>", file=outfile)
outfile.close()
main()
|
0d1e57cfe85dc3a5710d1c340d3fc7fb89270e8f | abantikatonny/Statistics-Codes | /Assignment 1/Question number 3.py | 2,557 | 3.6875 | 4 | import numpy as np
import pandas as pd
import scipy.stats
# import the data file
data = pd.read_csv('C:/hmm/courses/3rd semester/Special topics/Assignment 1/data_master.csv', delimiter=',')
# creating a database for US because it has the highest date_reported data
States_database = data[data['Country'] == 'United States of America']
date_range_for_States = list(States_database['Date_reported'])
filtered_date_list = []
for i_date in date_range_for_States:
if i_date[0] == '3' or i_date[0] == '4' or i_date[0] == '5' or i_date[0] == '6' or i_date[0] == '7' or i_date[0] == '8':
filtered_date_list.append(i_date)
def compute_correlation_coefficient(country1, country2):
"""
This function computes and returns the Pearson correlation coefficient between the daily new cases of the given
two countries.
param1 (string): The first country
:param country2: Second country
Returns:
float: Pearson correlation coefficient
"""
new_case_count_for_country1 = []
new_case_count_for_country2 = []
# Accumulating new case counts for country1
for temp_date in filtered_date_list:
data_for_temp_country = data[data['Country'] == country1]
data_for_temp_date = data_for_temp_country[data_for_temp_country['Date_reported'] == temp_date]
temp_new_case = list(data_for_temp_date['New_cases'])[0]
new_case_count_for_country1.append(temp_new_case)
for temp_date in filtered_date_list:
data_for_temp_country = data[data['Country'] == country2]
data_for_temp_date = data_for_temp_country[data_for_temp_country['Date_reported'] == temp_date]
temp_new_case = list(data_for_temp_date['New_cases'])[0]
new_case_count_for_country2.append(temp_new_case)
# Compute correlation coefficient
correlation_coefficient = scipy.stats.pearsonr(new_case_count_for_country1, new_case_count_for_country2)[0]
return round(correlation_coefficient, 4)
pairs_to_evaluate = [
['Australia', 'United States of America'],
['The United Kingdom', 'United States of America'],
['Brazil', 'United States of America'],
['India', 'United States of America'],
['Egypt', 'United States of America'],
['Viet Nam', 'United States of America'],
['Russian Federation', 'United States of America'],
['Italy', 'United States of America'],
]
for country1, country2 in pairs_to_evaluate:
print('Correlation coefficient for {} and {} is '.format(country1, country2), compute_correlation_coefficient(country1, country2))
|
49cf4cc3e37c4c98c6eaddebfe10c0b568b73332 | omuen/Muen-In-Python | /history/Test-Muen-20200123.py | 472 | 3.84375 | 4 | def check():
print(' *')
print(' *')
print('* *')
print(' *')
print('Happy New year')
def MerryChristmas(): ##Happy##
print(' *')
print(' ***')
print(' *****')
print('*******')
print(' *')
MerryChristmas()
print('_____________________________________________________________')
check()
x=input('write 1 or 2 ')
if x=='1':
check()
elif x=='2': ##Happy##
MerryChristmas()
else:
print('???')
|
45d8c01a543e57bc68ba185961653b22bdd8f10d | zhangye-bot/Python-W3school-100-problems | /Problem37.py | 341 | 3.796875 | 4 | print('请输入10个数字: ')
i = 0
number_list = []
while i < 10:
number = int(input("输入一个数字: "))
number_list.append(number)
i = i + 1
for i in range(0,len(number_list)):
print(number_list[i])
print('排列之后:')
number_list.sort()
for i in range(0,len(number_list)):
print(number_list[i])
|
cafeca9055858a2bcdbc73e2cc12cb219864be6c | malaikaandrade/Python | /Basico/Clase2/entradas (1).py | 461 | 3.9375 | 4 | print("Suma de dos numero")
num1 = input("Ingresa el primer número:")
num2 = input("Ingresa el segundo número:")
resul= num1 + num2
print(resul)
#en esta parte los esta tratando como cadenas y solo las esta concatenando, para que los pueda realmente sumar se tiene que convertir el dato a un entero
print("Suma de dos numero")
num1 = int(input("Ingresa el primer número:"))
num2 = int(input("Ingresa el segundo número:"))
resul= num1 + num2
print(resul)
|
45b1bb87545ff3044e548b898ef8b8782576ac87 | GlobalYZ/recruitmentDjango | /pythonBasis/lesson_02_Python入门/06.格式化字符串.py | 1,290 | 4.09375 | 4 | # 格式化字符串
a = 'hello'
# 字符串之间也可以进行加法运算
# 如果将两个字符串进行相加,则会自动将两个字符串拼接为一个
a = 'abc' + 'haha' + '哈哈'
# a = 123
# 字符串只能不能和其他的类型进行加法运算,如果做了会出现异常 TypeError: must be str, not int
# print("a = "+a) # 这种写法在Python中不常见
a = 123
# print('a =',a)
# 在创建字符串时,可以在字符串中指定占位符
# %s 在字符串中表示任意字符
# %f 浮点数占位符
# %d 整数占位符
b = 'Hello %s'%'孙悟空'
print(b)
b = 'hello %s 你好 %s'%('tom','孙悟空')
print(b)
b = 'hello %3.5s'%'abcdefg' # %3.5s字符串的长度限制在3-5之间,hello abcde
print(b)
b = 'hello %s'%123.456#
print(b)
b = 'hello %.2f'%123.456# hello 123.46,保留2位小数
print(b)
b = 'hello %d'%123.95# hello 123
print(b)
b = '呵呵'
print(b)
print('a = %s'%a)# a = 123
# 格式化字符串,可以通过在字符串前添加一个f来创建一个格式化字符串
# 在格式化字符串中可以直接嵌入变量
c = f'hello {a} {b}'
print(c)# hello 123 呵呵
print(f'a = {a}')
# 练习 创建一个变量保存你的名字,然后通过四种格式化字符串的方式
# 在命令行中显示,欢迎 xxx 光临! |
9521b428753418d5f786318cbe3464eb9592b293 | jae-hun-e/python_practice_SourceCode | /뼈대코드/5/5-20.py | 120 | 3.515625 | 4 | def insertion_sort(xs):
if xs != []:
return insert(xs[0],insertion_sort(xs[1:]))
else:
return [] |
b99c829719a20f1216b2c86210757be6914b2b74 | Team-Tomato/Learn | /Juniors - 1st Year/Nirmal/DAY 3/matrix_multiplication.py | 1,216 | 4.125 | 4 | p1=int(input("Enter the rows for matirx_1: "))
q1=int(input ("Enter the columns for matrix_1: "))
print("Enter the elements for matrix_1: ")
matrix_1 =[ [int(input()) for i in range(p1)] for j in range(q1)]
print("matrix_1 is: ")
for i in range(p1):
for j in range(q1):
print(format(matrix_1[i] [j], "<5"), end=" ")
print()
print("Enter the elements for matrix_2: ")
p2=int(input("Enter the rows for matirx_2: "))
q2=int(input ("Enter the columns for matrix_2: "))
matrix_2 =[ [int(input()) for i in range(p2)] for j in range (q2) ]
print("matrix_2 is: ")
for i in range(p2):
for j in range(q2):
print(format(matrix_2 [i] [j], "<5"), end=" ")
print()
if(q1 == p2):
result = [ [ 0 for i in range(q1)] for j in range(p2) ]
for i in range(p1):
for j in range(q2):
for k in range(p2):
result [i] [j] = result [i] [j] + matrix_1 [i] [k] * matrix_2 [k] [j]
print("Result is: ")
for i in range(q1):
for j in range (p2):
print(format(result [i] [j], "<5"), end=" ")
print()
else:
print("Cannot perform matix multiplication.")
|
85a717787387b6aefb8ace79a931a097ad5a61ff | nexiom1221/Phyton-Practice | /예제/practice7.py | 387 | 3.84375 | 4 | def std_weight(height, gender):
if gender== "남자":
return height * height * 22
else:
return height * height * 21
# height = 175
# gender = "남자"
height, gender= map(str,input("키와 성별을 입력하세요:").split())
weight = (round(std_weight(height / 100 ,gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2} 입니다.".format(height,gender,weight)) |
6f15039a8357581e98fd29c1037f91d68447589c | ekeydar/selfpy_sols | /ex6.1.2.py | 360 | 4.21875 | 4 | def shift_left(my_list):
"""
shifts list of 3 elements to the left
:param my_list: list of len 3
:type list
:return: list of len3, shifted left
:rtype list
"""
a, b, c = my_list
return [b, c, a]
def main():
print(shift_left([0, 1, 2]))
print(shift_left(['monkey', 2.0, 1]))
if __name__ == '__main__':
main()
|
e46e2b0a9d5a9c2be9667296fc2597d1dd6af0f6 | Changvang/Python_project | /Tictactoe/game.py | 4,392 | 4.03125 | 4 | # Board
# display board
# play game
# handle turn
# check win
# check rows
# check columns
# check diagonals
# check tie
# flip player
# --------------- Global Variables ---------------------
flip = True
# Game Board hold data of the game
board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
# Two player
X = "X"
O = "O"
#Start player
current_player = X
# Who won or tie?
winner = None
# Checking this game is playing or game over
game_still_ongoing = True
#Display a board game in the creen
def display_board():
#display attractive position for player know the position of board in the creen
position_display = [" | 1 | 2 | 3 | ", " | 4 | 5 | 6 | ", " | 7 | 8 | 9 | "]
# Display 3 value of board in 1 rows and additional view of these position
for i in range(3):
print(" | {0} | {1} | {2} | {3}".format(board[3*i], board[3*i + 1], board[3*i + 2], position_display[i]))
#Executing a turn for a player
def handle_turn():
#Set global variables
global current_player
# Print in the sreen who has this turn?
print(current_player + "'s turn!!!")
# Variable for checking input is valid format
valid_input_position = False
# Pisition player choose
position = ""
# Checking valid position and this position still None
while(not valid_input_position):
position = input("Choose a position from 1-9: ")
# check valid position input is a number from 1 - 9
if position.isalnum() and position in "123456789":
#Checking position still not fill
if not board[int(position)-1] == "-":
print("*Position has valued, Pic a gain")
else:
valid_input_position = True
else:
print("*Not valid position input, Type a gain")
#Update value for board
board[int(position)-1] = current_player
#Display board game
display_board()
# Change the turn for other player
def flip_player():
global flip, current_player
# flip = True for first player(X), and False for second player(O)
if flip:
# first player
current_player = O
else:
# second player
current_player = X
#end turn/ change flip for next player
flip = not flip
#Checking have a winner or no position available in the board(tie)
def check_game_over():
global winner
#Found the winner in this turn
check_if_win()
#The last turn but not found the winner
check_if_tie()
def check_if_win():
#Set global values
global game_still_ongoing, winner
# Get winner from row, column or diagnoals
row_winner = winner_row()
column_winner = winner_column()
diagonals_winner = winner_diagonals()
# if a row, column or a diagnol touch win rule -> set winner = current_player
if row_winner or column_winner or diagonals_winner:
winner = current_player
game_still_ongoing = False
#Checking have a row with same value of current player
def winner_row():
win = False
for i in range(3):
row_check = board[3*i] == board[3*i+1] == board[3*i+2] != "-"
win = win or row_check
return win
#Checking have a column with same value of current player
def winner_column():
win = False
for i in range(3):
column_check = board[i] == board[i+3] == board[i+6] != "-"
win = win or column_check
return win
#Checking have a diagonal with same value of current player
def winner_diagonals():
diagonal1 = board[0] == board[4] == board[8] != "-"
diagonal2 = board[2] == board[4] == board[6] != "-"
return diagonal1 or diagonal2
#Checking if the board game has no available position and game over with tie
def check_if_tie():
global game_still_ongoing
check_not_fill_position = "-" in board
if not check_not_fill_position:
game_still_ongoing = False
def play_game():
#Initial the game
display_board()
#game still in play
while(game_still_ongoing):
#handling a turn of a player
handle_turn()
#checking if the game has get stop case
check_game_over()
#if not over game will continue, so change turn for next player
flip_player()
#Executing for game over
if winner == X or winner == O:
print(winner + " Won.")
elif winner == None:
print("Tie") |
2d2c54168177e3b2208bb0c17f0ddfd9fa730e4d | jachin/coderdojotc-python | /tower2.py | 602 | 3.609375 | 4 | # Written by Jessica Zehavi for CoderDojo Twin Cities - www.coderdojotc.org
#!/usr/bin/python
import mcpi.minecraft as minecraft
import mcpi.block as block
# Connect to the Minecraft server
world = minecraft.Minecraft.create()
# Get the player's current position and store the coordinates
[x,y,z] = world.player.getPos()
# Set some variables to customize your tower
height = 3
material = block.GLASS
# Execute the loop, building from the bottom up
for level in range( 0, height ):
world.setBlock( x, level, z, material )
# Put the player on top of the tower
world.player.setPos( x, height, z )
|
918a8b3c1522d604743860c3cfc45a6fc0e5e132 | ptabis/pp1 | /05-ModularProgramming/8.py | 295 | 3.796875 | 4 | import turtle
def drawSquare(x,y,n):
pen = turtle.Turtle()
pen.penup()
pen.setposition(x,y)
pen.pendown()
for i in range(0, 4):
pen.forward(n)
pen.right(90)
for i in range(1, 5):
for j in range(1, 5):
drawSquare(-300+i*100, 300-j*100, 100)
|
dfcc71deba408a41d7bf0031fd67e111e4e66404 | AnotherOneWithAFace/logic-gates | /and.py | 876 | 4.15625 | 4 | def main():
print("This program emulates the functionality of an AND logic gate")
print("Enter either a 1 or a 0, twice")
print("Don't enter anything other than 1 or 0")
x = input()
y = input()
if x == "0":
bool1 = False
elif x == "1":
bool1 = True
else:
bool1 = "empty"
if y == "1":
bool2 = True
elif y == "0":
bool2 = False
else:
bool2 = "empty"
if bool2 and bool1 == True:
print("Your answer is: 1")
elif bool1 == True and bool2 == False or bool2 == True and bool1 == False:
print("Your answer is: 0")
elif bool1 and bool2 == False:
print("Your answer is: 0")
elif bool1 or bool2 == False:
print("Your answer is: 0")
if bool1 and bool2 == "empty":
print("your answer isnt 0, you need to enter either 0 or 1!")
main() |
30132cd72458b94cd244412d9dcdc108a5674c6f | yatikaarora/turtle_coding | /drawing.py | 282 | 4.28125 | 4 | #to draw an octagon and a nested loop within.
import turtle
turtle= turtle.Turtle()
sides = 8
for steps in range(sides):
turtle.forward(100)
turtle.right(360/sides)
for moresteps in range(sides):
turtle.forward(50)
turtle.right(360/sides)
|
2c5fd6b8cc0433918e8745b1e999ad068be97e2b | jeffthemaximum/CodeEval | /Python/Easy/word_to_digits.py | 332 | 3.734375 | 4 | test = "zero;two;five;seven;eight;four"
my_dict = {
'zero': '0',
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9'
}
my_array = test.split(';')
output = ''
for num in my_array:
output += my_dict[num.rstrip()]
print output
|
a9685c0da5e93ebc12e2a43cfca9f17622849be8 | Mrhairui/python1 | /other/find_object.py | 1,148 | 3.90625 | 4 | from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
n = len(matrix)
if n == 0:
return False
m = len(matrix[0])
t = n*m
if t == 0:
return False
left = 0
right = t - 1
if matrix[right//m][right%m] == target:
return True
middle = (right+left) // 2
while left <= right:
# if matrix[left//m][left%m] == matrix[middle//m][middle%m]:
# if matrix[middle//m][middle%m] == target:
# return True
# else:
# return False
if matrix[middle//m][middle%m] == target:
return True
elif matrix[middle//m][middle%m] > target:
right = middle - 1
middle = (right+left) // 2
else:
left = middle + 1
middle = (right+left) // 2
return False
if __name__ == '__main__':
solution = Solution()
matrix = [[1, 3]]
target = 3
p = solution.searchMatrix(matrix, target)
print(p)
|
371ee9c8d120ec2196ed4446bc1b90b772c83799 | himangi6550/Python-programs | /sumarray.py | 307 | 3.78125 | 4 | N = int(input())
# Get the array
numArray1 = list(map(int, input().split()))
numArray2 = list(map(int, input().split()))
sumArray = [N]
# Write the logic here:
for i in numArray1:
sumArray[i]=i
# Print the sumArray
for element in sumArray:
print(element, end=" ")
print("")
|
b1b51ef59247dad427fad0e5a35206943e4f7a04 | gizat/EulerProject | /Problem 009.py | 389 | 3.828125 | 4 | # Problem 9
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def main():
for a in range(1, 1001):
for b in range(a+1, 1001):
for c in range(b+1, 1001):
if a**2 + b**2 == c**2:
if a + b + c == 1000:
print(a*b*c)
if __name__ == '__main__':
main()
|
23c0b044646efa5d370ebc82e84255e60b7aa730 | ChinmayN30/Python-Projects | /Project_WeightConversion.py | 357 | 4.0625 | 4 | Weight = input("Enter your weight: ")
weight_Unit = input("(L)bs or (K)gs: ")
if weight_Unit.upper() == "L":
UserWeight = float(Weight) * 0.45
print(f"Your weight in Kgs is {UserWeight}")
elif weight_Unit.upper() == "K":
UserWeight = float(Weight) / 0.45
print(f"Your weight in Lbs is {UserWeight}")
else:
print("Invalid Input") |
c5e088b2f392ad4273935b5cfba2424032921cdf | mmaatuq/brain_storming | /dice3.py | 603 | 3.5 | 4 | def compute_strategy(dices):
assert all(len(dice) == 6 for dice in dices)
best_index=0
MMax=0
strategy = dict()
strategy["choose_first"] = True
strategy["first_dice"] = 0
l=find_the_best_dice(dices)
if l!=-1:
strategy["first_dice"] = l
else:
for i in dices:
for j in dices:
if i==j:
continue
l=find_the_best_dice(dices[i],dices[j])
m=l[1]-l[0]
if m >MMax:
MMax=m
best_index=j
strategy[i]=best_index
return strategy
|
c60a42a96fe0ab125f874fff4bb34e60de0e4129 | haoccheng/pegasus | /leetcode/btree_pre-inorder.py | 601 | 3.53125 | 4 | def build_tree(preorder, inorder):
if len(preorder) == 0:
return None
elif len(preorder) == 1:
return TreeNode(preorder[0])
else:
root = preorder[0]
inorder_root = inorder.index(root)
left_inorder = inorder[:inorder_root]
right_inorder = inorder[inorder_root+1:]
left_preorder = [e for e in preorder if e in left_inorder]
right_preorder = [e for e in preorder if e in right_inorder]
left = build_tree(left_preorder, left_inorder)
right = build_tree(right_preorder, right_inorder)
r = TreeNode(root)
r.left = left
r.right = right
return r
|
58c6fbf69e3e3d5dfd3ff73b7819dd5f5bbc959e | saadkang/PyCharmLearning | /controlstructure/whileloopdemo.py | 1,755 | 4.0625 | 4 | """
Execute Statements repeatedly
Conditions are used to Stop the Execution of loops
Iterable items are String, List, Tuple, and Dictionary
"""
x = 0
while x < 10:
print("The value of x is: "+ str(x))
x = x + 1
print('*'*40)
print('*'*40)
# So like established before after the while block whatever is indented is part of the while block
# In the above example we defined x is 0, and then we are basically saying that as long as x is less than 10
# print 'The value of x is:' 'whatever the value of x is' and in the next line we are increasing the value of x
# by one and continuing with the loop as long as the value of x is less than 10, once the value of x exceeds 10
# the loop will break or stop
# We can use the while loop to put the value in a list
l = []
num = 0
while num < 10:
l.append(num)
num += 1
print(l)
print('*'*40)
# So we have an empty list 'l' and we defined a variable 'num' that holds the number or value '0'
# and in the while loop we are saying as long as 'num' is less than 10 do what it says in the loop, and the loop is
# saying to append() meaning add the value of 'num' in the list and in the next line we are increasing the value of
# the variable 'num' by 1 and then the loop continues until the value of the variable reaches 9. After the vaule of
# the variable 'num' reaches 10 the condition of the while loop is not met and the loop breaks, the last line is not
# part of the while block so it get executed anyways and it is saying to print the list 'l' and the list is printed
# on the console
# We can add another line in the while loop asking to print the value of a variable
j = []
num2 = 0
while num2 < 10:
j.append(num2)
print("The value of num is: "+ str(num2))
num2 += 1
print(j) |
181fff03ae41ed98f906ef03d8b65587a7199cf8 | Gabriel01osabuede/AndrewOsabuedeGabriel | /Calculator.py | 354 | 4.5 | 4 | #Calculating the area of a circle
# storing 3.14 in a variable called pi
pi = 3.14
# Accepting input (radius) from the user.
radius = float(input("Type in the raduis of the circle : "))
# Using the formula to calculate the Area
Area = (pi * radius ** 2)
# Printing out the calculation to the console.
print(" Area of the circle = {}".format(Area))
|
a691e46fbd42c10f80785af9c27f111be523c5da | abbbhardwaj/Encryption | /src/UsingClass.py | 1,043 | 3.859375 | 4 |
import random
import time
# Class that generates password 3 times
class PwGenerator:
password = ''
def generator(self, length_of_password, chars):
p = 0
if p in range(3):
for pwd in range(length_of_password):
self.password += random.choice(chars)
print(self.password)
else:
print("Password reset limit exceeded. Kindly wait till the counter hit the zero")
def stopwatch(self, seconds):
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
print("Generating password in seconds"
"%2d" % (elapsed))
time.sleep(1)
chars = 'abcdefgh!@%^*&ijklmn1234567opqrstuvwxyzABHCDEFGHIJKLMNO0912345678!%@^$' # string to be used for pwd creation
length_of_password = 10 #length of pwd string
pw = PwGenerator()
print("Kindly generate a password before the time expires")
pw.stopwatch(5)
pw.generator(length_of_password, chars)
|
bd626435d991674b91d349f1a2db9351ebfbd14b | oddduckden/lesson2 | /task3.py | 899 | 4.15625 | 4 | # 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц
# (зима, весна, лето, осень). Напишите решения через list и через dict.
month = int(input('Введите номер месяца в году: '))
seasons_list = ['зима', 'зима', 'весна', 'весна', 'весна', 'лето', 'лето', 'лето', 'осень', 'осень', 'осень', 'зима']
seasons_dict = {1: 'зима', 2: 'зима', 3: 'весна', 4: 'весна', 5: 'весна', 6: 'лето', 7: 'лето', 8: 'лето', 9: 'осень',
10: 'осень', 11: 'осень', 12: 'зима'}
print('Сезон (по списку): ', seasons_list[month - 1])
print('Сезон (по словарю): ', seasons_dict[month]) |
c04c7c3c2ea49d99c94095e2364d7017c05c6b40 | Liss19/Examen | /explv2.py | 635 | 3.703125 | 4 | import re
class inicio2:
def op2(self):
expresion= input("Escribe una cadena: ")
print(expresion)
numeros=""
letras=""
numero=re.compile('[0-9]')
letra=re.compile('[a-zA-Z]')
for x in range(0,len(expresion)):
buscar=numero.search(expresion[x])
buscar2=letra.search(expresion[x])
if(buscar != None):
numeros=numeros+expresion[x]
if(buscar2 != None):
letras=letras+expresion[x]
print("Números: "+numeros)
print("Letras: "+letras)
p1=inicio2()
p1.op2() |
9fd6953ca0aacdf0b4b3f7c93d6b9e9ae61bbd3a | tongxindao/notes | /imooc_python3_class/ten/c12.py | 191 | 3.8125 | 4 | import re
s = "Life is short, i use python, i use python"
r = re.search("Life(.*)python(.*)", s)
# print(r.group(0, 1, 2))
print(r.groups())
# r = re.findall("Life(.*)python", s)
# print(r) |
5e61a757b3de77df4184aefc269de8d73b8a182e | tkshim/leetcode | /leetcode_0905_SortArrayByParity.py | 242 | 3.859375 | 4 | #!/usr/bin/env python
#coding:utf-8
def checkNumber(X):
odd = []
even = []
for x in X:
if x % 2 == 0:
odd.append(x)
else:
even.append(x)
return odd + even
print checkNumber([1,2,3,4])
|
e7b4409ed1c14d182255a3c9f3ca2b677e3c69c5 | hkelder/Python | /Homework/singelton.py | 890 | 4.34375 | 4 | # Write a program in which you have a class, and you can instantiate object of it.
# However, there is a restriction that you can create maximum of 1 object.
# When 1 single object has been created out of that class, we must not be able to create more objects.
# Code within the class is irrelevant but it should support only one object.
class Hello:
sharedState = {}
def __init__(self):
self.__dict__ = self.sharedState
class Singleton(Hello):
def __init__(self, arg):
Hello.__init__(self)
self.val = arg
def __str__(self):
return self.val
iteration1 = Singleton("Egg") # Since singleton replaces the previous iteration value, you can only have 1 value always
print(iteration1)
iteration2 = Singleton("Bacon")
print(iteration2)
print(iteration1)
iteration3 = Singleton("123")
print(iteration3)
print(iteration2)
print(iteration1)
|
6ac765e4b77b85c045e0a88fadb1c76239a5db1c | SAURABH5969/K-Means-Clustering | /PreProcess.py | 805 | 3.515625 | 4 | import pandas as pd
import numpy as np
import matplotlib as plt
from scipy.stats import mode
class PreProcess:
df=pd.DataFrame({})
def __init__(self,dataFrame):
self.df = dataFrame
self.fillNaAndNorm()
self.groupByCountry()
#fill na and normalize
def fillNaAndNorm(self):
for column in self.df.columns[1:]:
self.df[column].fillna(self.df[column].mean(), inplace=True)
#standerization
avg=self.df[column].mean()
std=np.std(self.df[column])
self.df[column]=(self.df[column]-avg)/std
#group by country
def groupByCountry(self):
self.df=self.df.groupby("country").mean()
del self.df["year"]
#dataframe=pd.read_excel("D:\\data.xlsx")
#dataCleaner = PreProcess(dataframe)
|
66cac4d5612dad98b0c1d7a239cb8cb00abac905 | GuavaLand/IntroToCS | /L10_daysBetweenDatesOfficial.py | 2,158 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import os
os.chdir('C:\Sources\IntroToCS')
def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < daysInMonth(year, month):
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
# YOUR CODE HERE!
days = 0
assert not isBefore(year2, month2, day2, year1, month1, day1)
'''Throw AssertionError if False
isBefore=True only if date1 < date2; False if date1 >= date2'''
while True:
if year1 == year2 and month1 == month2 and day1 == day2:
break
year1, month1, day1 = nextDay(year1, month1, day1)
days += 1
return days
def isBefore(year1, month1, day1, year2, month2, day2):
'''The first date is earlier (not equal) than the second'''
if year1 < year2:
return True
elif year1 == year2:
if month1 < month2:
return True
elif month1 == month2:
if day1 < day2:
return True
return False
def daysInMonth(year, month):
listOfDays = [31,28,31,30,31,30,31,31,30,31,30,31]
if isLeapYear(year) and month == 2:
return 29
return listOfDays[month-1]
def isLeapYear(year):
if year%4 != 0:
return False
elif year%100 != 0:
return True
elif year%400 != 0:
return False
else:
return True
#daysBetweenDates(2012,1,1,2012,1,3)
def test():
assert daysBetweenDates(2013,1,1,2013,1,1) == 0
assert daysBetweenDates(2013,1,1,2013,1,2) == 1
assert daysBetweenDates(1900,2,28,1900,3,1) == 1
assert daysBetweenDates(2012,2,28,2012,3,1) == 2
assert daysBetweenDates(2012,3,1,2012,4,1) == 31
print('Test finished!') |
6ee72e244b2984a10776dd7643aa61107a7d342f | blueeric/Python | /Stack.py | 744 | 3.875 | 4 | class Stack():
def __init__(self,size):
self.stack=[]
self.size=size
self.head=-1
def isEmpty(self):
if self.head==-1:
return True
else:
return False
def isFull(self):
if self.head+1==self.size:
return True
else:
return False
def enStack(self,con):
if self.isFull():
print("Stack is full")
else:
self.stack.append(con)
self.head=self.head+1
def outStack(self,con):
if self.isEmpty():
print("Stack is empty");
else:
self.stack.remove(con)
#self.stack.pop() #delete the last one
self.head=self.head-1; |
aa33f426d54a2b04f0b2b5f72136b1ac84ae389d | GMillerA/100daysofcode-with-python-course | /days/19-21-itertools/code/Stoplight.py | 681 | 3.90625 | 4 | import itertools
import sys
from time import sleep
import random
def sleep_timer():
return random.randint(3,7)
def stoplight():
"""Stoplight that cycles through colors"""
colors = 'Red Green Yellow'.split()
symbols = itertools.cycle(colors)
for color in symbols:
if color == "Red":
print('STOP! The color is {}!'.format(color))
sleep(sleep_timer())
elif color == "Green":
print('GO! The color is {}'.format(color))
sleep(sleep_timer())
else:
print('SLOW! The color is {}'.format(color))
sleep(3)
if __name__ == "__main__":
stoplight() |
9ecee629f60b23bcc1e0611bfdf1bf8416baea33 | seandewar/challenge-solutions | /hackerrank/easy/2d-array.py | 802 | 3.65625 | 4 | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/2d-array
import math
import os
import random
import re
import sys
# Complete the hourglassSum function below.
def hourglassSum(arr):
largestsum = -sys.maxsize - 1
for y in range(len(arr) - 2):
for x in range(len(arr[y]) - 2):
hgsum = arr[y ][x ] + arr[y ][x+1] + arr[y ][x+2]
hgsum += arr[y+1][x+1]
hgsum += arr[y+2][x ] + arr[y+2][x+1] + arr[y+2][x+2]
largestsum = max(largestsum, hgsum)
return largestsum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
81289f361b3ef20a1f5ed80d36cf3db1516237fc | siggimar92/ProgAssignment1 | /Lexer.py | 2,708 | 3.875 | 4 | from Token import Token
import string
from sys import stdin
__author__ = 'Hrafnkell'
class Lexer(object):
''' Diagnoses each token and describes it for the computer '''
def __init__(self):
self.c = ""
#self.string = ""
#self.string = stdin.read()
#self.string = self.string.replace(" ", "")
#self.string = self.string.replace("\n", "")
#self.string = self.string.replace("\t", "")
#self.i = 0
def nextToken(self):
token = ""
if(self.c == ""):
token = self.get_tokencode(self.next_char())
else:
token = self.get_tokencode(self.c)
self.c = ""
return token
def get_tokencode(self, lexeme):
while lexeme == " " or lexeme == "\n" or lexeme == "\t":
lexeme = self.next_char()
if lexeme == "+":
return Token("+", "+")
elif lexeme == "-":
return Token("-", "-")
elif lexeme == "*":
return Token("*", "*")
elif lexeme == "(":
return Token("(", "(")
elif lexeme == ")":
return Token(")", ")")
elif lexeme == "=":
return Token("=", "=")
elif lexeme == ";":
return Token(";", ";")
elif lexeme.isdigit():
tmpLex = lexeme
while True:
nxt_char = self.next_char()
if nxt_char.isdigit():
tmpLex += nxt_char
else:
self.c = nxt_char
break
return Token(tmpLex, "int")
elif lexeme.isalpha():
tmpLex = lexeme
while True:
nxt_char = self.next_char()
if nxt_char.isalpha():
tmpLex += nxt_char
if tmpLex == "print":
return Token("print", "print")
elif tmpLex == "end":
return Token("end", "end")
else:
self.c = nxt_char
break
return Token(tmpLex, "id")
else:
return Token("error", "error")
def next_char(self):
return stdin.read(1)
#lex = Lexer()
#print(lex.nextToken().tCode)
#print(lex.nextToken().tCode)
#print(lex.nextToken().tCode)
#for i in range(10):
# print(next_char())
#print("running")
#string = stdin.read()
#print(string)
#while True:
# stdin = input()
# for i in stdin.split():
# print(lex.nextToken(i).tCode)
#lex = Lexer()
#string = ""
#while lex.i != len(lex.stdin):
# tok = lex.nextToken()
# print(tok.tCode + " " + tok.lexeme)
#print(string)
|
a72c4a2ba6d24b7c25b79b5dbfdac7a1f8209742 | QuangTran999/projectBDS | /projectBDS/GUIbds.py | 3,624 | 3.578125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.ttk import *
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
win = Tk()
win.title("Home price prediction")
win.geometry("1500x2630")
win.iconbitmap("logo.ico")
dataset = pd.read_csv("123.csv").values
X = dataset[:, 0:4].reshape(-1, 4)
X = np.hstack((np.ones((X.shape[0], 1)), X))
y = dataset[:, dataset.shape[1]-1]
n, d = X.shape
theta = np.array([0.1]*d)
print(theta)
iters = 1000
learning_rate = 0.00001
#-------------------------------
datatest = pd.read_csv("dataBDStest.csv").values
Ytest = datatest[:, datatest.shape[1]-1]
Xtest = datatest[:, 0:4].reshape(-1, 4)
Xtest = np.hstack((np.ones((Xtest.shape[0], 1)), Xtest))
# #-------------------------------
def cost_function(theta, X, y):
y1 = theta*X
y1 = np.sum(y1, axis=1)
return (1/(2*n))*sum(y-y1)**2
def train(theta, X, y, learning_rate, iters):
cost_history = []
for i in range(iters):
for c in range(d):
# y1 = theta*X
y1 = theta * X
y1 = np.sum(y1, axis=1)
theta[c] = theta[c]-learning_rate*1/n*sum((y1-y)*X[:, c])
cost = cost_function(theta, X, y)
cost_history.append(cost)
return theta, cost_history
def prediction():
theta1, cost_history = train(theta, X, y, learning_rate, iters)
t3.delete(0, 'end')
num = float(t.get())
num0 = float(t0.get())
num1 = float(t1.get())
num2 = float(t2.get())
X1 = np.array([[1, num, num0, num1, num2]])
y1 = theta1 * X1
plt.figure()
result = np.sum(y1, axis=1)
t3.insert(END, str(result))
def clean():
t.delete(0, 'end')
t0.delete(0, 'end')
t1.delete(0, 'end')
t2.delete(0, 'end')
t3.delete(0, 'end')
lbl = Label(win, text='Acreage(m^2):')
lbl0 = Label(win, text='Street:')
lbl1 = Label(win, text='Floors:')
lbl2 = Label(win, text='Rooms:')
lbl3 = Label(win, text='Prediction(B):')
t = Entry()
t0 = Entry()
t1 = Entry()
t2 = Entry()
t3 = Entry()
btn1 = Button(win, text='Prediction')
btn2 = Button(win, text='Clean')
lbl.place(x=10, y=20)
t.place(x=100, y=20)
lbl0.place(x=10, y=60)
t0.place(x=100, y=60)
lbl1.place(x=10, y=100)
t1.place(x=100, y=100)
lbl2.place(x=10, y=140)
t2.place(x=100, y=140)
theta1, cost_history = train(theta, X, y, learning_rate, iters)
nptheta = np.array(theta1)
npXtest = np.array(Xtest)
# print(nptheta)
# print(npXtest)
YtestTheta = np.dot(npXtest, nptheta)
# print(YtestTheta)
St = ((Ytest - Ytest.mean())**2).sum()
Sr = ((Ytest - YtestTheta)**2).sum()
R2 = 1 - (Sr/St)
print(R2)
figure = Figure(figsize=(5, 4), dpi=70)
plot = figure.add_subplot(1, 1, 1)
plot.plot(YtestTheta, Ytest, color="blue", marker="o", linestyle="")
plot.set_xlabel("Y du doan")
plot.set_ylabel("Y thuc te")
canvas = FigureCanvasTkAgg(figure, win)
canvas.get_tk_widget().place(x=250, y=10)
plot.set_title('Interest Rate Vs. Stock Index Price')
x0 = np.linspace(min(YtestTheta), max(YtestTheta))
plot.plot(x0, x0)
figure2 = Figure(figsize=(5, 4), dpi=70)
plot1 = figure2.add_subplot(1, 1, 1)
plot1.plot(cost_history)
canvas2 = FigureCanvasTkAgg(figure2, win)
canvas2.get_tk_widget().place(x=250, y=350)
plot1.set_title('Interest Rate Vs. Stock Index Price')
b1 = Button(win, text='Prediction', command = prediction)
b2 = Button(win, text='Clean', command = clean)
b2.bind('<Button-1>')
b1.place(x=40, y=190)
b2.place(x=150, y=190)
lbl3.place(x=10, y=230)
t3.place(x=100, y=230)
win.geometry("620x750+10+10")
win.mainloop() |
193c3165bf8e887a0eba82b5fb7f33b8c4f8f53e | AlfredPianist/holbertonschool-higher_level_programming | /0x0A-python-inheritance/101-add_attribute.py | 620 | 4.0625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""101-add_attribute
This module contains a function that adds a new attribute to an object
if possible.
"""
def add_attribute(obj, name, value):
"""Function that adds a new attribute to an object if possible.
Args:
obj (:obj:): The object to be added a new attribute.
name (str): The name of the new attribute.
value (:obj:): The value of the new attribute.
Raises:
TypeError: Attribute can't be added.
"""
if not hasattr(obj, '__dict__'):
raise TypeError("can't add new attribute")
setattr(obj, name, value)
|
de2ef567c217662741efde592d745285d5d5ffdd | hylyujj/python_Interview | /peponacciSequence.py | 710 | 3.765625 | 4 | #-*- coding: utf-8 -*-
def firstFibFunc(n):
before, after = 1, 1
for i in range(n):
yield before
before, after = after, before + after
gen = firstFibFunc(5)
for i in gen:
print(i)
def consumerFibFunc():
before, after = 0, 1
while True:
yield before
before, after = after, before + after
print(before)
def producFibFunc(f):
f.send(None)
h = 0
while h < 5:
h += 1
f.send(h)
f.close()
f = consumerFibFunc()
producFibFunc(f)
def secondFibFunc(num):
firstValue, secondValue, index = 0, 1, 0
while index < num:
yield secondValue
firstValue, secondValue = secondValue, firstValue + secondValue
index += 1
for i in secondFibFunc(5):
print(i) |
c2eda2ed6bddd7871085e5023ea887b93f6a94b0 | huntercollegehighschool/srs2pythonbasicsf21-mtcl17 | /part1.py | 335 | 4 | 4 | """
Define a function sumofsquares that takes an integer input number. The function then adds all the first n perfect squares (starting from 1).
For example, sumofsquares(3) should return 14, since 1 + 4 + 9 = 14.
"""
def sumofsquares(number):
i=1
sumsquares=0
while i<=number:
sumsquares+=i**2
i+=1
return sumsquares |
4fbcc9755f9937195aea55434de1e98207fdb9c9 | fewva/my_python | /9/random1000.py | 502 | 3.5625 | 4 | import random
a = [random.randint(-1000, 1000) for i in range(10)] #10 элементов просто легче проверить)
imin = a.index(min(a))
imax = a.index(max(a))
if imax < imin:
imax, imin = imin, imax
kol = len(list(filter((lambda x: x < 0), a[imin:imax + 1])))
print(f'Список выглядит так: {a}, его максимальный элемент: {max(a)}, минимальный: {min(a)}, между ними {kol} отрицательных элементов')
|
3205f3552dae627d5c6a3249be24cf674645a7bf | gpapad14/DataAnalysisWorkshop | /PredictSurvivalB_titanic_data.py | 910 | 3.703125 | 4 | # In this portion of the assignment you should create a more complex heuristic with an accuracy of 80% or more.
# You are encouraged to use as many of the elements in the csv file as you need.
import pandas
predictions = []
df = pandas.read_csv("titanic_data.csv")
wrong=0
for passenger_index, passenger in df.iterrows():
if passenger[4]=="male" or passenger[6]>2 or passenger[7]>2:
predictions.append(0)
else:
predictions.append(1)
if not predictions[passenger_index]==passenger[1]:
wrong+=1
#print wrong
# Fixed predictions
print "Wrong predictions: "+str(wrong)+", Number of passengers: "+str(passenger_index+1)
accuracy=(891-wrong)/891.0
# The .0 helps us calculate the accuracy as a float number (not integer)
print "The accuracy is "+str(accuracy*100.0)+"%"
# New prediction gives accuracy greater than 80%, better than before. |
071d923391aab89b7562c238c3d71f7c11e6c32b | shankar7791/MI-10-DevOps | /Personel/Yash/Python/23feb/Pro7.py | 662 | 4 | 4 | # Program 7 : Write a Python program that accepts a string and calculate the number of digits and
# letters.
'''
s = input("Enter the string : " )
digits=letters=0
for i in s:
if i.isdigit():
digits=digits+1
elif i.isalpha():
letters=letters+1
print("Number of Letters", letters)
print("Number of Digits", digits)
'''
str1 = input("Enter a string: ")
dig=0
alp=0
i=0
l=len(str1)
while i<l:
if str1[i].isdigit():
dig =dig +1
elif str1[i].isalpha():
alp = alp +1
else:
print(f"Other than letter and digit are {str1[i]}")
i=i+1
print(f"Total Digits are : {dig}")
print(f"Total Letters are : {alp}") |
0d23d8fe2a67fe377bdb81e7ce836369de117b58 | anaschmidt/Aprendendo-a-programar | /Aulas/condicional.py | 571 | 4.03125 | 4 | # Condicional (IF - ELSE) if: Ponto no problema ex:. if (expressão condicional):
#código: quando eu tenho códigos desalinhados, são chamados de bloco identação: processo de separa os blocos ''bonitinhos''
# else: uma opção, não é obrigatório.0000000000000000000
#operadores lógicos: == != > < >= <=
#fazer uma variavel que o cara que quer sair ou não do programa
sair=input('você quer sair? ')
if sair == 'sim':
print('vamos sair do programa')
elif sair == 'não':
print('OK, vamos continuar')
else:
print('Não entendi o que você falou')
|
296ee8466ab356a30bbe17e100ff28c85b5eca6f | seershikab/assignment-4.py | /assignment4.3.py | 78 | 3.625 | 4 | def fact(n):
if n==1:
return n
else
return n*fact(n-1)
print(fact(5)) |
dd18d6fd077cfe660a6e62d0a274505bb34893eb | primegoon/homework | /twice/2.py | 267 | 3.65625 | 4 | a, b = input('숫자 두 개를 입력하세요: ').split()
a = int(a)
b = int(b)
print('덧셈은 : ', a + b)
print('뺄셈은 : ', a - b)
print('곱셈은 : ', a * b)
print('나눗셈은 : ', a / b)
print('몫은 : ', a // b)
print('나머지는 : ', a % b) |
a892d3c424ef0e876830ec268e11b5cc26ea89db | Arality/learnpython | /Lesson 4.py | 477 | 3.8125 | 4 | # Functions
# A function is a transportable section of code that you use to stop doing the same thing over and over again. It is defined by the key word def name(arguments):
#def LogFunction(paramater):
# print(paramater)
# Returns
# Sometimes you want your fuction to do things and give you the results to exit a function and return and object use the return keyword
#def addFunction(a, b):
# return a + b
#variable = addFunction(1,2)
#print(variable)
|
fc1116ba3c3671987e99dbf6d66953bbe0f98103 | Evaldo-comp/Python_Teoria-e-Pratica | /Livros_Cursos/Udemy/Lendo_Recebendo_dados/pep8.py | 2,123 | 3.859375 | 4 | """
PEP8 - Python Enhacement Proposal
São propostas de melhorias a Linguagem Python
The Zen of Python
import this
A ideia da PEP8 é que possamos escrever códigos Python de forma Pythônica
************************************************************************************
[1] - Utilizar camel case para nomes de classes
************************************************************************************
class Calculadora:
pass
************************************************************************************
[2] - Utilizar nomes minusculos, separados por underlaine para funções ou cariáveis
************************************************************************************
def soma():
pass
def soma_dois():
pass
numero = 4
************************************************************************************
[3] - Utilize 4 espaços para identação!(não use o tab)
************************************************************************************
if 'c' in 'banana':
print('tem')
else:
print('Não tem')
[4] Linhas em branco
- Separar funções e definições de classes com duas linhas em branco:
- Métodos dentro de uma classe devem ser separados com uma unica linha em, branco
[5] - Imports
- Imports deve ser sempre feitos em linhas separadas:
#import Errado
import sys, os
#import Certo
import sys
import os
#Não há problemas em utilizar:
from types import StringType, ListType
#Caso tenha muitos imports de um mesmo pacote, recomenda-se fazer:
from types import (
StringType
ListType
SetType
SetType
OutroType
)
# import devem ser colocados no top dos arquivos logo depois de qualquer
comentários ou qualquer docstrings, antes de constantes ou variaveis globais
[6] - Espaços em expressoes e instruções
#Não faça
funçõa( algo[ ] , { outro: 2})
#Faça:
funcao(algo[]), (outro:2})
#Não Faça:
algo (1)
#Faça:
algo(1)
#Não Faça
dict ['chave'] = lista [indice]
#Faça:
dic['chave'] = lista[indice]
#Não Faça:
x =1
y =2
#Faça:
x=1
y=2
[7] - Termine sempre uma instrução comm uma nova linha
"""
import this
|
eb2d21919bcf351569b4de102380a95502f59a4b | monicajoa/AirBnB_clone_v2 | /web_flask/2-c_route.py | 1,227 | 3.75 | 4 | #!/usr/bin/python3
""" C is fun
This module holds a script that starts a Flask web application
web application must be listening on 0.0.0.0, port 5000
Routes:
/: display “Hello HBNB!”
/hbnb: display “HBNB”
/c/<text> display “C ” followed by the value of the text variable
using the option strict_slashes=False in your route definition
"""
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def hello_hbnb():
""" Method that returns Hello text from a client requests
Returns:
[str]: Display “Hello HBNB!”
"""
return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
""" Method that returns HBNB text from a client requests
Returns:
[str]: Display “HBNB”
"""
return "HBNB"
@app.route('/c/<text>', strict_slashes=False)
def display_text(text):
""" Method that returns “C <text> from a client requests
Args:
text ([str]): variable in the url
Returns:
[str]: Display “C ” followed by the value of the text variable
"""
return "C {}".format(text.replace('_', ' '))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.