blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b0aef07a91f900947a13900a2fdeaa0d46ac336b | mrbahrani/File-Managment-AP-Project | /search.py | 6,306 | 3.890625 | 4 | """
| This file including all functions and variables needed for searching inside directories of all of the memory.
| The list of including functions:
| 1.return_equals
| 2.return_equals_step_by_step
| 3.search
| 4.step_by_step_search
|
| Including variables:
| 1.search_list:list
"""
from os import listdir
from funcs import drivers
from os.path import isdir
from funcs import remove_equals
from threading import Thread
from string import uppercase, lowercase
search_list = [] # This list contains search results
threads_list = []
class CompleteSearch(Thread):
"""
| This class is Thread class children.The return_equals stores all files and directories those are in
| or into the included directories of that with name equals word string. or returns the result
"""
def __init__(self, directory, word):
super(CompleteSearch, self).__init__()
self.directory = directory
self.word = word
self.is_pattern=False
if self.word[0] == '[' and self.word[-1] == ']':
self.is_pattern= True
print "Starting Pattern Search"
def return_equals(self, directory, word, result=search_list):
"""
| This void function saves all including files and directories with same name with word to the search_list list.
return_equals(directory, word[, result=search_list])
:rtype: object
:param directory:str
:param word:str
:param result:list
"""
try:
directories = listdir(self.directory)
except WindowsError:
directories = []
if "$Recycle.Bin" in directories:
directories.remove("$Recycle.Bin")
if "*\\*" in directories:
directories.remove("*\\*")
# print directories
for element in directories:
element = element.lower()
word = word.lower()
word_index = element.find(word)
if not element:
continue
elif self.is_pattern :
if self.search_s(element) :
result.append(directory + "\\" + element)
elif element.split('.')[-1] == "txt":
print element.split('.')[-1]
try:
text_file = open(self.directory + "\\" + element, 'r')
line = text_file.readline()
while line:
if search_s(line):
result.append([self.directory + "\\" + element, ])
break
line = text_file.readline()
text_file.close()
except IOError:
print 'kir'
print
elif element == self.word:
result.append(directory + "\\" + element)
elif word_index + 1:
# print directory + "\\" + element
result.append([self.directory + "\\" + element, word_index, word_index + len(word)])
elif element.split('.')[-1] == "txt":
print element.split('.')[-1]
try:
text_file = open(self.directory + "\\" + element, 'r')
line = text_file.readline()
while line:
if word in line:
result.append([self.directory + "\\" + element, word_index, word_index + len(word)])
break
line = text_file.readline()
text_file.close()
except IOError:
print 'kir'
print
elif isdir(directory + "\\" + element):
thread_obj = CompleteSearch(directory + "\\" + element, self.word)
threads_list.append(thread_obj)
thread_obj.start()
thread_obj.join()
def run(self):
self.return_equals(self.directory, self.word)
def search_s(self, word2):
order_word = self.word[1:len(self.word)-1].split()
pointer = 0
if order_word[0][0] == "^":
if word2[pointer:pointer+len(order_word[0])-1] == order_word[0][1:] :
return True
else:
for opp in order_word:
if len(opp) == 3 and opp[1] == "-":
if (ord(word2[pointer]) >= ord(opp[0])) and (ord(word2[pointer]) <= ord(opp[2])):
pointer += 1
else :
return False
elif opp[0] == "?" :
if word2[pointer:pointer+len(opp)-1] == opp[1:] :
return False
else :
pointer += len(opp) - 1
elif opp[0] == "*" :
pointer += 1
else:
if word2[pointer:pointer+len(opp)] == opp :
pointer += len(opp)
else :
return False
return True
def search(word, current_directory, search_result_list=search_list):
"""
| This function returns search results of files and directories with same name of word.
| First current directory searches and if there is any result, will return as a list
| If user searches in home page, all drivers searches for results and the result will return as a list;
search(word, current_directory[, search_result_list=search_list])
:param word:str
:param current_directory:str
:param search_result_list:list
:return list
"""
if search_result_list:
for counter in range(len(search_result_list)):
search_result_list.pop()
if current_directory:
searcher_object = CompleteSearch(current_directory, word)
searcher_object.start()
searcher_object.join()
return remove_equals(search_result_list)
else:
for cleaner in range(len(search_result_list)):
search_result_list.pop()
for driver in drivers():
searcher_object = CompleteSearch(driver, word)
searcher_object.start()
return remove_equals(search_result_list)
|
89e712cf0ccc852076c7994a0822af1f00262849 | kushinyi/Class0221_Project | /ClassP01.py | 249 | 3.546875 | 4 | grades=[[5,14,7],[23,36,28],[88,80,92]]
print(grades[0])
print(sum(grades[0])/len(grades[0])) #國文平均
print(sum(grades[1])/len(grades[1])) #英文平均
print(sum(grades[2])/len(grades[2])) #數學平均
grades.append([94,90,96])
print(grades) |
d405e3040ebb118d397716cce763b1309dfde8ca | asuhail1270106/ITMD-413_FP | /src/myDatabase.py | 4,038 | 3.90625 | 4 | # Programmed by Abdullah Suhail
# myDatabase.py
# 04/21/2018
# ITMD 413 Spring 2018 - Final Project
# Professor James Papademas
# This program will allow users to view and rate television shows
# from a database called shows.db using a GUI interface
# the sqlite3 module lets you create databases and manipulate them
# import show_data that has the data scraped from the "website" I created
import sqlite3
from sqlite3 import Error
import show_data
# function to create the database
def createDB():
# create a database connection to a SQLite database
try:
conn = sqlite3.connect('shows.db')
except Error as e:
print('createDB Error: ', e)
finally:
print ('Database Created')
conn.close()
# function to create the table in the database
def createTable():
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
c.execute('create table if not exists shows'
'(id integer primary key, show_name text not null, show_desc text not null, '
'show_rating integer)')
except Error as e:
print('createTable Error: ', e)
finally:
print('Table Created')
c.close()
conn.close()
# function to select a specific show description from the database
def selectShowdesc(show_name):
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
c.execute('select show_desc from shows where show_name = ?', (show_name,))
show_desc = c.fetchone()
return show_desc
except Error as e:
print ('selectShowdesc Error: ', e)
finally:
c.close()
conn.close()
# function to select all the shows in the database
def selectShows():
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
c.execute('select show_name from shows')
shows = c.fetchall()
return shows
except Error as e:
print ('selectShows Error: ', e)
finally:
c.close()
conn.close()
# function to select all the show ratings in the database
def selectShowrating():
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
c.execute('select * from shows where show_rating is not null')
ratings = c.fetchall()
return (ratings)
except Error as e:
print ('selectShows Error: ', e)
finally:
c.close()
conn.close()
# function to populate database with the show names and descriptions from show_data
def insertShows():
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
for name, desc in show_data.show_name_desc:
data = (name, desc)
sql = 'insert into shows (show_name, show_desc) values (?,?)'
c.execute(sql, data)
conn.commit()
except Error as e:
print('insertShows Error: ', e)
finally:
print('Database Populated')
c.close()
conn.close()
# function to updata a specific show rating in the DB
def updateShowrating(value, show_name):
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
sql = 'update shows set show_rating = ? where show_name = ?'
data = (value, show_name)
c.execute(sql, data)
conn.commit()
except Error as e:
print ('updateShowrating Error: ', e)
finally:
print ('Rating for ' + show_name + ' has been Updated')
c.close()
conn.close()
# function to empty the shows table
def deleteShows():
try:
conn = sqlite3.connect('shows.db')
c = conn.cursor()
c.execute('delete from shows')
conn.commit()
except Error as e:
print('deleteShows Error: ', e)
finally:
print('Table Emptied')
c.close()
conn.close()
# createDB()
# createTable()
# insertShows()
# selectShows()
# deleteShows()
|
a7ea1ea8e34a87ba829a58a542dd7ddb7d9fea6d | Nadine02/github_oer | /crawling/GitHubRepoFinderByTopic.py | 2,945 | 4.0625 | 4 | """ Find suitable repositories on Github, given a list of relevant topics.
Potentially interesting topics are listed in the topics list in the searching folder.
This script communicates with the Github API to request all known repositories, that are tagged with at least one of the given topics.
For each topic a file is created, that contains the found repositories.
To call this script with some basic authentication, it accepts a Github user name and the corresponding passwort or token.
"""
import os
import sys
import time
import requests
from github import Github, GithubException, RateLimitExceededException
# call this script via 'python3 GitHubRepoFinderByTopic.py <GitHub user name> <GitHub user password>'
g = Github(sys.argv[1], sys.argv[2])
script_path = os.path.dirname(os.path.realpath(__file__))
input_file = open(os.path.join(
script_path, "Searching", "Topics.txt"), "r")
topics = input_file.readlines()
input_file.close()
base_URL = "https://api.github.com/search/repositories?q=topic:"
i = 0
# iterate over all topics, to request all corresponding repositories
while i < len(topics):
try:
# remove unnecessary whitespace from topic
topic = topics[i].strip()
# current page counter for repsonses split up by pagination
page_counter = 1
# get maximum possible results in one response via per_page = 100
response = requests.get(base_URL + topic + "&page=" +
str(page_counter) + "&per_page=100")
repos = response.json()
file = open(os.path.join(script_path, "Searching", "ReposByTopic", topic + ".txt"),
"w")
print("Searching repos tagged with '" + topic + "'...")
for repo in repos["items"]:
git_repo = g.get_repo(repo["full_name"])
file.write(
str(git_repo.full_name) + ";" + str(git_repo.html_url) + ";\n")
file.close()
while len(repos["items"]) == 100:
page_counter += 1
response = requests.get(base_URL + topic + "&page=" +
str(page_counter) + "&per_page=100")
repos = response.json()
if repos["items"]:
file = open(
os.path.join(script_path, "Searching",
"ReposByTopic", topic + ".txt"),
"a")
for repo in repos["items"]:
git_repo = g.get_repo(repo["full_name"])
file.write(
str(git_repo.full_name) + "; " + str(git_repo.html_url) +
";\n")
file.close()
i += 1
except RateLimitExceededException:
print("Rate Limit exceeded")
print("Going to sleep for 15 min before restarting")
print("zzz...")
# sleep 15 min to reset rate limits
time.sleep(900)
|
d5b6a8d45514a33695ac231e635bd0e107096c38 | GreStas/PyBase20200110 | /lesson03_def.py | 140 | 3.578125 | 4 | def f1(val):
# тут Python выполняет va = переданное значение
print('val =', val)
a = f1(25)
print(a)
|
9551472aa37f2f47e4a8a86c0254ddc1cada5379 | Daewooer/CoolProblem | /main.py | 326 | 3.5625 | 4 | import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
|
106bc497fec81823250a248de6912a5c3458fcbf | Omkar-M/Coffee-Machine | /Problems/The Louvre/task.py | 377 | 3.9375 | 4 | class Painting:
def __init__(self, title1, artist1, year1):
self.title = title1
self.artist = artist1
self.year = year1
def print_value(self):
print(f'"{self.title}" by {self.artist} ({self.year}) hangs in the Louvre.')
title, artist, year = [input() for x in range(3)]
painting = Painting(title, artist, year)
painting.print_value()
|
d6ec5353a03833a20ebe4789d1a250762a79a6f0 | J4VJ4R/pythonCourse | /conditionals/ifarray.py | 117 | 3.625 | 4 | #!/usr/bin/python3
house1 = ['sr', 'ms', 'young', 'villain']
if 'villain' in house1:
print ("we found villain") |
71a4461971b219110e35c97714a7fdac5cb18c2f | ydyrx414/learn_py | /chapter6/exercise6-6.py | 324 | 4.03125 | 4 | favorite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
names = {'jen': 'python','sarah': 'c'}
for name in favorite_language.keys():
if name in names.keys():
print("Thank you for your participation")
else:
print("Please take the investigation")
|
fe162ee1d9ee4d13aedc26d2ffa75b0b6d2ff709 | hakancemG/Python-FaceRecognitionOnVideo | /Python Face Recognition on Video/face_recognition_video_pogram.py | 1,130 | 3.65625 | 4 | # Author : Hakan Cem Gerçek / hkncm-github.
# Face recognition by input video
#import 'OpenCV' & 'face recognition' libraries.
import cv2
import face_recognition_models
#Get a reference to video.
video_capture = cv2.VideoCapture('videoname.mp4')
#Declare path of Haarcascade.
face_cascade = cv2.CascadeClassifier('C:\Python37\Lib\site-packages\cv2\data\haarcascade_frontalface_alt2.xml')
while True:
#Grab a single frame of video.
ret, frame = video_capture.read()
#In OpenCV, frames usually turn into grayscale.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5)
#Display results.
for(x,y,w,h) in faces:
color = (0, 127, 255)
stroke = 2
end_cord_x = x + w
end_cord_y = y + h
cv2.rectangle(frame, (x,y), (end_cord_x, end_cord_y), color, stroke)
#Display the result of video.
cv2.imshow('Video',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#End.
video_capture.release()
cv2.destroyAllWindows()
# Author : Hakan Cem Gerçek / hkncm-github.
|
1dcd813e96f82ce2f7af94b6481cb54acea83d81 | srikanthpragada/pythondemo_21_june_2019 | /funs/pass_by_value.py | 356 | 3.625 | 4 | # Cannot change actual parameter through formal parameter as object is immutable
def change(n):
print(id(n))
n = 0
print(id(n))
# Can change actual parameter through formal parameter as object is mutable
def add_to_end(lst, v):
lst.append(v)
a = 100
print(id(a))
change(a)
print(id(a))
print(a)
l = [10, 20]
add_to_end(l, 30)
print(l)
|
3b6bf20b899b7dee3f63b15c84551fe9faae4c52 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/largest-series-product/1ebacb70a5944f35b45f2086a3d057fc.py | 786 | 3.53125 | 4 | class Series(object):
def __init__(self, numbers) :
self.numbers=[int(n) for n in numbers]
def slices(self, n) :
"""Produces all series of length n from the sequence
Raises ValueError if n<=0 or longer than the sequence
"""
if n <= 0 or n > len(self.numbers) :
raise ValueError(
"Invalid slice length for this series: {0}".format(n) )
return [list(self.numbers[x: x + n] )
for x in range(0, len(self.numbers)-n + 1) ]
def largest_product(self, n):
if n > 0:
return max([ Series.product(slc) for slc in self.slices(n) ] )
else:
return 1
@staticmethod
def product(inlist):
return reduce(lambda x,y: x*y,inlist,1)
|
e5db940fd61bba76dafc849b54ea26e8aaf15aed | Ryxai/harp | /heapqueue.py | 6,243 | 3.859375 | 4 | from typing import *
from math import floor
class HeapQueue:
"""
Derived from Skeina's heapqueue implementation provides a heapq like interface with the a key function
(and type annotations!), does not require mappings to reorder a priority queue. Note that implicitly this is a
minheap and can be turned into a max heap queue with the use of the multiplicative inverse.
"""
def __init__(self, key: Callable[Any, int] = None):
"""
Initializes the heapqueue class, can use the default heapqueue sorting method or provide a key function
:param key:
"""
if not key:
self.__key__ = lambda x: x
else:
self.__key__ = key
@staticmethod
def __parent__(index: int) -> int:
"""
Returns the index of the parent element of the priority queue. If the current element is the root returns -1
:param index: The index of the element in the binary heap to get the parent of
:return: The index of the parent element or -1 if the index is already the root
"""
if index < 1:
return -1
else:
return int(floor(index / 2))
@staticmethod
def __young_child__(index: int) -> int:
"""
Gets the left-most child of the current node at the given index
:param index: An integer representing the index of the current node in the heap
:return: An integer representing the index of the left-most child node
"""
return 2 * index
@staticmethod
def __swap__(heap: List[Any], first_index: int, second_index: int) -> List[Any]:
"""
Trades the values of the nodes
:param heap: A heap implemented as a List of a given type
:param first_index: The index of the first element to be swapped
:param second_index:The index of the second element to be swapped
:return: The heap with the elements at first_index and second_index swapped
"""
temp = heap[first_index]
heap[first_index] = heap[second_index]
heap[second_index] = temp
return heap
def __bubble_down__(self, heap: List[Any], index: int) -> List[Any]:
"""
Swaps and transfers values down the heap maintaining the minheap invariant
:param heap: The heap
:param index: The index of the current element to perform a bubble_down on, can be called from
within a __bubble_down__ call
:return The heap with the target value having been bubbled down the heap
"""
child_index = self.__young_child__(index)
min_index = index
i = 0
while i <= 1:
if child_index + i <= len(heap) and self.__key__(heap[min_index]) > self.__key__(heap[child_index + i]):
min_index = child_index + i
i = i + 1
if min_index != index:
heap = self.__swap__(heap, index, min_index)
heap = self.__bubble_down__(heap, min_index)
return heap
def __bubble_up__(self, heap: List[Any], index: int) -> List[Any]:
"""
Bubbles a value up the heap as per the minheap invariant
:param heap: The heap
:param index: The index of the current value to bubble up
:return:
"""
if self.__parent__(index) == -1:
return heap
parent_index = self.__parent__(index)
if self.__key__(heap[parent_index]) > self.__key__(heap[index]):
heap = self.__swap__(heap, index, parent_index)
return self.__bubble_up__(heap, parent_index)
def pop(self, heap: List[Any]) -> Union[IndexError, [Any, List[Any]]]:
"""
Removes the top element from the heap and then replaces it with the next minimal element while maintaining the
heap invariant.
:param heap: The heap to retrieve an element from
:return:A tuple containing the removed element and the remaining heap
"""
if len(heap) == 0:
raise IndexError("Heap length cannot be zero.")
ret = heap[0]
heap = heap[1:]
return ret, self.__bubble_down__(heap, 1)
def push(self, heap: List[Any], item: Any) -> List[Any]:
"""
Pushes a new value onto the heap and then correctly locates it according to the invariant
:param heap: The heap to push an element to
:param item: The item to push into the heap
:return: The heap with the item inserted into a correction according to the invariant
"""
heap.append(item)
return self.__bubble_up__(heap, len(heap) - 1)
@staticmethod
def peek(heap: List[Any]) -> Any:
return heap[0]
def pushpop(self, heap: List[Any], item: Any) -> Union[IndexError, [Any, List[Any]]]:
"""
Pushes a new item onto the heap and then retrieves the minimal item from the heap. Is faster then a separate
push & pop.
:param heap: The heap from which to obtain a min item and to push one too
:param item: The item to push onto the heap
:return: A tuple containing the popped item and the updated heap
"""
if self.__key__(heap[0]) > self.__key__(item):
return item, heap
else:
item, heap[0] = heap[0], item
return item, self.__bubble_up__(heap, 0)
def heapreplace(self, heap: List[Any], item: Any) -> Union[IndexError, [Any, List[Any]]]:
"""
Pops an item from the heap and then pushes a new item to it. Is faster then a pop & push.
:param heap: THe heap tp pop and item from and then push one to
:param item:The item to push to the heap
:return: A tuple containing the popped item and the updated heap
"""
ret = heap[0]
heap[0] = item
return ret, self.__bubble_down__(heap, 0)
def heapify(self, heap: List[Any]) -> List[Any]:
"""
Transforms a list into a heap, in O(len(x)) time
:param heap: The input list of items to be transformed into a heap
:return: The list transformed into a heap
"""
for i in range(0, len(heap) - 1):
heap = self.__bubble_down__(heap, i)
return heap
|
65272af12146c9cd1f47e084a68d557f1d1073dd | uloga/python_misc | /classes/switch.py | 813 | 4.03125 | 4 | #######################
# simple switch class
class Switch:
def __init__(self, case=None):
self.case = case
def __iter__(self):
yield self.match #yield match once
raise StopIteration
def match(self, *args):
if self.case in args:
return True
else:
return False
def main():
value = 'three'
for case in Switch(value):
if case('one'):
print('this is first')
break
if case('two'):
print('this is second')
break
if case('three'):
print('this is third')
break
if case('four'):
print('tis is fourth')
break
else:
print("This is a default")
if __name__ == '__main__': main()
|
f733f6d9a8c06061bb5ed1e69e1ce3b3a9a0b9b4 | liyl0663/liyl | /python/day05/zhan.py | 634 | 3.8125 | 4 | stack = []
def push_it():
item = input('item to push:')
stack.append(item)
def pop_it():
if stack:
print('\033[33mfrom stack poped %s\033[0m' % stack.pop())
def view_it():
print(stack)
def show_menu():
cmd = {'0':push_it,'1':pop_it,'2':view_it}
prompt = """(0)push it
(1)pop it
(2)view it
(3)exit
please input your choice(0/1/2/3):"""
while True:
choice = input(prompt).strip()
if choice not in '0123':
print('invalid input,try again')
continue
if choice == '3':
break
cmd[choice]()
if __name__ == '__main__':
show_menu()
|
65c8255a5322263c489c6657bfd3badec9ec8122 | YoungHo-Jo/algo | /Backjoon/02166_포도주_시식/main.py | 491 | 3.625 | 4 | n = int(input())
cups = []
for _ in range(n):
cups.append(int(input()))
cache = [[0 for _ in range(3)] for _ in range(n)] # [the index of the cup][the number of cups that was drunken]
for wineIdx in range(n):
if wineIdx == 0:
cache[wineIdx][1] = cups[wineIdx]
continue
cache[wineIdx][0] = max(cache[wineIdx - 1])
cache[wineIdx][1] = cache[wineIdx - 1][0] + cups[wineIdx]
cache[wineIdx][2] = cache[wineIdx - 1][1] + cups[wineIdx]
print(max(cache[n - 1]))
|
c103b75e0243d8f6faa151868ea32e6c291694fb | YoyinZyc/Leetcode_Python | /Google/Pro270. Closest Binary Search Tree Value.py | 965 | 4.03125 | 4 | '''
题意:
找到BST中和target最接近的数字
注意这个target是float类型的
本质是遍历BST
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
sub = float('inf')
last_val = 0
while root:
if root.val < target:
if target - root.val < sub:
last_val = root.val
sub = target-root.val
root = root.right
elif root.val > target:
if root.val- target < sub:
last_val = root.val
sub = root.val-target
root = root.left
else:
return root.val
return last_val |
56f79c894d52bc721f9551f0e965b82a5f8fc186 | xdr940/utils | /grd_depth/test3.py | 629 | 3.515625 | 4 | #d(dx,alpha,h)
#当dx增大时, d的关系为越大越正比
import numpy as np
import matplotlib.pyplot as plt
import math
from math import pi
from numpy import sin,sqrt,tan
#x = [0:0.1:pi]
theta = np.linspace(0,pi/4,100)
#ag = 45
#alpha = ag*2*pi/360
alpha45 = pi/8
alpha30 = pi/36
h=50
dx = np.linspace(0,30*h,100)
#print(temp)
#y= (sin(alpha+theta)/sin(pi/2 + theta))
d45 = sqrt((1+tan(pi/4-alpha45)**2)*h**2 + dx**2 +2*h*dx*tan(pi/4 - alpha45))
d30 = sqrt((1+tan(pi/4-alpha30)**2)*h**2 + dx**2 +2*h*dx*tan(pi/4 - alpha30))
plt.plot(dx,d45,'b',label = 'alpha45')
plt.plot(dx,d30,'r',label='alpha30')
plt.legend()
plt.show() |
e7501d120782211ff24415b53cbb39e9a1948644 | haoxu13/ud120-projects | /outliers/outlier_cleaner.py | 765 | 3.78125 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
"""
cleaned_data = []
### your code goes here
### return error tuple (age, net_worth, error)
### then discard 10% of the largest residual error
residual_error = map(lambda (x1, x2, x3):(x1, x2, (x2-x3)**2), zip(ages, net_worths, predictions))
residual_error.sort(key = lambda x: x[2])
cleaned_data = residual_error[:(int)(round(0.9*len(predictions)))]
return cleaned_data
|
8d0cedd8f61f6e7aef01946913a4d833dc3c6554 | Caaddss/livros | /gui.py | 4,479 | 3.828125 | 4 | from tkinter import *
class gui():
window = Tk()
window.wm_title("Minha Biblioteca")
# Variáveis
txtTitulo = StringVar()
txtSubtitulo = StringVar()
txtEditora = StringVar()
txtAutor1 = StringVar()
txtAutor2 = StringVar()
txtAutor3 = StringVar()
txtCidade = StringVar()
txtAno = StringVar()
txtEdicao = StringVar()
txtPaginas = StringVar()
txtVolume = StringVar()
# Objetos que estarão na tela
lbltitulo = Label(window, text="Título")
lblsubtitulo = Label(window, text="Subtítulo")
lbleditora = Label(window, text="Editora")
lblautor_1 = Label(window, text="1º Autor")
lblautor_2 = Label(window, text="2º Autor")
lblautor_3 = Label(window, text="3º Autor")
lblcidade = Label(window, text="Cidade")
lblano = Label(window,text="Ano da Publicação")
lbledicao = Label(window, text="Edição")
lblpaginas = Label(window,text="Páginas")
lblvolume = Label(window, text="Volume")
# Campos de input
enttitulo = Entry(window, textvariable=txtTitulo)
entsubtitulo = Entry(window,textvariable=txtSubtitulo)
enteditora = Entry(window, textvariable=txtEditora)
entautor1 = Entry(window, textvariable=txtAutor1)
entautor2 = Entry(window, textvariable=txtAutor2)
entautor3 = Entry(window, textvariable=txtAutor3)
entcidade = Entry(window, textvariable=txtCidade)
entano = Entry(window, textvariable=txtAno)
entedicao = Entry(window, textvariable=txtEdicao)
entpaginas = Entry(window, textvariable=txtPaginas)
entvolume = Entry(window, textvariable=txtVolume)
# Listbox com os livros cadastrados
listLivros = Listbox(window)
# Scrollbar para funcionar junto com a listLivros
scrollLivros = Scrollbar(window)
# Botões
btnViewAll = Button(window, text = "Ver todos")
btnBuscar = Button(window, text = "Buscar")
btnInserir = Button(window, text = "Inserir")
btnUpdate = Button(window, text = "Atualizar Selecionados")
btnDel = Button(window, text = "Deletar Selecionados")
btnClose = Button(window, text = "Fechar")
# Associar os objetos a grid da janela, primeiro as labels
lbltitulo.grid(row=0, column=0)
lblsubtitulo.grid(row=1, column=0)
lbleditora.grid(row =2, column=0)
lblautor_1.grid(row=3, column=0)
lblautor_2.grid(row=4, column=0)
lblautor_3.grid(row=5, column=0)
lblcidade.grid(row=6, column=0)
lblano.grid(row=7, column=0)
lbledicao.grid(row=8, column=0)
lblpaginas.grid(row=9, column=0)
lblvolume.grid(row=10, column=0)
# Depois as entrys
enttitulo.grid(row=0, column=1)
entsubtitulo.grid(row=1, column=1)
enteditora.grid(row=2, column=1)
entautor1.grid(row=3, column=1)
entautor2.grid(row=4, column=1)
entautor3.grid(row=5, column=1)
entcidade.grid(row=6, column=1)
entano.grid(row=7, column=1)
entedicao.grid(row=8, column=1)
entpaginas.grid(row=9, column=1)
entvolume.grid(row=10, column=1)
# Posicionando os Botões
btnViewAll.grid(row=13,column=0,columnspan=2) #columnspan quando algo ocupa mais de uma coluna
btnBuscar.grid(row=14, column=0,columnspan=2)
btnInserir.grid(row=15, column=0,columnspan=2)
btnUpdate.grid(row=16, column=0, columnspan=2)
btnDel.grid(row=17, column=0, columnspan=2)
btnClose.grid(row=18, column=0, columnspan=2)
# Posicionando a lista e o scrollLivros
listLivros.grid(row=0, column=2,rowspan=10) #rowspan quando algo ocupa mais de uma linha
scrollLivros.grid(row=0, column=6, rowspan=10)
# Associando o Scrollbar com a Listbox
listLivros.configure(yscrollcommand=scrollLivros.set) # yscrollcommand responsável por definir qual objeto sera responsavel por acompanhar o rolamento vertical
scrollLivros.configure(command=listLivros.yview) # qual função será chamada quando a ScrollBar for ativada
# Vamos agora arrumar a aparência
x_pad = 5
y_pad = 3
width_entry = 50
for child in window.winfo_children():
widget_class = child.__class__.__name__
if widget_class == "Button":
child.grid_configure(sticky='WE', padx=x_pad, pady=y_pad)
elif widget_class == "Listbox":
child.grid_configure(padx=0, pady=0, sticky='NS')
elif widget_class == "Scrollbar":
child.grid_configure(padx=0, pady=0, sticky='NS')
else:
child.grid_configure(padx=x_pad, pady=y_pad, sticky='N')
def run(self):
gui.window.mainloop()
|
14b4258232a1c746f58ffaa7d862715ff76552bd | Programmerryoki/Matrix | /MatrixClass.py | 1,042 | 3.515625 | 4 | from typing import List, Tuple
class Matrix:
matrix = None
_size = None
def __init__(self, size: Tuple[int] = None,
matrixlist: List[List[int]] = None,
matrix: "Matrix" = None,
**kwargs):
if size:
self._size = size
def size(self) -> Tuple[int]:
return self._size()
def __eq__(self, other: "Matrix") -> bool:
def __bool__(self) -> bool:
return bool(self.size() and self.matrix)
def __add__(self, other: "Matrix") -> "Matrix":
def __sub__(self, other: "Matrix") -> "Matrix":
def __mul__(self, other: "Matrix") -> "Matrix":
def __str__(self) -> str:
ml = max(max(len(str(i)) for i in j) for j in self.matrix) + 1
return "\n".join(f"| {' '.join(f'{j:>{ml}}' for j in i)} |" for i in self.matrix)
def __copy__(self) -> "Matrix":
return self
def __deepcopy__(self, memodict={}) -> "Matrix":
new = Matrix(matrix=self)
memodict[id(new)] = new
return new
|
00235c84fbcc27127eb166d416161cdc4f2daca2 | moonseokho85/TIL | /A.I/10_Keras/keras15_LSTM3_verbose.py | 1,215 | 3.5625 | 4 | from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 데이터 준비
x = array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12], [20, 30, 40], [30, 40, 50], [40, 50, 60]])
y = array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 50, 60, 70])
print("shape of x: ", x.shape)
print("shape of y: ", y.shape)
x = x.reshape(x.shape[0], x.shape[1], 1)
# 모델 구성
model = Sequential()
model.add(LSTM(64, activation='relu', input_shape=(3, 1))) # 3: column number & 1: 몇개씩 자르는지
model.add(Dense(128))
model.add(Dense(64))
model.add(Dense(32))
model.add(Dense(1))
model.summary()
model.compile(loss= 'mse', optimizer= 'adam', metrics= ['mae'])
model.fit(x, y, epochs= 100, verbose= 0, batch_size= 3) # 앙상블 모델일 때 입력값을 리스트 형식으로 넣어준다.
# 평가 예측
loss, mae = model.evaluate(x, y, batch_size= 3)
print("loss: ", loss)
print("mae: ", mae)
x_input = array([[6.5, 7.5, 8.5], [50, 60, 70], [70, 80, 90], [100, 110, 120]]) # (3,) -> (1, 3) -> (1, 3, 1)
x_input = x_input.reshape(4, 3, 1)
y_predict = model.predict(x_input)
print("y_predict: ", y_predict)
|
840cfd3c122dba5807f38e7bb62b39bc952f126a | Krishna219/Fundamentals-of-computing | /Principles of Computing (Part 2)/Week 2/my_solution.py | 2,154 | 3.84375 | 4 | def triangular_sum(num):
"""
Sum of n numbers
"""
if num == 0:
#base case
return 0
else:
return num + triangular_sum(num - 1)
#recursive case
for i in range(11):
print triangular_sum(i)
def number_of_threes(num):
if num//10 == 0:
if num == 3:
return 1
else:
return 0
else:
if num%10 == 3:
return 1 + number_of_threes(num//10)
else:
return number_of_threes(num//10)
print number_of_threes(3453433)
def is_member(my_list, elem):
if len(my_list) == 1:
return my_list[0] == elem
else:
if elem == my_list[0]:
return True
else:
return is_member(my_list[1:], elem)
print is_member(['c', 'a', 't'], 'q')
def remove_x(my_string):
if len(my_string) == 1:
if my_string == 'x':
return ""
else:
return my_string
else:
if my_string[0] == 'x':
return remove_x(my_string[1:])
else:
return my_string[0] + remove_x(my_string[1:])
print remove_x("catxxdogx")
def insert_x(my_string):
if len(my_string) == 2:
return my_string[0] + "x" + my_string[1]
else:
return my_string[0] + "x" + insert_x(my_string[1:])
print insert_x("catdog")
def list_reverse(my_list):
if len(my_list) == 1:
return my_list
else:
return [my_list[-1]] + list_reverse(my_list[0:-1])
print list_reverse([2, 3, 1])
def gcd(num1, num2):
if num2 > num1:
return gcd(num2, num1)
else:
if num2 == 0:
return num1
else:
return gcd(num2, num1 - num2)
print gcd(1071, 462)
def slice(my_list, first, last):
if first > len(my_list) or last > len(my_list) or first >= last:
return []
else:
first_elem = my_list[first]
print first_elem
return [first_elem] + slice(my_list, first + 1, last)
print slice(['a', 'b', 'c', 'd', 'e'], 2, 4)
print slice([10,21,34,56,78,90,101,23,45,67,89], 5, 9), [10,21,34,56,78,90,101,23,45,67,89]
|
6f00c9332978c5bb23d1255d66197ac79d899c68 | cosJin/LeetCode | /old/Hash/136.py | 392 | 3.59375 | 4 | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
dic = 0
for i in range(len(nums)):
if i%2 == 0:
dic+=nums[i]
elif i%2 == 1:
dic-=nums[i]
return dic
test = Solution()
print(test.singleNumber([1,2,1,4,4,2,3])) |
4e604e60fdf3f403e59c2b77c0704eb70d1669ef | sebastinaa/python-learn | /数据分析/code/numpy/03-NumPy数组属性.py | 1,019 | 3.5 | 4 | # -*- coding:utf-8 -*-
import numpy as np
'''
ndarray.shape
这个数组属性返回一个包含数组维度的元组,它也可以用于调整数组大小
'''
# a = np.array([[1,2,3],[4,5,6]])
# print(a)
# print(a.shape)
#调整数组大小
# a = np.array([[1,2,3],[4,5,6]])
# a.shape=(3,2)
# print(a)
'''
reshape 调整数组大小
'''
# a = np.array([[1,2,3],[4,5,6]])
# b = a.reshape(3,2)
# print(b)
'''
ndarray.ndim 返回数组的维数
'''
# a = np.arange(24)
# print(a)
# print(a.ndim)
# b = a.reshape(2,4,3)
# print(b)
# print(b.ndim)
# print(b.shape)
'''
numpy.itemsize
返回数组中每个元素的字节单位长度
'''
#数组的int8 一个字节
# x = np.array([1,2,3,4,5], dtype = np.int8)
# print(x.itemsize)
#数组的float32 4个字节
# x = np.array([1,2,3,4,5], dtype = np.float32)
# print(x.itemsize)
'''
ndarray.size
返回数组的大小,即shape中的乘积
'''
arr = np.arange(18).reshape(2,3,3)
print(type(str(arr)))
print(arr.shape)
print(arr.size)
|
b11e53e7e8eb9728742da025cf1cb147ef3e7a6c | ryanyuchen/Data-Structure-and-Algorithms | /1 Algorithmic Toolbox/Week 2 Algorithmic Warm-up/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 811 | 3.703125 | 4 | # Uses python3
import random
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
def calc_fib_fast(n):
if (n <= 1):
return n
else:
res = [None] * (n+1)
res[0] = 0
res[1] = 1
for i in range(2,n+1):
res[i] = res[i-1] + res[i-2]
return res[n]
def stress_test(m):
k = 0
while (k < 100):
n = random.randint(1, m)
res1 = calc_fib(n)
res2 = calc_fib_fast(n)
print("\n")
if (res1 != res2):
print("Wrong Answer: ", res1, " ", res2, "\n")
k = k + 1
break
else:
print("OK\n")
k = k + 1
stress_test(40)
n = int(input())
print(calc_fib(n))
print(calc_fib_fast(n))
|
3b44be6e0ff4632d9d0aab239c1e371f25990e18 | arpanmangal/Abusive-Language-Style-Transfer | /model/convert.py | 448 | 3.609375 | 4 | """
Converting the Abusive Speech to Normal Speech
"""
import re
from . import translate as tr
from . import preprocess as pp
def convert (sentence, mode='fr'):
"""
Remove the hate and convert to non-offensive sentence
"""
processed_sentence = pp.preprocess(sentence)
if (len (processed_sentence) < 2):
processed_sentence = "Please enter longer sentence ."
return tr.translate (processed_sentence, target=mode)
|
b83cbc8ce1f749e6468e397192a6b3bda08a2822 | alehpineda/python_morsels | /orderedset/orderedset.py | 1,744 | 3.59375 | 4 | from collections.abc import MutableSet, Sequence
class OrderedSet(MutableSet):
def __init__(self, items):
self.items = dict.fromkeys(items, None)
def __iter__(self):
for item in self.items:
yield item
def __len__(self):
return len(self.items)
def __contains__(self, item):
return item in self.items
# Bonus 1 - add and discard
def add(self, item):
self.items[item] = None
def discard(self, item):
self.items.pop(item, None)
# Bonus 2 - Equality
def __eq__(self, other):
if not isinstance(other, OrderedSet):
return self.items.keys() == other
return tuple(self.items.keys()) == tuple(other.items.keys())
# Bonus 3 - Supports index
def __getitem__(self, i):
return list(self.items.items())[i][0]
class OrderedSet2(Sequence, MutableSet):
"""Set-like object that maintains insertion order of items."""
def __init__(self, iterable):
self.items = set()
self.order = []
self |= iterable
def __contains__(self, item):
return item in self.items
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.order[index]
def add(self, item):
if item not in self.items:
self.order.append(item)
self.items.add(item)
def discard(self, item):
if item in self.items:
self.order.remove(item)
self.items.remove(item)
def __eq__(self, other):
if isinstance(other, type(self)):
return len(self) == len(other) and all(
x == y for x, y in zip(self, other)
)
return super().__eq__(other)
|
e51e438204075eb19f20cbd51aed8915e43365e1 | erjan/coding_exercises | /number_of_closed_islands.py | 4,265 | 3.546875 | 4 | '''
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
'''
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(i,j):
if grid[i][j]==1:
return True
if i<=0 or i>=m-1 or j<=0 or j>=n-1:
return False
grid[i][j]=1
up=dfs(i-1,j)
down=dfs(i+1,j)
left=dfs(i,j-1)
right=dfs(i,j+1)
return left and right and up and down
m,n = len(grid),len(grid[0])
c=0
# iterate through the grid from 1 to length of grid for rows and columns.
# the iteration starts from 1 because if a 0 is present in the 0th column, it can't be a closed island.
for i in range(1,m-1):
for j in range(1,n-1):
# if the item in the grid is 0 and it is surrounded by
# up, down, left, right 1's then increment the count.
if grid[i][j]==0 and dfs(i,j):
c+=1
return c
--------------------------------------------------------------------------------------------------------------------
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
## RC ##
## APPROACH : DFS ##
## LOGIC ##
## 1. Find, Islands just like normal Leetcode 200. Number of Islands problem.
## 2. While doing so, check if every land block, is not in the border.
## 3. If it is in the border, mark that Island as Invalid island and after traversal donot include in the count
def dfs( i, j, visited):
if( (i,j) in visited ):
return
if not self.inValidIsland and ( i== 0 or j == 0 or i == m-1 or j == n-1 ):
self.inValidIsland = True
visited.add((i,j))
for x,y in directions:
if 0 <= i+x < m and 0 <= j+y < n and grid[i+x][j+y] == 0:
dfs( i+x, j+y, visited )
if not grid: return 0
m, n = len(grid), len(grid[0])
count, visited = 0, set()
directions = [(0,1),(1,0),(0,-1),(-1,0)]
for i in range(m):
for j in range(n):
self.inValidIsland = False
if (i,j) not in visited and grid[i][j] == 0:
dfs( i, j, visited )
count = count + (1 if( not self.inValidIsland ) else 0)
return count
-----------------------------------------------------------------------------------------------------------
class Solution(object):
def closedIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
count =0
# iterate through the grid from 1 to length og grid for rows
# and columns.
# the iteration starts from 1 because if a 0 is present
# in the 0th column, it can't be a closed island.
for i in range(1, len(grid)-1):
for j in range(1, len(grid[0])-1):
# if the item in the grid is 0 and it is surrounded by
# up, down, left, right 1's then increment the count.
if grid[i][j] == 0 and self.dfs(grid, i , j):
count +=1
return count
def dfs(self, grid, i, j):
# if grid[i][j] is 1 then return True, this helps is checking the
# final return conditons.
if grid[i][j]==1:
return True
# now check if the element 0 is present at the outmost rows and column
# then return False
if i<=0 or j<=0 or i>=len(grid)-1 or j >=len(grid[0])-1:
return False
# initialize the item as 1
grid[i][j] = 1
# now check the conditions for up, down, left, right
up = self.dfs(grid, i+1, j)
down = self.dfs(grid, i-1, j)
right = self.dfs(grid, i, j+1)
left = self.dfs(grid, i, j-1)
# if up, down , left, right is True, then return to main function
return up and down and left and right
|
c3a073ad2a536f86db97e1b4850fb956d516e547 | ryeLearnMore/LeetCode | /078_subsets.py | 1,978 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#@author: rye
#@time: 2019/3/20
# 这是什么神仙思路啊,好难。。。
'''
想到有可能用递归去做,但是真的不知道怎么实现。多学习。。。
其他解题思路:https://github.com/ryeLearnMore/awesome-algorithm/blob/master/docs/Leetcode_Solutions/Python/078._Subsets.md
19.3.23。又看了一遍,觉得这种回溯方法设计的很巧妙,值得多学习,多看几遍。
'''
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
def search(tmp_res, idx):
if idx == len(nums):
res.append(tmp_res)
else:
search(tmp_res + [nums[idx]], idx + 1)
search(tmp_res, idx + 1)
search([], 0)
return res
# --------------------19.4.28----------又有点忘了------------
# 结果:[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
'''
根据递归的思想:因为解题方式不变,所以把大规模的问题分解为小规模的问题,
可以观察到[[1, 2, 3], [1, 2], [1, 3], [1] ||| [2, 3], [2] ||| [3] ||| []]
先1不动,让2,3去变化,然后2不动,让3去变化,以此类推。。。
基于上述思想,可以总结为解题方式为:先让第一个元素不动,找出后面的子集,然后让第二个元素不动
找出后面的子集。。。
idx是关键!
'''
def subsets(nums):
res = []
def search(tmp_res, idx):
if len(nums) == idx:
res.append(tmp_res)
else:
search(tmp_res + [nums[idx]],idx + 1)
search(tmp_res, idx + 1)
search([], 0)
return res
if __name__ == '__main__':
nums = [1, 2, 3]
print(Solution().subsets(nums))
print(subsets(nums)) |
c314c987271d06da9caf75f949517c4d30d95da9 | HEKA313/lab_8 | /Task.py | 3,436 | 4.03125 | 4 | import math
import sys
def is_there_the_triangle(a1, b1, c1, a2, b2, c2): # Проверка существования треугольника
check = True
if a1 <= 0 or b1 <= 0 or c1 <= 0 or a2 <= 0 or b2 <= 0 or c2 <= 0:
print("Треугольника с отрицательными сторонами не бывает)")
check = False
if not (a1 + b1 > c1 and a1 + c1 > b1 and b1 + c1 > a1):
print("Треугольника со сторонами ({}, {}, {}) не существует".format(a1, b1, c1))
check = False
if not (a2 + b2 > c2 and a2 + c2 > b2 and b2 + c2 > a2):
print("Треугольника со сторонами ({}, {}, {}) не существует".format(a2, b2, c2))
check = False
return check
def similarity_check(triangle1, triangle2): # Проверка подобия
if triangle1[0] / triangle2[0] == triangle1[1] / triangle2[1] == triangle1[2] / triangle2[2]:
check = True
else:
check = False
return check
def finding_the_area(triangle): # нахождение площади
p = (triangle[0] + triangle[1] + triangle[2]) / 2
s = math.sqrt(p * (p - triangle[0]) * (p - triangle[1]) * (p - triangle[2]))
return s
def finding_the_perimeter(triangle): # нахождение периметра
return triangle[0] + triangle[1] + triangle[2]
name_file = sys.argv[1] # чтение командной строки
file = open(name_file, 'r') # открытие файла
n = int(file.readline()) # считывание количества треугольников
# инициализация массивов
triangles1 = [0] * n
triangles2 = [0] * n
for i in range(n):
triangles1[i] = [0] * 3
triangles2[i] = [0] * 3
for i in range(n): # считывание массивов
line = file.readline().split()
for j in range(3):
triangles1[i][j] = int(line[j])
triangles2[i][j] = int(line[3 + j])
# инициализация переменных
count = 0
square = [0] * n
perimeter = [0] * n
for i in range(n):
a1, b1, c1 = triangles1[i][0], triangles1[i][1], triangles1[i][2]
a2, b2, c2 = triangles2[i][0], triangles2[i][1], triangles2[i][2]
if is_there_the_triangle(a1, b1, c1, a2, b2, c2): # существуют ли треугольники
if similarity_check(triangles1[i], triangles2[i]): # подобны ли треугольники
# подсчет количества подобных треуг и нахождения площади и периметра
count += 1
square[i] = (finding_the_area(triangles1[i]) + finding_the_area(triangles2[i]))
perimeter[i] = (finding_the_perimeter(triangles1[i]) + finding_the_perimeter(triangles2[i]))
if count != 0: # проверка на количество подобных треугольников
print("Количество пар подобных треугольников равно: {}".format(count))
print("Суммарные площади каждой пары подобных треугольников равны:")
for elem in square: # вывод площадей
if elem != 0:
print("{}".format(elem))
print("Суммарные периметры каждой пары подобных треугольников равны:")
for elem in perimeter: # вывод периметров
if elem != 0:
print("{}".format(elem))
else:
print("Подобные треугольники не были найдены")
print()
|
43cc94ecb08bb6ef18a3c57c4c6d2034df30f78b | NikhilaBanukumar/GeeksForGeeks-and-Leetcode | /insertionsort.py | 234 | 3.734375 | 4 | # O(n2)
def insertion(a):
for i in range(1,len(a)):
key=a[i]
j=i-1
while j>=0 and key<a[j]:
a[j+1]=a[j]
j-=1
a[j+1]=key
return a
a=[12,11,13,5,6]
print(insertion(a))
|
9eddee6a143a46e42055bdac8f016a98a8d7a748 | python-practice-b02-927/vernovskaya | /lab2/task72.py | 189 | 3.59375 | 4 | import turtle
from math import sin
from math import cos
from math import pi
t = turtle.Turtle()
t.shape('turtle')
for i in range(1, 100):
t.goto(i*sin(pi/10), i*cos(pi/10))
input()
|
78c99a618d4d0f7f72b9af5c6cf11fee1d8dc716 | santoshpy/algorithms-1 | /heap.py | 2,087 | 3.859375 | 4 | import sys
MAX_INT = sys.maxint
'''
Heap data structure
-------------------
Maintains a balanced binary tree, where the value of each node is never larger than the values of its children.
The tree is represented using an array, since it is easy to calculate the index of the parent/child of a given
element (see __find_parent_index/__find_child_indexes)
'''
class Heap:
def __init__(self):
self.l = []
def insert(self, value):
self.l.append(value)
index_of_value = len(self.l) - 1
while index_of_value:
index_of_parent = self.__find_parent_index(index_of_value)
value_of_parent = self.l[index_of_parent]
if value_of_parent > value:
self.__swap(index_of_value, index_of_parent)
index_of_value = index_of_parent
else:
break
def extract_min(self):
count = len(self.l)
if count == 0:
return None
min_value = self.l.pop(0)
count -= 1
if count == 0:
return min_value
last_value = self.l.pop(count - 1)
self.l.insert(0, last_value)
i = 0
value = last_value
while True:
i1, i2 = self.__find_child_indexes(i)
v1 = MAX_INT if i1 is None else self.l[i1]
v2 = MAX_INT if i2 is None else self.l[i2]
if value <= min(v1, v2):
break
elif v1 <= v2:
self.__swap(i1, i)
i = i1
else:
self.__swap(i2, i)
i = i2
return min_value
def __swap(self, i1, i2):
self.l[i1], self.l[i2] = self.l[i2], self.l[i1]
def __find_parent_index(self, i):
return i / 2 # Python discards remainders for integer division, which is what we need here
def __find_child_indexes(self, i):
max_index = len(self.l) - 1
i1 = i*2
i2 = i1 + 1
if i1 > max_index:
return None, None
else:
return i1, None if i2 > max_index else i2 |
8b673813e87f5615b55bfaf22cd7c0b5c56a4f6f | Fulvio7/curso-python-guppe | /guppe/exercicios_secao_8/ex_11.py | 1,087 | 4.15625 | 4 | """
11- Elabore uma função que receba três notas de uma aluno como
parâmetros e uma letra. Se a letra for 'A', a função deve retornar a
média aritmética das notas do aluno; se for 'P', deverá calcular a média
ponderada, com pesos: 5, 3 e 2.
"""
def calcula_media(nota1, nota2, nota3, tipo_media):
if tipo_media == 'A':
media = (nota1 + nota2 + nota3) / 3
return media
elif tipo_media == 'P':
media = ((nota1 * 5) + (nota2 * 3) + (nota3 * 2)) / 10
return media
return 'Erro inesperado.'
n1, n2, n3 = -1, -1, -1
tipo_de_media = str
print('Média de um aluno:')
while n1 < 0 or n1 > 10:
n1 = float(input('Digite a nota 1: '))
while n2 < 0 or n2 > 10:
n2 = float(input('Digite a nota 2: '))
while n3 < 0 or n3 > 10:
n3 = float(input('Digite a nota 3: '))
print('Digite o tipo de Média:')
while tipo_de_media != 'A' and tipo_de_media != 'P':
tipo_de_media = input('Aritmética [A] ou Ponderada [P]: ')
tipo_de_media = tipo_de_media.upper()
print(f'Média = {calcula_media(n1, n2, n3, tipo_de_media):.2f}')
|
91559591ccce766559c896dde76cbbd368897f8a | kindlyhickory/Homework_1 | /lesson02/ex2_3.py | 1,573 | 3.890625 | 4 | while True:
try:
month = int(input('Введите номер месяца: '))
months_dict = {1: 'зима январь',
2: 'зима февраль',
3: 'весна март',
4: 'весна апрель',
5: 'весна май',
6: 'лето июнь',
7: 'лето июль',
8: 'лето август',
9: 'осень сентябрь',
10: 'осень октябрь',
11: 'осень ноябрь',
12: 'зима декабрь'
}
months_list = ['зима январь', 'зима февраль', 'весна март', 'весна апрель', 'весна май', 'лето июнь',
'лето июль',
'осень сентябрь',
'лето август', 'осень октябрь', 'осень ноябрь', 'зима декабрь']
print(f'Время года cо словаря: {months_dict[month]}')
print(f'Время года со списка: {months_list[month - 1]}')
break
except IndexError:
print('Такого времени года не существует')
except ValueError:
print('Это не число')
except KeyError:
print('Такого времени года не существует')
|
2dced53043e090a185945611e7b0f893e88e297d | max180643/PSIT-IT | /Week-16/BloodDonation.py | 527 | 3.796875 | 4 | """
BloodDonation
Author : Chanwit Settavongsin
"""
def main(age, weight, time, answer):
""" BloodDonation check """
if age == 17 or (age >= 60 and age <= 70):
cert = input()
if age >= 17 and age <= 70 and weight >= 45 and \
(time > 0 or (time == 0 and age <= 55)) and cert == "True":
answer = "Yes"
elif age >= 17 and age <= 70 and weight >= 45 and (time > 0 or (time == 0 and age <= 55)):
answer = "Yes"
return answer
print(main(int(input()), int(input()), int(input()), "No"))
|
25b2315e39eed9bb7c810a434b483371181f3cb8 | entrkjm/pythonAlgorithms | /2675.py | 216 | 3.53125 | 4 | num = int(input())
for i in range(num):
R, S = input().split()
R = int(R)
# split : distinguish input value by blank
S = str(S)
for j in range(len(S)):
print(R * S[j], end ='')
print() |
5d292459a0555526abb3c8f984dedc5245e3a056 | greenfrog82/DailyCoding | /Codewars/4kyu/4kyu_valid_braces/src/other_1.py | 457 | 4.15625 | 4 | def validBraces(string):
while '{}' in string or '()' in string or '[]' in string:
string = string.replace('{}', '')
string = string.replace('()', '')
string = string.replace('[]', '')
return '' == string
print validBraces('(){}[]') == True
print validBraces('([{}])') == True
print validBraces('(}') == False
print validBraces('[(])') == False
print validBraces('[({})](]') == False
print validBraces('[({})])]') == False
|
0f2f19336e93d61cc33161ec3307cdead1677ee5 | shawnq8861/Python-Examples | /PythonPractice.py | 1,392 | 3.71875 | 4 | """
Practice from Chapter 12, 13
"""
if 1:
print('hello')
x = 'spam'
while x:
print x,
x = x[:-1]
print '\n'
a = 0
b = 10
while a < b:
print a,
a += 1
def funct1():
pass
print '\n'
x = 10
while x:
x -= 1
if x % 2 != 0: continue
print x,
print '\n'
x = 10
while x:
x -= 1
if x % 2 == 0:
print x,
x = 0
while x < 100:
print x
x +=5
if x == 30:
break
y = 0
for x in [1, 2, 3, 4]:
y += x
print 'sum = ' + str(y)
for x in ['first', 'second', 'third']:
for y in [1, 2, 3, 4, 5]:
print x, ' ', y
for i in range(5):
print 'i = ', i
L = [1, 2, 3, 4, 5]
for i in range(len(L)):
L[i] += 1
print L
def AddNum(x = 1, y = 2):
return x + y
print '2 + 7 = ', AddNum(2, 7)
OtherName = AddNum
print 'calling by new name...'
print '5 + 11 = ', OtherName(5, 11)
print AddNum( 'char ', str(4))
def times(x, y):
return x * y
print '3 * 5 = ', times(3, 5)
print '\'a\' * 4 = ', times('a', 4)
def intersect(seq1, seq2):
res = [] # Start empty
for x in seq1: # Scan seq1
if x in seq2: # Common item?
res.append(x) # Add to end
return res
print intersect([1, 2, 3, 4], [2, 3, 5, 6, 7])
st1 = 'shawn'
st2 = 'spam'
print 'intersection of ', st1, ' and ', st2, ' is ', intersect(st1, st2)
|
e1ecd71413bbb91aa449fdff63a093eb91333e5b | menglingshu/Python_Exercises | /MyTimer.py | 1,448 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 21 16:46:01 2018
@author: Lingshu
"""
import time as t
class MyTimer():
def __init__(self):
self.unit = ['years', 'month', 'day', 'hour', 'min', 'second']
self.prompt = 'not yet begin timer'
self.lasted = []
self.begin = 0
self.end = 0
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self, other):
prompt = 'total running time is: '
result = []
for index in range(6):
result.append(self.lasted[index] + other.lasted[index])
if result[index]:
prompt += (str(result[index]) + self.unit[index])
return prompt
def start(self):
self.begin = t.localtime()
self.prompt = 'please stop time first'
print('time begin')
def stop(self):
if not self.begin:
print('please start timer please')
else:
self.end = t.localtime()
self._calc()
print('time stop')
def _calc(self):
self.lasted = []
self.prompt = "total running time is: "
for index in range(6):
self.lasted.append(self.end[index] - self.begin[index])
if self.lasted[index]:
self.prompt += (str(self.lasted[index]) + self.unit[index])
self.begin = 0
self.end = 0 |
cbe44fe160f83d90c07feceb4da38b4b0b4aeb70 | DFYT42/Python---Beginner | /Python_Turtle_Clock.py | 2,073 | 4.6875 | 5 | ##Create a clock image with Turtles
##Import Turtle module
import turtle
##Initialize Turtle Screen
wn = turtle.Screen()
##Set Background color
wn.bgcolor("Black")
##Set Window Title
wn.title("Python Turtle Clock")
##Initialize Turtle
alex = turtle.Turtle()
##Set Turtle color and shape
alex.color("orange")
alex.shape("turtle")
##Input
x = turtle.numinput("Clock Size","Enter a number for the clock size (10-425): ",50, minval=10, maxval=425)
"assign a variable to dialog box that initializes to the turtle screen for numeric inputs from the user"
"turtle.numinput(""dialog box name"",""direction for input"",default value,minval=x,maxval=x)"
"default value, minval, & maxval are all optional but consider the user might assume program does not work if the scope"
"occurs outside the screen or is so small it cannot be seen"
##Function
def clock(x):
"using a for loop, create a clock image, the size of (x), by moving the turtle"
"around the screen and drawing only in certain locations"
alex.left(90)
"initializes turtle to 12:00 position"
##For loop
for i in range(12):
"For every instance,(number 0-11 bc computers start counting at 0)"
"turtle does the following"
alex.pu() ##pick turtle pen up so turtle leaves no trace
alex.forward(x) ##move turtle x spaces
alex.pd() ##put turtle pen down to draw again
alex.forward(20) ##move turtle a set 20 spaces
alex.pu()
alex.forward(20) ##move turtle a set 20 spaces
alex.stamp() ##place a stamp of the turtle shape
alex.backward(x+40) ##move turtle back the total distance traveled, (x+20+20)
alex.right(30) ##turn turtle by 30 degrees to position for next loop, (360 degrees in circle/12 clock numbers)
##Call Function
clock(x)
"when program runs, this line tells computer to find the definition/function of clock and take those actions"
"using the parameters given by default--in this case x = 50--, or by the user"
##Close program loop
wn.mainloop()
|
f4d46512cd3aadbd47e782df5fc0e2b65714012e | andersonOlliver/criptography-aes | /util/params.py | 1,258 | 3.546875 | 4 | from typing import TextIO
from util.mode import Mode
class Param:
sizeKey: int
key: str = ''
file: TextIO
pathFile: str = ''
operationMode: Mode = Mode.UNDEFINED
def __init__(self, mode: Mode):
self.operationMode = mode
print("Já vamos começar! Mas primeiro precisamos de algumas informações: ")
while self.operationMode is Mode.UNDEFINED:
print("Por gentileza informe o tipo de operação:")
aux = input("'C' => Cripografar\n'D' => Decriptografar")
self.operationMode = Mode.ENCRYPT if aux is 'C' else Mode.DECRYPT if aux is 'D' else Mode.UNDEFINED
while self.pathFile == '':
try:
self.pathFile = input("Informe o caminho do arquivo a ser processado: ")
self.file = open(self.pathFile, 'r')
self.file.close()
except IOError:
print("Arquivo não encontrado!")
self.pathFile = ''
self.key = input("Infome a chave (8 ou 16 caracteres): ")
self.sizeKey = len(self.key)
while self.sizeKey != 8 and self.sizeKey != 16:
self.key = input("Infome a chave (8 ou 16 caracteres): ")
self.sizeKey = len(self.key)
|
cc6fbc7c2097a37440c18775d314e8e7dc15070b | danielsummer044/EDUCATION | /find_count.py | 308 | 3.5625 | 4 | arr = [21, 23, 31, 34, 11, 111, 17, 12, 7, 5]
a = 2
b = 4
def find_count(n):
count = 0
while n > 0:
digit = n % 10
n = n // 10
count = count + 1
return count
for i in range(len(arr)):
count = find_count(arr[i])
if count > a and count < b:
print((arr[i]))
|
886876c0027331761ab8290207d001d7c7b0806c | LXSkyhawk/cp2015 | /practical4/q5_count_letter.py | 424 | 4.03125 | 4 | def count_letter(str, ch):
str = str.lower()
ch = ch.lower()
if len(str) == 1:
if str[0] == ch:
return 1
else:
return 0
elif str[len(str) - 1] == ch:
return 1 + count_letter(str[:-1], ch)
else:
return count_letter(str[:-1], ch)
string = input("Enter string: ")
character = input("Enter wanted character: ")
print(count_letter(string, character))
|
398670cfbceb0d423b1f25297302d71ad628e843 | yuichiro-cloud/coder | /pai/1.py | 408 | 3.609375 | 4 | leet = list(input())
print(len(leet))
for i in range(len(leet)):
if leet[i] == 'A':
leet[i] = '4'
elif leet[i] == 'E':
leet[i] = '3'
elif leet[i] == 'G':
leet[i] = '6'
elif leet[i] == 'I':
leet[i] = '1'
elif leet[i] == 'O':
leet[i] = '0'
elif leet[i] == 'S':
leet[i] = '5'
elif leet[i] == 'Z':
print('z')
leet[i] = '2'
else:
continue
print(''.join(leet))
|
e5bccbb3c9be373eaf2bd9091b01e747a70d1749 | mvind/hangman | /hangman.py | 14,402 | 4.0625 | 4 | # Problem Set 2, hangman.py
# Name:
# Collaborators:
# Time spent:
# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = load_words()
def is_char_correct(secret_word, guess):
if guess in secret_word:
return True
else:
return False
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the letters of secret_word are in letters_guessed;
False otherwise
'''
mistake_found = False
word_check = ''.join(set(str(secret_word)))
#print(word_check)
for i in range(0,len(word_check)):
char = word_check[i]
#print('Checking: ' + char)
for j in letters_guessed:
if (str(char) == j):
#print 'match', char
break
else:
#print 'Not a match'
if j == letters_guessed[len(letters_guessed)-1]:
mistake_found = True
break
else:
continue
#mistake_found = True
if i == len(word_check)-1 and mistake_found == False:
#print('You have guessed the word correctly')
return True
elif mistake_found == True:
#print('You havent guessed the word correctly')
return False
else:
continue
# print is_word_guessed('apple',['a','e','l','p'])
# print ['a','e','l','p']
def get_guessed_word(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing
letters_guessed: list (of letters), which letters have been guessed so far
returns: string, comprised of letters, underscores (_), and spaces that represents
which letters in secret_word have been guessed so far.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
user_word = ''
for i in secret_word:
#print(i)
for j in letters_guessed:
if j == i:
user_word = user_word+j
#print('match', user_word)
break
else:
if j == letters_guessed[len(letters_guessed)-1]:
user_word = user_word+'_'
else:
continue
return user_word
#print(get_guessed_word('apple',['g','n','l','e']))
def get_available_letters(letters_guessed):
'''
letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
alphabet = list(string.ascii_lowercase)
for char in letters_guessed:
alphabet.remove(char)
return ''.join(alphabet)
#print(get_available_letters(['a','b','m']))
def hangman(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should start with 6 guesses
* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.
* Ask the user to supply one guess per round. Remember to make
sure that the user puts in a letter!
* The user should receive feedback immediately after each guess
about whether their guess appears in the computer's word.
* After each guess, you should display to the user the
partially guessed word so far.
Follows the other limitations detailed in the problem write-up.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
warnings_left = 3
guesses_left = 6
letters_guessed = []
print('Welcome to the game Hangman! \n')
print('I am thinking of a word that has ' + str(len(secret_word)), 'letters.')
print('You have ',warnings_left, 'warnings left')
while guesses_left > 0:
check = False
print('\n---------------')
print('You have ' + str(guesses_left) + ' guesses left')
print('Available letters: ' + str(get_available_letters(letters_guessed)))
#Get input and check if its correct format
while not check:
guess = input("Please guess a letter: ").lower()
if guess.isalpha() and guess not in letters_guessed: #Correct input from user
check = True
elif warnings_left>0:
print('Please make sure to enter only one letter you havent prevoisly entered')
warnings_left -= 1
print('Warnings left before you lose a guess: ', warnings_left)
if warnings_left == 0:
print('No warnings left, you\'ve lost a guess')
guesses_left -= 1
elif warnings_left == 0:
print('No warnings left, you\'ve lost a guess')
guesses_left -= 1
#Add guess to list
letters_guessed.append(guess)
if is_char_correct(secret_word, guess):
print('Correct!')
else:
print('Not correct!')
if guess in "bcdfghjklmnpqrstvwxyz":
guesses_left -= 1
elif guess in "aeiou":
guesses_left -= 2
print('Secret word so far: ', get_guessed_word(secret_word, letters_guessed))
#Check if user has guessed the secret word
if is_word_guessed(secret_word,letters_guessed):
print('You have correctly guessed the word!')
print('Score: ', (guesses_left*len(''.join(set(secret_word)))))
break
print('---------------')
if guesses_left <= 0:
print('You have run out of guesses, the secret word was', secret_word)
# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)
# -----------------------------------
def match_with_gaps(my_word, other_word):
'''
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special symbol
_ , and my_word and other_word are of the same length;
False otherwise:
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
if len(my_word) == len(other_word): #Only check words of same length
#Get unique characters from my word
unique_my_word = ''.join(set(my_word)).replace('_','')
unique_other_word = ''.join(set(other_word))
#Get position for the characters from my word
unique_pos = []
for char in unique_my_word:
unique_pos.append([[pos for pos, c in enumerate(my_word) if char == c],char])
#print(unique_pos, '\n')
guide_pos = []
for char in unique_other_word:
guide_pos.append([[pos for pos, c in enumerate(other_word) if char == c],char])
#print(guide_pos)
for i in range(len(unique_pos)):
pointer =unique_pos[i][1]
for j in range(len(guide_pos)):
if pointer == guide_pos[j][1]:
#print("Found you")
#Check position arrays match over
if unique_pos[i][0] == guide_pos[j][0]:
#print('Match')
continue
else:
#print('Not a match')
return False
else: #Means that the words dont match over i.e there some character different
if pointer in other_word:
continue
else:
return False
return True
else:
return False
#print(match_with_gaps('m_vt','move'))
#print(match_with_gaps('te_t','tact'))
#print(match_with_gaps('t__t','tact'))
def show_possible_matches(my_word):
'''
my_word: string with _ characters, current guess of secret word
returns: nothing, but should print out every word in wordlist that matches my_word
Keep in mind that in hangman when a letter is guessed, all the positions
at which that letter occurs in the secret word are revealed.
Therefore, the hidden letter(_ ) cannot be one of the letters in the word
that has already been revealed.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
length = len(my_word)
matches = []
for w in wordlist:
if len(w) != length:
continue
else:
if match_with_gaps(my_word, w) == True:
matches.append(w)
else:
continue
#print(matches)
return_string = ''
for i in matches:
return_string += ' '+i
print(return_string)
#show_possible_matches('a_pl_')
def hangman_with_hints(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should start with 6 guesses
* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.
* Ask the user to supply one guess per round. Make sure to check that the user guesses a letter
* The user should receive feedback immediately after each guess
about whether their guess appears in the computer's word.
* After each guess, you should display to the user the
partially guessed word so far.
* If the guess is the symbol *, print out all words in wordlist that
matches the current guessed word.
Follows the other limitations detailed in the problem write-up.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
warnings_left = 3
guesses_left = 6
letters_guessed = []
print('Welcome to the game Hangman! \n')
print('I am thinking of a word that has ' + str(len(secret_word)), 'letters.')
print('You have ',warnings_left, 'warnings left')
while guesses_left > 0:
check = False
print('\n---------------')
print('You have ' + str(guesses_left) + ' guesses left')
print('Available letters: ' + str(get_available_letters(letters_guessed)))
#Get input and check if its correct format
while not check:
guess = input("Please guess a letter: ").lower()
if guess == '*':
print('Possible matches are: ')
show_possible_matches(get_guessed_word(secret_word, letters_guessed))
print('---------------\n')
#break
elif guess.isalpha() and guess not in letters_guessed: #Correct input from user
check = True
elif warnings_left>0:
print('Please make sure to enter only one letter you havent prevoisly entered')
warnings_left -= 1
print('Warnings left before you lose a guess: ', warnings_left)
if warnings_left == 0:
print('No warnings left, you\'ve lost a guess')
guesses_left -= 1
elif warnings_left == 0:
print('No warnings left, you\'ve lost a guess')
guesses_left -= 1
#Add guess to list
letters_guessed.append(guess)
if is_char_correct(secret_word, guess):
print('Correct!')
else:
print('Not correct!')
if guess in "bcdfghjklmnpqrstvwxyz":
guesses_left -= 1
elif guess in "aeiou":
guesses_left -= 2
print('Secret word so far: ', get_guessed_word(secret_word, letters_guessed))
#Check if user has guessed the secret word
if is_word_guessed(secret_word,letters_guessed):
print('You have correctly guessed the word!')
print('Score: ', (guesses_left*len(''.join(set(secret_word)))))
break
print('---------------')
if guesses_left <= 0:
print('You have run out of guesses, the secret word was', secret_word)
# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.
if __name__ == "__main__":
# To test part 2, comment out the pass line above and
# uncomment the following two lines.
#secret_word = choose_word(wordlist)
#hangman(secret_word)
###############
# To test part 3 re-comment out the above lines and
# uncomment the following two lines.
secret_word = choose_word(wordlist)
hangman_with_hints(secret_word)
|
0e632642560677d7ea3ff28b58eef0026ac5c305 | vijaynitrr/python-code | /code/inheritance.py | 344 | 3.640625 | 4 | class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(object):
def __init__(self):
print "third"
class Fourth(First ,Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print "that's it"
a = Fourth() |
884a34a1878b9e4b93ccb0d98f03ceaf62c31ddf | bhagavansprasad/students | /rahul/python/strings.py | 4,139 | 3.5625 | 4 | test_str = "Aura Networks Bangalore"
print test_str
for byte in test_str:
print byte,
print ""
print len(test_str)
i = 0
while (i < len(test_str)):
print test_str[i],
i += 1
print ""
print test_str[0]
print test_str[1]
print test_str[-1]
print test_str[-2]
print test_str[1:6]
print test_str[1:23]
print test_str[1:30]
print test_str[::-1]
s1 = "Hello Aura Networks"
s2 = "Python Training"
print "string1 :", s1
print "string2 :", s2
print s1[0]
print s1[-1]
print s1[-2]
print s1[6:10]
print s1[11:30]+"11234"
exit(1)
test = "abcd"
print test[4:6]
name = "Saketh Ram"
age = 13
salary = 1000
height = 5.123
#print "name ", name, "age ", age,
print "my friend %s age is %d and salary is %d height is %f" % (name, age, salary, height)
print name, age
print name * 3
#name[0] = 'x'
s = "Aurovill"
#s[0] = 'B' #error #immutable
s = "B" + s[:]
print s
s = "B" + s[2:]
print s
s = "B" + s[2:5]
print s
s = "B" + s[1:5]
print s
str = "this is string example. and temp...wow!!!";
print "str.capitalize() : ", str.capitalize()
print str
str = str.capitalize()
print str
print ""
print dir(s)
print str
sub = "i";
print "str.len() :", len(str)
print "str.count(sub) : ", str.count(sub)
print "str.count(sub, 4) : ", str.count(sub, 4)
print "str.count(sub, 4, 10) : ", str.count(sub, 4, 10)
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
sub = " ";
print "str.count(sub) : ", str.count(sub)
print ""
print str
i = 0
str = "this is string example....wow!!!";
print str
suffix = "wow!!!";
prefix = "This";
print "1. ", str.endswith(suffix)
print "2. ", str.endswith(suffix, 5, 7)
print "3. ", str.startswith(prefix)
print "4. ", str.capitalize().startswith(prefix)
print ""
str = "this is string example....wow!!!";
str2 = "exam";
print "1. ", str.find(str2)
print "2. ", str.find(str2, 10)
print "3. ", str.find(str2, 20)
print "4. ", str.index(str2, 10)
print ""
str = "THIS is string example....wow!!!";
print str.islower()
print str.lower().islower()
print str.lower()
str = "this is string example....wow!!!";
print str.islower()
print str.upper()
print str.upper().capitalize()
print str.upper().capitalize().islower()
print str.upper().isupper()
print ""
str = " ";
print str.isspace()
str = "This is string example....wow!!!";
print str.isspace()
str = "This is string is example...is .wow!!!";
print ""
print str
print str.replace("is", "was")
print str
str = "This is string is example...is .wow!!!";
print str
print str.replace("is", "was", 1) #Number of occurences to replace
print ""
str = " this is string example....wow!!! ";
print str,
print "xxxx"
print str.rstrip(),
print "xxxx"
print str.strip(),
str = "88888888this is string example....wow!!!8888888888888888888888";
print str
print str.rstrip('8')
print (str.rstrip('8')).lstrip('8')
print (str.rstrip('8')).lstrip('8').lstrip("th")
str = "88888888this is string example....wow!!!8888888888abc888888888888";
#output should be str = "this is string example....wow!!!abc";
print str
substr = "abc"
print str.lstrip('8').rstrip('8').rstrip(substr).rstrip('8')+substr
print type(str.lstrip('8').rstrip('8').rstrip(substr).rstrip('8')+substr)
print ""
str = "Line1-ab cdef \nLine2-abc\nLine4-abcd";
print str
print str.split()
print type(str.split())
print str.split(' ', 1 )
print str.split(' ', 2 )
email = "bhagavansprasad@gmail.com"
print email.split('@')
username = email.split('@')[0]
dname = email.split('@')[1]
print username
print dname
username,dname = email.split('@')
print username
print dname
exit(1)
print ""
str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines()
print str.splitlines(0)
print str.splitlines(1)
print str.splitlines(4)
print str.splitlines(5)
str = "Line1-ab cdef Line2-abc Line4-abcd";
print str
print str.split(' ')
print str.split()
print len(str.split(' '))
exit(1);
|
bbb2a3c28d4cb5043f8e65bab209d7e822843719 | AbhijeetKrishnan/codebook | /CodeChef/APRIL17/SIMDISH.py | 525 | 3.59375 | 4 | t = int(input())
for test in range(t):
dish1 = input().split()
dish1.sort()
dish2 = input().split()
dish2.sort()
similar_ingredient_count = 0
i, j = 0, 0
while i != len(dish1) and j != len(dish2):
if dish1[i] == dish2[j]:
similar_ingredient_count += 1
i += 1
j += 1
elif dish1[i] < dish2[j]:
i += 1
else:
j += 1
if similar_ingredient_count >= 2:
print('similar')
else:
print('dissimilar') |
87c7109d2527931cf1afc84802e7189b00aee531 | roykroth/Project_Euler | /problem14.py | 383 | 3.859375 | 4 | import numpy as np
def collatz(n):
yield n
while n != 1:
if n % 2 == 0:
n = n/2
else:
n = 3*n + 1
yield n
def coll_len(n):
return len([i for i in collatz(n)])
longest = 0
longest_num = 3
for i in xrange(3, int(1e6)):
l = coll_len(i)
if l > longest:
longest = l
longest_num = i
print longest_num |
83944d37a537eb098f45826c5ec82c320cea7383 | JamieCass/pynotes | /regex.py | 10,042 | 3.59375 | 4 | #######################################################################
# Regular Expressions (REGEX)
#######################################################################
##########################################
# What are Regular Expression
##########################################
# - A way of desscribing patterns within search strings
https://docs.python.org/3/library/re.html #(link to regex documentation)
##########################################
# EMAILS
##########################################
# - Starts with 1 or more letter, number, +, _, -,.
# - A single @ sign then
# - 1 or more letter, number, or - then
#- A single dot then
# - Ends with 1 or more letter, number, -, or .
# Regular expression would look like this..
#(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)
##########################################
# Potential use cases
##########################################
# - Credit card number validating
# - Phone number validating
# - Advanced find/replace in text
# - Formatting text/output
# - Syntax highlighting
##########################################
# Some regex syntax (LOOK AT A CHEAT SHEET FOR MORE)
##########################################
http://www.rexegg.com/regex-quickstart.html (cheatsheet)
https://pythex.org/ (online tester)
#----- some characters -----
# '\d' digit 0-9
# '\w' letter, digit or underscore
# '\s' whitespace character
# '\D' not a digit
# '\W' not a word character
# '\S' not a whitespace character
# '.' any character except line break
#----- quantifers -----
# '+' one or more
# '{3}' exactly x times. {3} - 3 times
# '{3,5}' three to five times
# '{4,}' four or more times
# '*' zero or more times
# '?' once or none (optional)
#----- anchors and boundaries -----
# '^' start of string or line (the '^' also means not.. [^@$] would match anything thats neither @ nor $ sign)
# '$' end of string or line
# '\b' word boundary (space, start or end of a line)
# Using the ^ and $.. This is only good to check if the string or line is ONLY whatever is in the between them.
# '|' LOGICAL OR
##########################################
# REGEX with Python
##########################################
# import regex module
import re
# the r stands for raw string, if it wasnt at the beginning, you would have to do 2 '\' for python to recognise it as a backslash
# define our phone number regex
phone_regex = re.compile(r'\d{3} \d{3}-\d{4}')
email = re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+')
# search a string with out regex
res = phone_regex.search('Call me at 415 555-4242!')
res.group()
email.search('Email me at jamies_email@gmail.com')
##########################################
# Validating phone numbers with python
##########################################
# get 1 phone number at a time from a string
def extract_phone(input):
phone_regex = re.compile(r'\b\d{3} \d{3}-\d{4}\b')
match = phone_regex.search(input)
if match:
return match.group()
return None
extract_phone('my numbers is 878 009-3847')
print(extract_phone('my numbers is 746 837-938373827'))
# get multiple phone numbers in a string
def extract_all_phones(input):
phone_regex = re.compile(r'\b\d{3} \d{3}-\d{4}\b')
return phone_regex.findall(input)
extract_all_phones('my number is: 934 938-9927 or 836 837-3827')
# return True if the sstring is only a phone number and nothing else
def is_valid_phone(input):
phone_regex = re.compile(r'^\d{3} \d{3}-\d{4}$')
match = phone_regex.search(input)
if match:
return True
return False
def is_valid_phone(input):
phone_regex = re.compile(r'\d{3} \d{3}-\d{4}')
match = phone_regex.fullmatch(input) # we can use full match instead of search with the '^' and '$' at the start and end of the string.
if match:
return True
return False
##########################################
# Parsing URLs with python
##########################################
url_regex = re.compile(r'(https?)://(www\.[A-za-z-]{2,256}\.[a-z]{2,6})([-a-zA-Z0-9@:%_\+.~#?&//=]*)') # we put the '*' at the end because its optional 1 or more.
match = url_regex.search("https://www.my-website.com/bio?data=blah&dog=yes")
# we have put perens arpung each group so we can get the info for each group
print(f"Protocol: {match.group(1)}")
print(f"Domain: {match.group(2)}")
print(f"Everything Else: {match.group(3)}")
print(match.groups())
print(match.group())
##########################################
# Symbolic group names
##########################################
def parse_name(input):
name_regex = re.compile(r'^(Mr\.*|Mrs\.*|Ms\.*|Mdme\.*) (?P<first>[A-Za-z]+) (?P<last>[A-Za-z]+)$')
matches = name_regex.search(input)
print(matches.group())
print(matches.group('first')) # labeled by using the '?P<first>' in our name_regex
print(matches.group('last'))
parse_name("Mrs. Tilda Swinton")
parse_name('Mr Jamie Losks')
##########################################
# Regex compilation flags
##########################################
# Verbose flag can be 're.VERBOSE' or re.X
# Ignorecase flag can be 're.IGNORECASE' or 're.I'
# Without Verbose Flag...
# pat = re.compile(r'^([a-z0-9_\.-]+)@([0-9a-z\.-]+)\.([a-z\.]{2,6})$')
import re
pattern = re.compile(r"""
^([a-z0-9_\.-]+) #first part of email
@ #single @ sign
([0-9a-z\.-]+) #email provider
\. #single period
([a-z\.]{2,6})$ #com, org, net, etc.
""", re.X | re.I) # if you want to use both flag you need to use the '|' and that will use both flags!!
match = pattern.search("ThomaS123@Yahoo.com")
print(match.group())
print(match.groups())
##########################################
# Regex substitution basics (.sub)
##########################################
# We can use sub to change regex matches in a string
# you need to use the ('pattern of the REGEX'.sub('what we replace matches with', from the input))
# \g<number of group> keeps the group we want and then we can change anyting else that matches the regex
text = 'Last night Mrs. Daisy and Mr. White mudered Mr. Chow'
pattern = re.compile(r'(Mr.|Mrs.|Ms.) ([a-z])[a-z]+', re.I) #this will search for all names with IGNORECASE
result = pattern.sub('*****', text) # we change the names to '*****'
result_2 = pattern.sub('\g<1> ***** ', text) # we use the '\g<1>' to keep the first group the same then we put whatever we are changing after..
result_3 = pattern.sub('\g<1> \g<2>', text) # we put the first letter of the name into a seperate group, so now, we can just have the title and first letter shown instead of the whole name.
result # '*****' replaces the title and name
result_2 # '*****' replaces the name but not the title
result_3 # shows just the title and first letter of the name.
##########################################
# Swapping file names
##########################################
import re
titles = [
"Significant Others (1987)",
"Tales of the City (1978)",
"The Days of Anna Madrigal (2014)",
"Mary Ann in Autumn (2010)",
"Further Tales of the City (1982)",
"Babycakes (1984)",
"More Tales of the City (1980)",
"Sure of You (1989)",
"Michael Tolliver Lives (2007)"
]
titles.sort()
fixed_titles = []
pattern = re.compile(r'(?P<title>^[\w ]+) \((?P<date>\d{4})\)')
for book in titles:
# result = pattern.sub("\g<2> - \g<1>", book)
result = pattern.sub("\g<date> - \g<title>", book) # We swap the title and date around.
fixed_titles.append(result)
fixed_titles.sort()
fixed_titles
########################################## NEW TASK ##########################################
# function that accepts a single string and return True if the string is formatted as time
def is_valid_time(time):
time_test = re.compile(r'^\d{1,2}:\d{2}$')
if time_test.search(time):
return True
return False
is_valid_time('1:52')
is_valid_time('134:56')
########################################## NEW TASK ##########################################
# function that accepts a string and returns a list if the binary bytes conained in the string.
# each string is just a combination of eight 1's or 0's
def parse_bytes(input):
bytes_regex = re.compile(r'\b[01]{8}\b') # remember a word boundary is a space or the start/end of a line.
match = bytes_regex.findall(input)
return match
parse_bytes('my data is: 10010110 10010101')
parse_bytes('10010010 873 10010')
########################################## NEW TASK ##########################################
# function that checks to see if a string matches a date format of 'dd/mm/yyyy'
# it should also work with 'dd.mm.yyy' or 'dd,mm,yyyy' and should return a dictionary of the d, m and y
def parse_date(input):
date_regex = re.compile(r'^(?P<day>\d{2})[/.,](?P<month>\d{2})[/.,](?P<year>\d{4})$')
match = date_regex.search(input)
if match:
return {
'd': match.group('day'),
'm': match.group('month'),
'y': match.group('year')
}
return None
parse_date('20,08,1919')
parse_date('20.08.199919')
########################################## NEW TASK ##########################################
# function that will replace any profanity with the word 'CENSORED'
# this includes 'fracking', 'fracker', 'frack' etc..
def censor(input):
censor_regex = re.compile(r'(frack[a-z]*)', re.I)
result = censor_regex.sub('CENSORED', input)
return result
# Couold of done it like this..
# def censor(input):
# pattern = re.compile(r'\bfrack\w*\b', re.IGNORECASE)
# return pattern.sub("CENSORED", input)
censor('youre a fracking idiot')
def my_searcher(input):
pho_regex = re.compile(r'\b\d{10}\b')
em_regex = re.compile(r'\b[a-z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-z0-9-.]+\b', re.I)
match1 = pho_regex.findall(input)
match2 = em_regex.findall(input)
return {
'Phone numbers' : match1,
'Emails:' : match2
}
my_searcher('hello, my name is jamie, my phone number is 0473263546 and my email is jamie@gmail.com. If you need to contact me outside of hours call 0485578847 or email my personal account on jamie2@gmail.com')
|
532ccfeeeb90f0253f797033fe95b1fd3f1634c4 | jkpubsrc/python-module-jk-console | /examples/colorizedoutput.py | 282 | 3.5 | 4 | #!/usr/bin/env python3
#
# This example demonstrates how to write colored text to STDOUT.
#
from jk_console import Console
print(Console.ForeGround.CYAN + "Hello World!" + Console.RESET)
print(Console.BackGround.rgb256(128, 0, 0) + "Hello World!" + Console.RESET)
|
54dd16013ae3d8305ee28a192a8d133e83650182 | AlyxMoon/Project-Euler-Solutions | /Python34/Problem24.py | 771 | 3.546875 | 4 | def get_nth_lexic_permutation(digits, goal):
count = 1
while(count < goal):
end = len(digits)
i = end - 1
while(digits[i - 1] >= digits[i]): i -= 1
j = end
while(digits[j - 1] <= digits[i - 1]): j -= 1
digits[i - 1], digits[j - 1] = digits[j - 1], digits[i - 1]
i += 1
j = end
while(i < j):
digits[i - 1], digits[j - 1] = digits[j - 1], digits[i - 1]
i += 1
j -= 1
count += 1
return int(''.join([ "%d" % x for x in digits]))
print(get_nth_lexic_permutation([0,1,2,3,4,5,6,7,8,9], 1000000))
# Finding the pattern...
# 0123456789 beginning
# 0123456798 SWAP last two
# 0123456879 SWAP last with third, SWAP last two
# 0123456897 SWAP last two
# 0123457689 SWAP last with fourth, SWAP last two, SWAP second to last two |
a2cf45e96c7cdffb441a5dc68530b5b32397afe6 | Kourtz/coding_bootcamp | /Common_courses/Python/day_2/ex_05.py | 511 | 3.59375 | 4 | import math
y= int(input('Enter year between 1900-2099:'))
if y>2099 or y<1900:
print("Error")
a=y%4
b=y%7
c=y%19
d=(19*c+15)%30
e=(2*a+4*b-d+34)%7
month=math.floor((d+e+114)/31)
day=(d+e+114)%31+1
day2=day+13
if month==3 or month==5:
if day2>31:
day2=day2-31
month=month+1
else:
day2=day2
month=month
else:
if day2>30:
day2=day2-30
month=month+1
else:
day2=day2
month=month
print ("Day:",day2,"Month:",month,end="")
|
353cda36345449e9403d4d1ebf4ad3ed8e8a2874 | ykumards/project-euler | /python_sols/problem17.py | 2,304 | 3.90625 | 4 | import math
"""
Problem 17
Learn to spell out all the numbers properly before attempting this!
There's scope for memoization, but the speed issue only arises when scaled
much higher
"""
def getDigit(n):
if n == 1:
return "one"
elif n == 2:
return "two"
elif n == 3:
return "three"
elif n == 4:
return "four"
elif n == 5:
return "five"
elif n == 6:
return "six"
elif n == 7:
return "seven"
elif n == 8:
return "eight"
elif n == 9:
return "nine"
elif n == 10:
return "ten"
else:
return ""
def getTeens(n):
if n == 11:
return "eleven"
elif n == 12:
return "twelve"
elif n == 13:
return "thirteen"
elif n == 14:
return "fourteen"
elif n == 15:
return "fifteen"
elif n == 16:
return "sixteen"
elif n == 17:
return "seventeen"
elif n == 18:
return "eighteen"
elif n == 19:
return "nineteen"
def getMid(n):
if n >= 20 and n < 30:
return "twenty " + getDigit(n % 20)
elif n >= 30 and n < 40:
return "thirty " + getDigit(n % 30)
elif n >= 40 and n < 50:
return "forty " + getDigit(n % 40)
elif n >= 50 and n < 60:
return "fifty " + getDigit(n % 50)
elif n >= 60 and n < 70:
return "sixty " + getDigit(n % 60)
elif n >= 70 and n < 80:
return "seventy " + getDigit(n % 70)
elif n >= 80 and n < 90:
return "eighty " + getDigit(n % 80)
else:
return "ninety " + getDigit(n % 90)
def getHundreds(n):
if n == 1000: return "one thousand"
# We only care about 3 digit numbers
hun = "hundred"
hundreds = int(str(n)[0])
others = int(str(n)[1:])
if others == 0:
return getDigit(hundreds) + " " + hun
else:
return getDigit(hundreds) +" "+ hun + " and " + wordify(others)
def wordify(n):
if n <= 10:
return getDigit(n)
elif n <= 19:
return getTeens(n)
elif n < 100:
return getMid(n)
else:
return getHundreds(n)
def main():
sum = 0
for i in xrange(1, 1001):
print wordify(i)
sum += len(wordify(i).replace(' ',''))
print sum
if __name__ == "__main__":
main()
|
c12e5db1a086f41fb81baf81b73b23bc54823090 | dario-castano/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 263 | 3.765625 | 4 | #!/usr/bin/python3
class MyList(list):
"""Class who inherits from list"""
def __init__(self):
"""Initializer"""
super().__init__()
def print_sorted(self):
"""Returns the list but sorted"""
print(sorted(self.copy()))
|
e9c8a825e6d5020826676e1696ab3b530047b3a8 | roque-brito/ICC-USP-Coursera | /icc_pt2/week3/poo/exemplos_basico.py | 711 | 3.859375 | 4 | class Carro:
pass # classe vazia
# cria uma instância "meu_carro":
meu_carro = Carro()
print(meu_carro) # nome da instancia __main__, junto com o endereço na memória
# podes criar outra instância:
carro_ime = Carro()
print(carro_ime) # observar o endereço diferente na memoria
# criar atributos ao objeto (instanciado):
meu_carro.ano = 2019
meu_carro.modelo = 'Prisma'
meu_carro.cor = 'Branco'
print(meu_carro.ano, meu_carro.modelo, meu_carro.cor)
carro_ime.ano = 1999
carro_ime.modelo = 'Saveiro'
carro_ime.cor = 'Verde'
print(carro_ime.ano, carro_ime.modelo, carro_ime.cor)
# manipulação de atributos e objetos instanciados:
novo_carro = meu_carro
novo_carro.ano += 2
print(meu_carro.ano)
|
b57753327799a69efcb0d3fa09b6182059231406 | yin-hong/cs231n-assignment | /cs231n-assignment1/linear_svm.py | 3,551 | 3.578125 | 4 | import numpy as np
def svm_loss_naive(W,X,y,reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
note delta = 1
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
num_train=X.shape[0]
num_class=W.shape[1]
dw=np.zeros(W.shape)
loss=0.0
score = np.dot(X, W)
for i in range(num_train):
dw_tmp=0
for j in range(num_class):
if j==y[i]:
continue
else:
margin=score[i,j]-score[i,y[i]]+1
if margin>0:
dw[:,j]=dw[:,j]+np.transpose(X[i])
loss=loss+margin
dw[:,y[i]]+=-X[i].T
dw=dw/num_train
loss=loss/num_train+0.5*reg*np.sum(W*W)
dw=dw+reg*W
return loss,dw
def svm_loss_vectorized(W,X,y,reg):
"""
Structured SVM loss function, vectorized implementation.
Inputs and outputs are the same as svm_loss_naive.
"""
loss=0.0
dw=np.zeros(W.shape)
#############################################################################
# TODO: #
# Implement a vectorized version of the structured SVM loss, storing the #
# result in loss. #
#############################################################################
num_train=X.shape[0]
num_class=W.shape[1]
score=np.dot(X,W)
All_True_Label_Score=score[range(num_train),y.tolist()].reshape(-1,1)
L_tmp=score-All_True_Label_Score+1
L_tmp[range(num_train),y.tolist()]=-1
L_tmp_Large_than_zero=L_tmp>0
L_tmp=L_tmp*L_tmp_Large_than_zero
loss=np.sum(L_tmp)/num_train+0.5*reg*np.sum(W*W)
#############################################################################
# END OF YOUR CODE #
#############################################################################
#############################################################################
# TODO: #
# Implement a vectorized version of the gradient for the structured SVM #
# loss, storing the result in dW. #
# #
# Hint: Instead of computing the gradient from scratch, it may be easier #
# to reuse some of the intermediate values that you used to compute the #
# loss. #
#############################################################################
coff_mat=np.zeros((num_train,num_class))
coff_mat[L_tmp>0]=1
coff_mat[range(num_train),y.tolist()]=0
sum_row=np.sum(coff_mat,axis=1)
#sum_row=np.sum(L_tmp_Large_than_zero,axis=1)
coff_mat[range(num_train),y.tolist()]=-sum_row
dw=np.dot(X.T,coff_mat)
dw=dw/num_train+reg*W
return loss,dw
|
e89e76ed33aa5c259424459f7a77cc9f4a6df78d | kurumeti/Market-Basket-Analysis | /edm/apriori.py | 4,420 | 3.90625 | 4 | """
Description:
An Effectively Python Implementation of Apriori Algorithm for Finding Frequent
Sets and Association Rules
"""
from collections import defaultdict
import csv
class Apriori(object):
def __init__(self, minSupp, minConf):
""" Parameters setting
"""
self.minSupp = minSupp # min support (used for mining frequent sets)
self.minConf = minConf # min confidence (used for mining association rules)
def fit(self, filePath):
""" Run the apriori algorithm, return the frequent *-term sets.
"""
# Initialize some variables to hold the tmp result
transListSet = self.getTransListSet(filePath) # get transactions (list that contain sets)
itemSet = self.getOneItemSet(transListSet) # get 1-item set
itemCountDict = defaultdict(int) # key=candiate k-item(k=1/2/...), value=count
freqSet = dict() # a dict store all frequent *-items set
self.transLength = len(transListSet)
# number of transactions
self.itemSet = itemSet
# Get the frequent 1-term set
freqOneTermSet = self.getItemsWithMinSupp(transListSet, itemSet,
itemCountDict, self.minSupp)
# Main loop
k = 1
currFreqTermSet = freqOneTermSet
while currFreqTermSet != set():
freqSet[k] = currFreqTermSet # save the result
k += 1
currCandiItemSet = self.getJoinedItemSet(currFreqTermSet, k) # get new candiate k-terms set
currFreqTermSet = self.getItemsWithMinSupp(transListSet, currCandiItemSet,
itemCountDict, self.minSupp) # frequent k-terms set
#
self.itemCountDict = itemCountDict
self.freqSet = freqSet # Only frequent items(a dict: freqSet[1] indicate frequent 1-term set )
return itemCountDict, freqSet
def getSpecRules(self, rhs):
""" Specify a right item, construct rules for it
"""
if rhs not in self.itemSet:
print('Please input a term contain in the term-set !')
return None
rules = dict()
for key, value in self.freqSet.items():
for item in value:
if rhs.issubset(item) and len(item) > 1:
item_supp = self.getSupport(item)
item = item.difference(rhs)
conf = item_supp / self.getSupport(item)
if conf >= self.minConf:
rules[item] = conf
return rules
def getSupport(self, item):
""" Get the support of item """
return self.itemCountDict[item] / self.transLength
def getJoinedItemSet(self, termSet, k):
""" Generate new k-terms candiate itemset"""
return set([term1.union(term2) for term1 in termSet for term2 in termSet
if len(term1.union(term2))==k])
def getOneItemSet(self, transListSet):
""" Get unique 1-item set in `set` format
"""
itemSet = set()
for line in transListSet:
for item in line:
itemSet.add(frozenset([item]))
return itemSet
def getTransListSet(self, filePath):
""" Get transactions in list format
"""
transListSet = []
with open(filePath, 'r') as file:
reader = csv.reader(file, delimiter=',')
for line in reader:
transListSet.append(set(line))
return transListSet
def getItemsWithMinSupp(self, transListSet, itemSet, freqSet, minSupp):
""" Get frequent item set using min support
"""
itemSet_ = set()
localSet_ = defaultdict(int)
for item in itemSet:
freqSet[item] += sum([1 for trans in transListSet if item.issubset(trans)])
localSet_[item] += sum([1 for trans in transListSet if item.issubset(trans)])
# Only conserve frequent item-set
n = len(transListSet)
for item, cnt in localSet_.items():
itemSet_.add(item) if float(cnt)/n >= minSupp else None
return itemSet_
|
bf96519dbebb33053341b02de2e6932938d50797 | daily-boj/dryrain39 | /P14405.py | 400 | 3.75 | 4 | if __name__ == '__main__':
pikachu_str = input()
while "pi" in pikachu_str or "ka" in pikachu_str or "chu" in pikachu_str:
pikachu_str = pikachu_str.replace("pi", "_OK_")
pikachu_str = pikachu_str.replace("ka", "_OK_")
pikachu_str = pikachu_str.replace("chu", "_OK_")
pikachu_str = pikachu_str.replace("_OK_", "")
print("YES" if pikachu_str == "" else "NO")
|
0bfa7e8c611b970cde47dd23e522a087dc3535ad | GermanVelasco06/GermanAndresVelascoBossa | /tareas/tarea de polinomio.py | 843 | 3.890625 | 4 | respuesta = "si"
print ( " Digite el grado de su polinomio ")
gradoDelPolinomio =int ( input())
coeficientes = [0 for i in range (gradoDelPolinomio+1)]
exponentes = [0 for i in range (gradoDelPolinomio+1)]
i = 0
contador = 0
def resolverPolinomio (grado,coeficientes,x,contador):
resultado = 0
resultado = int(coeficientes[grado])
i = grado
while i>0 :
resultado = resultado *x + int(coeficientes[i-1])
contador +=1
i-=1
print ("multiplicaciones: ", contador)
return resultado
for i in range (0,gradoDelPolinomio +1):
print (" escriba el coeficiente para el termino de x elevado a ", i)
coeficientes [i] = input()
print ( " Digite el valor de x ")
x = int(input())
print("El resultado es: " , resolverPolinomio(gradoDelPolinomio,coeficientes,x,contador))
|
69679fef28a1534518ab9c49fcc3c0cefdb4a953 | Lucas-Severo/python-exercicios | /mundo01/ex028.py | 801 | 4.46875 | 4 | '''
Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5
e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.
'''
from cores import Cores # necessário o arquivo cores.py
from random import randint
import time
cor = Cores()
print('-*'*27)
print('Vou pensar em um número entre 0 e 5. Tente adivinhar...')
print('-*'*27)
num = int(input('Em que número eu pensei? '))
numEscolhido = randint(0, 5)
print('PROCESSANDO...')
time.sleep(1)
if num == numEscolhido:
print(f'{cor.font("verde")}PARABÉNS! Você conseguiu me vencer!{cor.limpar()}')
else:
print(f'{cor.font("vermelho")}Ganhei! Eu pensei no número {numEscolhido} e não no {num}!{cor.limpar()}')
|
3636adac4c35d790019a66b4873bc47e546a22fb | maruV/_Learning | /Python/Programs/labQuiz/untitled1.py | 1,072 | 3.625 | 4 | # Vishal Maru
# Lab Quiz
def getList(filename):
open_file = open(filename, 'r')
strList = open_file.readlines()
global S_list
S_list = []
for str in strList:
# if str[-1] == '\n' or str[-1] == " ":
# str = str[:-1]
S_list.append(str.rstrip())
def LongestStr(S_list):
Lstring = len(max(S_list, key=len))
print("Index of the longest line:")
L_index = 0
for (index, string) in enumerate(S_list):
if len(string) == Lstring:
L_index = index
print(L_index)
def ifOne(S_list):
print("Lines with '1' digits:")
for str in S_list:
if '1' in str:
print(str)
def ifSpaces(S_list):
print("Indices of strings with 4 or more consecutive spaces:")
for (i, str) in enumerate(S_list):
if " " in str:
print(i)
def main():
filename = input("Which file?")
getList(filename)
print(LongestStr(S_list))
ifOne(S_list)
ifSpaces(S_list)
print("Done")
main() |
9b439ef2bac54b49d96adf824987344c740f7398 | Himanshu-Mishr/projecteuler | /projecteuler/problem51.py | 655 | 3.5 | 4 | #!/usr/bin/python3
# coder : Himanshu Mishra
# about : problem 51
# algorithm used : not decided till now
# links : http://projecteuler.net/problem=51
import time
def primechecker(num):
"""
primechecker() :checks prime or not
"""
x= num//2
while x>1:
if num%x == 0:break
x -= 1
else:return True
return False
def main():
start = time.time()
b = [str(i) + str(j) for i in range(1000,9999) for j in [1,3,7,9] if primechecker(int(str(i) + str(j)))]
print(b)
print("time taken :",time.time() - start)
# this is the standard biolerplate that calls the main() function.
if __name__ == '__main__':
main()
|
6c0c5acddf20b88e5c90917bc35931601b1892d9 | tanghl1994/MCGS | /final_data_produce_tree_2.py | 381 | 3.953125 | 4 | import random
print(13)
for i in range(2):
print(i+1,end=',')
print(3)
for i in range(3):
for j in range(2):
print((i+1)*3+j+1,end=',')
print((i+2)*3)
for i in range(9):
print()
for i in range(3):
print('min')
for i in range(9):
a = random.random()
while (a==0):
a = random.random()
print(a)
for i in range(9):
print(1)
|
3e7f2bc82a91a1fffb39af895c11d63f857babc1 | NAIST-SD-PBL-PAL/Teddy-plus | /python-idioms/npi-enumerate.py | 1,013 | 3.796875 | 4 | ## Non-idiomatic enumerate
# No.1
def n7():
for i in range(len(l)):
x = l[i]
try:
x = next(i for i, n in enumerate(l) if n > 0)
except StopIteration:
print('No positive numbers')
else:
print('The index of the first positive number is', x)
# No.2
def n8():
x = next(n for n in l if n > 0)
except StopIteration:
print('No positive numbers')
else:
print('The first positive number is', x)
# No.3
def n9():
ls = list(range(10))
index = 0
while index < len(ls):
print(ls[index], index)
index += 1
# No.4
def n10():
# Add three to all list members.
a = [3, 4, 5]
b = a #a and b refer to the same list object
for i in range(len(a)):
a[i] += 3 #b[i] also changes
# No.5
def n11():
for i in range(len(array)):
#do stuff with i
#do stuff with array[i]
# No.6
def n12():
index = 0
for element in my_container:
print (index, element)
index+=1
|
558434c757130a0db5d5065c78e49a58fd63210b | soonler/Python000-class01 | /Week_02/G20200343030035/week02_G20200343030035_ex01.py | 1,261 | 3.984375 | 4 |
# 客人 (原总价、商品数)
class Cus_Pay(object):
def __init__(self, original_pay, quantity):
self._original_pay = original_pay
self._quantity = quantity
def pay(self):
return self._original_pay
class Normal_Cus_Pay(Cus_Pay):
def __init__(self, original_pay, quantity):
super().__init__(original_pay, quantity)
def pay(self):
if self._original_pay < 200:
return self._original_pay
else:
return self._original_pay * 0.9
class Vip_Cus_pay(Cus_Pay):
def __init__(self, original_pay, quantity):
super().__init__(original_pay, quantity)
def pay(self):
if self._original_pay >= 200:
return self._original_pay * 0.8
elif self._quantity >= 10:
return self._original_pay * 0.85
if __name__ == '__main__':
true_cus1 = {'vip':True, 'original_pay':1000, 'quantity':13}
if true_cus1['vip'] == True:
print(f'Dear vip, your payment will be: {Vip_Cus_pay(true_cus1["original_pay"], true_cus1["quantity"]).pay()}')
else:
print(f'Dear customer, your payment will be: {Normal_Cus_pay(true_cus1["original_pay"], true_cus1["quantity"]).pay()}')
|
bc58b39c091e1bd92c16809703b1c158ce6fadc4 | yaolizheng/leetcode | /46/permutations.py | 371 | 4.09375 | 4 | def helper(l, temp, result):
if len(temp) == len(l):
result.append(temp)
else:
for x in l:
if x not in temp:
helper(l, temp + [x], result)
def permutations(l):
temp = list()
result = list()
helper(l, temp, result)
return result
if __name__ == '__main__':
l = [1, 2, 3]
print permutations(l)
|
c4a57db2bb6a5b0c14aac0712a28496908e11ca8 | chrisschnabel/adventofcode2020 | /day13/shuttle.py | 1,457 | 3.75 | 4 | import time
import numpy as np
def get_wait(time, nums):
"Input a time and a list of busses, return array wait times"
out = []
for num in nums:
if num < time:
w = num - time % num
if num == w:
w = 0
elif num == time:
w = 0
if num > time:
w = num - time
out.append(w)
return np.array(out)
def main():
timeStart = time.perf_counter_ns()
# Get info from file
f = open("input.txt")
now = int(f.readline().strip())
busses = []
target = []
w = 0
for b in f.readline().strip().split(","):
if not b == "x":
busses.append(int(b))
target.append(w)
w += 1
f.close()
target = np.array(target)
now = busses[0]
delta = [1]
on_target = False
while not on_target:
# for x in range(5):
wait = get_wait(now, busses)
delta = np.subtract(target, wait)
step = 1
for i in range(len(delta)):
if delta[i] == 0:
step *= busses[i]
now += step
on_target = (wait == target).all()
print(f"time: {now-step}")
print(f"busses: {busses}")
print(f"target: {target}")
print(f"wait: {wait}")
print(f"delta: {delta}")
timeStop = time.perf_counter_ns()
print(f"Runtime is {(timeStop - timeStart)/1000000} ms")
if __name__ == "__main__":
main()
|
f1e3c106a15893b3c1bb12a67e2ad3fc06fcb87c | aragon08/Python3-101 | /Python101/vectores_matrices.py | 671 | 3.609375 | 4 | # vectores y matices
import numpy as np
# vector = np.array([6,7,1,2,3])
# print(vector.astype(str))
# print(vector.astype(float))
# a = np.array([6,7,1,2,3])
# b = np.array([6,7,5,8,1])
# print(a + b)
# print(a * b)
# print(a > b)
# V = np.array([6,7,1,2,3])
# print(V[3])
# print(V.max())
# print(V.min())
# print(V.argmax())
# print(V.argmin())
# print(V.sum())
# print(V.prod())
# matrizA = np.array([[1,2,3],[4,5,6],[7,8,9]])
# matrizB = np.array([[1,2,3],[4,5,6],[7,8,9]])
# print('vector: ',V)
# print(matrizA + matrizB)
V = np.array([6,7,1,2,3])
matrizA = np.array([[1,2,3],[4,5,6],[7,8,9]])
print('vector: ', V.size)
print('Matriz: ', matrizA.size)
|
5f242bc99bd463422674c3027e84382e928a4c7b | addisgithub/dividend-Yeild-project | /list.py | 2,036 | 3.59375 | 4 | class Stock:
def __init__(self, name, high, low, date):
self.name = name
self.high = high
self.low = low
self.date = date
def remove(stonks):
temp = []
temp = stonks
temp_high = getTopstock(temp)
temp.remove(temp_high)
temp_low = getlasthighstock(temp)
temp.remove(temp_low)
total = sum(x.high for x in temp)
avg = total / len(temp)
return avg
def getTopstock(stonks):
highest = stonks[0]
for i in stonks:
if i.high > highest.high:
highest = i
return highest
def getlasthighstock(stonks):
lowest = stonks[0]
for i in stonks:
if i.high < lowest.high:
lowest = i
return lowest
def getlowstock(stonks):
highest = stonks[0]
for i in stonks:
if i.low < highest.low:
highest = i
return highest
def median(stonks):
assemble = sorted(stonks, key=lambda x: x.high, reverse=True)
if len(assemble) % 2 == 0:
ans = (assemble[int(len(assemble) / 2)].high + assemble[int(len(assemble) / 2) - 1].high) / 2
return ans
elif len(assemble) % 2 == 1:
ans_2 = len(assemble) / 2
return ans_2
def main():
stonks = []
stonks.append(Stock("appl", 534, 220, "02-20-2020"))
stonks.append(Stock("tsla", 543, 42, "02-20-2020"))
stonks.append(Stock("v", 565, 96, "02-20-2020"))
stonks.append(Stock("brhk", 5536, 963, "02-20-2020"))
stonks.append(Stock("nio", 5350, 3560, "02-20-2020"))
stonks.append(Stock("amzn", 3560, 780, "02-20-2020"))
stonks.append(Stock("boa", 4200, 660, "02-20-2020"))
stonks.append(Stock("co", 570, 70, "02-20-2020"))
stonks.append(Stock("mst", 230, 60, "02-20-2020"))
stonks.append(Stock("gh", 540, 40, "02-20-2020"))
#print(getTopstock(stonks).name)
#print(median(stonks))
print(remove(stonks))
#print(getlasthighstock(stonks).name)
if __name__ == "__main__":
main()
|
c329b28c1e8a2674899dfe4ee5b7ba6ca325ffff | faker-hong/testOne | /leetcode(多线程,DP,贪心,SQL)/二刷DP与贪心LeetCode/每日练习/剑指47. 礼物的最大价值/solution.py | 1,253 | 3.625 | 4 | '''
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。
你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。
给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
'''
class Solution(object):
def maxValue(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
m = len(grid[0])
dp = [[0] * m for _ in range(n)]
dp[0][0] = grid[0][0]
# base case
for i in range(1, n):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for j in range(1, m):
dp[0][j] = dp[0][j - 1] + grid[0][j]
for i in range(1, n):
for j in range(1, m):
dp[i][j] = grid[i][j] + max(dp[i - 1][j], dp[i][j - 1])
return dp[n-1][m-1]
if __name__ == '__main__':
grid = [
[1, 3, 1],
[1, 5, 1],
[4, 2, 1]
]
s = Solution()
res = s.maxValue(grid)
print(res) |
d1b1767a948f53f62fecddf4531313c47fadabb6 | pasinimariano/masterUNSAM | /clase06/rebotes.py | 586 | 3.734375 | 4 | # Ejercicio 1.5: La pelota que rebota
# rebotes.py
def rebotes():
altura = 100 # medida expresada en mts
rebotes = [] # se crea lista vacia donse se guardaran los rebotes que haga la pelota
cantidad = 0 # especifica la cantidad de rebotes que se realizaron
while len(rebotes) < 10:
altura = round(altura / 5 * 3, 2)
cantidad += 1
tupla = cantidad, altura
rebotes.append(tupla)
return rebotes
def incrementar(s):
carry = 1
l = len(s)
for i in range(l-1,-1,-1):
print(i)
incrementar([0,0,0,1,0,1]) |
3489abcbe0a9a2e702fa84a6219b47329945ac3d | CairoBars/MyPython | /basic/day8/threading_ext4_daemon.py | 589 | 3.578125 | 4 | #Author:Cairo Li
import threading
import time
def run(n):
print("task",n)
time.sleep(2)
print("task done",n,threading.current_thread())
start_time=time.time()
t_objs=[]
for i in range(50):
t=threading.Thread(target=run,args=("t-%s"%i,))
# t.setDaemon(True)#把当前线程设置成守护进程
#设置成守护线程,主线程退出后,不管子线程有没有执行完,子线程都会结束
t.start()
t_objs.append(t)
print("-----all threads has finished...",threading.current_thread(),threading.active_count())
print("cost:",time.time()-start_time) |
042b45636db98724492fa9566b38f0c598ad3f4d | deniseicorrea/Aulas-de-Python | /python/ex003.py | 144 | 3.75 | 4 | n1 = int(input('Digite o primeiro número:'))
n2 = int(input('Digite o segundo número: '))
s = n1+n2
print(f'A soma entre {n1} e {n2} é {s}' ) |
50a380fc90575a20c61f465ae2f37213238cfcfc | grance1/b | /args.py | 322 | 3.734375 | 4 | #!/usr/bin/python2.7
def fn(*args):
print args
print fn()
print fn('a')
print fn('a','b')
print fn('a','b','c')
def aversge(*args):
sum = 0.0
if len(args) == 0:
return sum
for x in args:
sum = sum + x
return sum / len(args)
print aversge()
print aversge(1,2)
print aversge(1,2,2,3,4)
|
eb2de8d823cc67c88934776536ec726bf29b2178 | Randle9000/pythonCheatSheet | /pluralsight/advanced_python/advanced_flow_control/dispatching_on_type/E0_initial_problem.py | 1,136 | 3.578125 | 4 | class Shape:
def __init__(self, solid):
self.solid = solid
class Circle(Shape):
def __init__(self, center, radius, *args, **kwargs):
super().__init__(*args,**kwargs)
self.center = center
self.radius = radius
def draw(self):
print("\u25CF" if self.solid else "\u25A1")
class Parallelogram(Shape):
def __init__(self, pa, pb, pc, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pa = pa
self.pb = pb
self.pc = pc
def draw(self):
print("\u25B0" if self.solid else "\u25B1")
class Triangle(Shape):
def __init__(self, pa, pb, pc, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pa = pa
self.pb = pb
self.pc = pc
def draw(self):
print("\u25B2" if self.solid else "\u25B3")
def main():
shapes = [Circle(center=(0.0), radius=5, solid=False),
Parallelogram(pa=(0,0), pb=(1,1), pc=(0.3), solid=True),
Triangle(pa=(0,0), pb=(2,3), pc= (0,1), solid=True)]
for shape in shapes:
shape.draw()
if __name__ == '__main__':
main() |
d5e43d970824c07364eac3137a21574cb6422517 | julianddd/StockScreener | /utilities/ioUtils.py | 610 | 3.578125 | 4 | import csv
def writeCSV(array, filePath='C:\\Users\\Julian\\Development\\StockScreener\\scratchPad\\', fileName='temp.csv'):
writer = csv.writer(open(filePath + fileName, 'w'), delimiter=',', lineterminator='\n')
for x in array:
writer.writerow([x])
def readCSV(filePath='C:\\Users\\Julian\\Development\\StockScreener\\scratchPad\\', fileName='temp.csv'):
array = []
reader = csv.reader(open(filePath + fileName))
for x in reader:
array.append(x)
return array
if __name__ == '__main__':
# writeCSV(['this, is, a, test', 'this, is, a, test'])
print(readCSV())
|
fa21cc7628de7735cd5b69ae1128f512c96e5873 | deocampo/bsd-tensorflow | /introduction/operations.py | 981 | 3.90625 | 4 |
import tensorflow as tf
# Basic constant operations
# The value returned by the constructor represents the output
# of the Constant op.
c1 = tf.constant(4)
c2 = tf.constant(5)
# Launch the default graph.
with tf.Session() as sess:
print("c1=4, c2=5")
print("Addition with constants: %i" % sess.run(c1+c2))
print("Multiplication with constants: %i" % sess.run(c1*c2))
# Basic Operations with variable as graph input
# The value returned by the constructor represents the output
# of the Variable op. (define as input when running session)
# tf Graph input
c1 = tf.placeholder(tf.int16)
c2 = tf.placeholder(tf.int16)
# Define some operations
add = tf.add(c1, c2)
mul = tf.multiply(c1, c2)
# Launch the default graph.
with tf.Session() as sess:
# Run every operation with variable input
print("Addition with variables: %i" % sess.run(add, feed_dict={c1: 4, c2: 5}))
print("Multiplication with variables: %i" % sess.run(mul, feed_dict={c1: 4, c2: 5}))
|
5f13694870caec29f801156e42523dbb11037297 | 2dam-spopov/di | /P5_Sergey-4.py | 1,768 | 4.25 | 4 | #!/usr/bin/python3
# Escriba un programa que permita crear una lista de palabras y que,
# a continuación, pida una palabra y elimine esa palabra de la lista.
# 1-Inicialización de variables.
# 2-Pregunta e introducción de número de palabras en la lista.
# Se usa control de error de excepción, si no se entroduce un
# número entero mayor que 0 el programa sigue preguntando.
# 3-Creación de la lista con valores introducidos.
# 4-Introducción de palabra para eliminación. Si la palabra no está en
# la lista da aviso y vuelve a preguntar. Da posibilidad de borrar
# otra palabra o terminar el programa.
#1#
lista = []
flag = True
#2#
while True:
try:
numPalabras = int(input("Dime cuántas palabras tiene la lista: "))
if numPalabras == 0 or numPalabras < 0:
print("Debes introducir un número mayor que 0")
continue
break
except ValueError:
print("Debes introducir un número entero")
#3#
if numPalabras > 0:
for i in range(0, numPalabras):
palabra = input("Dígame la palabra " + str(i+1) + ": ")
lista.append(palabra)
print("La lista creada es: ", lista)
#4#
while flag:
palabraElim = input("Palabra a eliminar: ")
vecesRepet = lista.count(palabraElim)
if vecesRepet == 0:
print("La palabra introducida no está en la lista, comprueba: ",
lista, " y vuelve a intentarlo: ")
else:
for i in range(vecesRepet):
lista.remove(palabraElim)
print("La lista es ahora: ", lista)
if input("¿Desea borrar otra palabra? s/n") != "s":
flag = False
|
31c272d873f818e4721df7228e627ea237598f1e | geekw/algorithms | /applications/myutils/combinatorial.py | 798 | 3.6875 | 4 |
# Returns the list of permutations of a list
class Permutation:
def __init__(self, the_list):
self._list = the_list
def __len__(self):
return len(self._list)
def solutions(self):
return self._permute(self._list)
# This implementation is extremely inefficient!!!
def _permute(self, elements):
print elements
if len(elements) == 1:
return [elements]
else:
solutions = list()
for head in elements:
remains = list(elements)
remains.remove(head)
rsolutions = self._permute(remains)
for rsolution in rsolutions:
rsolution.insert(0, head)
solutions.extend(rsolutions)
return solutions
|
26b65e2fbecfb044c26dbd26e1fde7f743238243 | Mpanshuman/Oretes_test-19-02-21- | /Q3.py | 581 | 3.796875 | 4 | size = int(input('Enter Number of marks:'))
alice = list(map(int,input('Enter marks of alice with spaces:').split()))
bob = list(map(int,input('Enter marks of bob with spaces:').split()))
alice_point = 0
bob_point = 0
# comparing marks of alice and bob and assiging points
for i in range(size):
if alice[i] < bob[i]:
bob_point +=1
elif alice[i] > bob[i]:
alice_point +=1
if __name__ == "__main__":
if alice_point > bob_point:
print('alice won')
elif bob_point > alice_point:
print('bob won')
else:
print('draw') |
fbce673a20b80418cf84822f846b3bd686d1cb04 | ralphS16/Euler-Project | /euler_prob4.py | 576 | 3.71875 | 4 | #Project Euler - Problem #4 : https://projecteuler.net/problem=4
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import math
def ispal(num):
text = str(num)
pal = True
for i in range(int(len(text)/2)):
if text[i] != text[-1*i-1]:
pal = False
return pal
bigpal = 0
for i in range(1000):
for j in range(1000):
if ispal(i*j):
if bigpal < i*j:
bigpal = i*j
print bigpal |
95eb0d7377ef4b27bc2782f6036c0a39e3b12a47 | lak4az/python-work | /hw4.py | 11,112 | 4.125 | 4 | ## Name: Logan King
## File: assignment04.py (STAT 3250)
## Topic: Assignment 4
##
import numpy as np
import pandas as pd
import re
## This assignment requires the data file 'airline_tweets.csv'. This file
## contains records of over 14000 tweets and associated information related
## to a number of airlines. You should be able to read this file in using
## the usual pandas methods.
airline_tweets = pd.read_csv('C:/Users/Student/Downloads/airline_tweets.csv')
## Note: Questions 1-9 should be done without the use of loops.
## Questions 10-13 can be done with loops.
## 1. Determine the number of tweets for each airline, indicated by the
## name in the 'airline' column of the data set. Give the airline
## name and number of tweets in table form.
airline_group = airline_tweets['airline'].groupby(airline_tweets['airline'])
#group by airline
airline_group.count()
#give count of each airline
'''
#1 Determine the number of tweets for each airline, indicated by the
## name in the 'airline' column of the data set
airline
American 2759
JetBlue 2222
Southwest 2420
US Airways 2913
United 3822
Virgin America 504
Name: airline, dtype: int64
'''
## 2. For each airlines tweets, determine the percentage that are positive,
## based on the classification in 'airline_sentiment'. Give a table of
## airline name and percentage, sorted from largest percentage to smallest.
pos_airline_tweets = airline_tweets[airline_tweets['airline_sentiment'] == 'positive']
#mask airline tweets to create dataframe with just positive tweets
pos_group = pos_airline_tweets['airline'].groupby(pos_airline_tweets['airline'])
#group positive df by airline
percent_pos = pos_group.count()/airline_group.count()*100
#find count of positive airline tweets divided by count of total airline tweets (from Q1)
#times 100 for percent
percent_pos.sort_values(ascending=False)
#sort values descending
'''
#2 table of
## airline name and percentage, sorted from largest percentage to smallest
airline
Virgin America 30.158730
JetBlue 24.482448
Southwest 23.553719
United 12.872841
American 12.178325
US Airways 9.234466
Name: airline, dtype: float64
'''
## 3. List all user names (in the 'name' column) with at least 20 tweets
## along with the number of tweets for each. Give the results in table
## form sorted from most to least.
user_group = airline_tweets['name'].groupby(airline_tweets['name'])
#group by usernames
user_count = user_group.count()
#get count of each username and save
user_count[user_count >= 20].sort_values(ascending=False)
#mask user count to users with more than 20 tweets and sort descending
'''
#3 all user names (in the 'name' column) with at least 20 tweets
## along with the number of tweets for each
name
JetBlueNews 63
kbosspotter 32
_mhertz 29
otisday 28
throthra 27
weezerandburnie 23
rossj987 23
MeeestarCoke 22
GREATNESSEOA 22
scoobydoo9749 21
jasemccarty 20
Name: name, dtype: int64
'''
## 4. Determine the percentage of tweets from users who have more than one
## tweet in this data set.
len(user_count[user_count > 1])/len(user_count)*100
#mask user count to only display those with more than one tweet, find length of table
#that gives us the number of users with more than one tweet. Then divide by the
#lenth of total users to get proportion with more than one tweet.
#multiply by 100 for percent
'''
#4 percentage of tweets from users who have more than one
## tweet
38.955979742890534
'''
## 5. Among the negative tweets, which five reasons are the most common?
## Give the percentage of negative tweets with each of the five most
## common reasons. Sort from most to least common.
neg_airline_tweets = airline_tweets[airline_tweets['airline_sentiment'] == 'negative']
#mask airline tweets to create df with only negative tweets
neg_group = neg_airline_tweets['negativereason'].groupby(neg_airline_tweets['negativereason'])
#group negative tweets by negative reason
neg_pcts = neg_group.count()/len(neg_airline_tweets)*100
#find the count of each negative reason and divide by total number of negative tweets
#multiply by 100 to get percent
neg_pcts.sort_values(ascending=False).nlargest(5)
#sort descending and show top 5
'''
#5 Give the percentage of negative tweets with each of the five most
## common reasons
negativereason
Customer Service Issue 31.706254
Late Flight 18.141207
Can't Tell 12.965788
Cancelled Flight 9.228590
Lost Luggage 7.888429
Name: negativereason, dtype: float64
'''
## 6. How many of the tweets for each airline include the phrase "on fleek"?
np.sum(airline_tweets.text.str.contains('on fleek'))
#find the tweets that contain all fleek and take the sum
'''
#6 tweets for each airline include the phrase "on fleek"
146
'''
## 7. What percentage of tweets included a hashtag?
np.sum(airline_tweets.text.str.contains('#'))/len(airline_tweets.text)*100
#find the sum of tweets that contain a hashtag, divide by total number of tweets
#multiply by 100
'''
#7 percentage of tweets included a hashtag
17.001366120218577
'''
## 8. How many tweets include a link to a web site?
np.sum(airline_tweets.text.str.contains('http'))
#since links start with http or https, find sum of strings that contain each and add
'''
#8 tweets include a link to a web site
1173
'''
## 9. How many of the tweets include an '@' for another user besides the
## intended airline?
len(airline_tweets.text.str.count('@')[airline_tweets.text.str.count('@')>1])
#take count @ in each string
#mask that to only display those tweets with more than one @
#take length of that
'''
#9 tweets include an '@' for another user besides the
## intended airline
1645
'''
## 10. Suppose that a score of 1 is assigned to each positive tweet, 0 to
## each neutral tweet, and -1 to each negative tweet. Determine the
## mean score for each airline, and give the results in table form with
## airlines and mean scores, sorted from highest to lowest.
sentiment_value = [] #create blank array for sentiment value
for i in range(len(airline_tweets.airline_sentiment)):
#loop for range of length of airline_sentiment array in dataframe
if airline_tweets.airline_sentiment[i] == 'positive':
sentiment_value.append(1)
#append 1 to the array if positive sentiment
if airline_tweets.airline_sentiment[i] == 'neutral':
sentiment_value.append(0)
#append 0 to array if neutral sentiment
if airline_tweets.airline_sentiment[i] == 'negative':
sentiment_value.append(-1)
#append -1 to array if negative sentiment
airline_tweets['sentiment_value'] = sentiment_value
#append the array to airline tweets df
sent_group = airline_tweets['sentiment_value'].groupby(airline_tweets['airline'])
#group airline tweets by their sentiment value
sent_group.mean().sort_values(ascending=False)
#take mean of sentiment values for each airline and sort descending
'''
#10 Determine the
## mean score for each airline, and give the results in table form with
## airlines and mean scores, sorted from highest to lowest
airline
Virgin America -0.057540
JetBlue -0.184968
Southwest -0.254545
United -0.560178
American -0.588619
US Airways -0.684518
Name: sentiment_value, dtype: float64
'''
## 11. Among the tweets that "@" a user besides the indicated airline,
## what percentage include an "@" directed at the other airlines
## in this file? (Note: Twitterusernames are not case sensitive,
## so '@MyName' is the same as '@MYNAME' which is the same as '@myname'.)
airlines = ['@virginamerica','@united','@southwestair','@jetblue', '@usairways','@americanair']
#create list of airline twitter handles
def mult(text): #create function
ct = 0 #set count to 0
for i in airlines: #loop for each airline twitter handle
if text.count(i) >=1: #if the airline appears once or more in string
ct += 1 #add 1 to count
if ct >= 2: #if count is greater than or equal to 2
return True #return true
else: #else
return False #return false
over1 = airline_tweets[airline_tweets['text'].str.count('@')>1]
#find number of tweets with more than one mention
ans11 = over1['text'].str.lower().apply(mult).sum()/len(over1)*100
#make text of tweets with more than one mention lowercase and apply the function,
#take sum of output, divide by length of tweets with more than one mention
#multiply by 100 for percent
ans11 #print answer
'''
#11 percentage include an "@" directed at the other airlines
21.458966565349545
'''
## 12. Suppose the same user has two or more tweets in a row, based on how they
## appear in the file. For such tweet sequences, determine the percentage
## for which the most recent tweet (which comes nearest the top of the
## file) is a positive tweet.
prev = airline_tweets.iloc[0:-2,].reset_index() #all rows before last two rows
dur = airline_tweets.iloc[1:-1,].reset_index() #all rows except first and last rows
post = airline_tweets.iloc[2:,].reset_index() #all rows after first two rows
rate = dur['airline_sentiment'][(prev['name']!=dur['name'])&(dur['name']==post['name'])]
#rows with same user tweeting sight after they tweeted
np.mean(rate == 'positive')*100
#percentage of tweets that are positive
'''
#12 determine the percentage
## for which the most recent tweet (which comes nearest the top of the
## file) is a positive tweet
11.189634864546525
'''
## 13. Give a count for the top-10 hashtags (and ties) in terms of the number
## of times each appears. Give the hashtags and counts in a table
## sorted from most frequent to least frequent. (Note: Twitter hashtags
## are not case sensitive, so '#HashTag', '#HASHtag' and '#hashtag' are
## all regarded as the same. Also ignore instances of hashtags that are
## alone with no other characters.)
airline_tweets = pd.read_csv('C:/Users/Student/Downloads/airline_tweets.csv')
#reinitialize dataframe
airline_tweets.text.str.lower().str.extractall(r'(\#\w+)')[0].value_counts().head(10)
#make all tweets lowercase, extract every hashtag in each string
#take counts of each, display top 10
'''
#13 Give the hashtags and counts in a table
## sorted from most frequent to least frequent
#destinationdragons 81
#fail 69
#jetblue 48
#unitedairlines 45
#customerservice 36
#usairways 30
#neveragain 27
#americanairlines 27
#united 26
#usairwaysfail 26
Name: 0, dtype: int64
'''
|
d6cfed1b99f3cb5be9591fe948d92e15b707ab7a | shrutipatil12/python_basic | /python/FirstName.py | 165 | 3.9375 | 4 | #Program to accept and display user name.
print("Enter the first name")
FirstName=input ()
print("Enter last name")
LastName=input()
print( LastName , FirstName) |
19d9f78e2e3d70767de3f917ae7b46f42bc0f85a | dheeraj1010/Hackerrank_problem_solving | /Repeated_string.py | 315 | 3.859375 | 4 | import math
def repeatedString(s, n):
x = math.floor(n/len(s))
first_repeat = x*(s.count('a'))
x = n%len(s)
s = s[:x]
second_repeat = s.count('a')
repeation = first_repeat+second_repeat
return repeation
s = input().strip()
n = int(input())
result = repeatedString(s, n)
print(result)
|
0c1362828e276674dbae0511361c5ed21f4b5119 | rmgard/python_deep_dive | /secondSection/theClassRoom.py | 3,650 | 3.8125 | 4 | ################################################
# Classes & OOP
################################################
################################################
# Class with Getters and setters
################################################
class RectangleGetSet:
def __init__(self, width, height):
self._width = width
self._height = height
def area(self):
return self._width * self._height
def perimeters(self):
return 2 * (self._width + self._height)
'''def to_string(self):
return 'Rectangle: width={0}, height={1}'.format(self._width, self._height)
'''
def __str__(self):
return 'Rectangle: width={0}, height={1}'.format(self._width, self._height)
def get_width(self):
return self._width
def set_width(self, width):
if width <= 0:
raise ValueError('Width must be positive.')
else:
self._width = width
def __repr__(self):
return 'Rectangle({0}, {1})'.format(self._width, self._height)
def __eq__(self, other):
if isinstance(other, Rectangle):
return self._width == other._width and self._height == other._height
else:
return False
def __lt__(self, other):
if isinstance(other, Rectangle):
return self. area() < other.area()
else:
return NotImplemented
################################################
# Pythonic Class
################################################
class Rectangle:
''' The commented out init method below instantiates our width and height in such a way
that a rectangle can take negative values for width and height.
To resolve this, we can write an init function that calls our property getter
in order to run through some of the logic of the property. This can be seen in
the new init method directly below this commented out block.
def __init__(self, width, height):
self._width = width
self._height = height
'''
def __init__(self, width, height):
self.width = width
self.height = height
''' We can basically bypass Java like getters and setters by using our properties
These properties can be left alone until they're actually needed, which is
helpful because we won't break backwards compatability even though we doing
instantiate the class with a get/set method'''
@property
def width(self):
return self._width
@width.setter
def width(self, width):
if width <= 0:
raise ValueError('width must be positive')
else:
self._width = width
@property
def height(self):
return self._height
@height.setter
def height(self, height):
if height <= 0:
raise ValueError('height must be positive')
else:
self._height = height
def __str__(self):
return 'Rectangle: width={0}, height={1}'.format(self.width, self.height)
def getwidth(self):
return self.width
def setwidth(self, width):
if width <= 0:
raise ValueError('Width must be positive.')
else:
self.width = width
def __repr__(self):
return 'Rectangle({0}, {1})'.format(self.width, self.height)
def __eq__(self, other):
if isinstance(other, Rectangle):
return self.width == other.width and self.height == other.height
else:
return False
def __lt__(self, other):
if isinstance(other, Rectangle):
return self. area() < other.area()
else:
return NotImplemented
|
80aa7f96e957e0bb973a08f6064f423d032b007b | csenn/alg-practice | /general/stack.py | 612 | 3.796875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
node.next = self.head
self.head = node
def pop(self):
if not self.head or not self.head.next:
return None
self.head = self.head.next
if __name__ == '__main__':
stack = Stack()
stack.add(1)
print stack.head.data
stack.add(2)
print stack.head.data
stack.pop()
print stack.head.data
stack.add(4)
print stack.head.data
|
2486b778270ef6ea369dd0b685ec2f9a7489f9e7 | jsdelivrbot/prototipos | /Python/01.Vanilla/01.September/01.Object_And_Data_Structure_Basics/04.lists.py | 1,368 | 3.953125 | 4 | my_list = [1, 2, 3]
# 1st, 1st, 3rd
my_list = ['string', 5, 6.2]
# ['string', 5, 6.2]
# print(my_list)
print(len(my_list))
# 3
# indexing andslicing
my_list = ['one', '2', 3]
print(my_list[0])
# one
print(my_list[1:])
# ['2', 3]
print(my_list[:2])
# ['one', '2']
# ==============================================
# methods
print(my_list + ['fourth']) # SAME AS append
# ['one', '2', 3, 'fourth']
# permenant
my_list = my_list + ['fourth']
print(my_list)
# ['one', '2', 3, 'fourth']
print(my_list * 2)
# ['one', '2', 3, 'fourth', 'one', '2', 3, 'fourth']
a = [1, 2, 3]
a.append('append') # SAME AS +
print(a)
# [1, 2, 3, 'append']
a.pop() #permanent last index
print(a)
# [1, 2, 3]
firsttt = a.pop(0) # permanent index
print(a)
# [2, 3]
print(firsttt)
# 1
new_list = ['e', 'v', 'e', 'r']
new_list.reverse() #permen
print(new_list)
# ['r', 'e', 'v', 'e']
new_list.sort()
print(new_list)
# ['e', 'e', 'r', 'v']
# ====================================================
a_1 = [1, 2, 3]
a_2 = [4, 5, 6]
a_3 = [7, 8, 9]
matrix = [a_1, a_2, a_3]
print(matrix)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2], matrix[0][1], matrix[0][0])
# 6 2 1
# =================List Comprehension =====================
first_col = [row[0] for row in matrix]
print(first_col)
# [1, 4, 7]
|
b9e885e02965fac2da59bf9529d88bfbcdee980e | BaileyKindrick96/CSCI-220-and-220L-Python | /HW2BookProblems-1.py | 3,680 | 3.96875 | 4 | '''Homework for Chapter 2
Name: Bailey Kindrick
I certify that is entirely my work.
Chapter 2
Book questions (30%)
T/F
1. F
2. T
3. F
4. T
5. F
6. T
7. T
8. F
9. T
10. F
Multiple Choice
1. C
2. A
3. D
4. A
5. B
6. D
8. A
10. D
Discussion
4a. 0
1
4
9
16
4b. TypeError: 'type' object is not subscriptable
4c. Hello
Hello
Hello
Hello
4d. 0 1
1 2
2 4
3 8
4 16
5. It is a good idea to write in pseudocode because it will allow you to formulate your ideas without worrying about the rules of Python.
6. The 'sep' parameter can be utilized in a print statement on any character, string, or integer. The ‘sep’ parameter is also to format output statements with strings.
7. What prints when the code is executed?
Programming Exercises (70%)
'''
# Example worked for you.
# Write a program that inputs numbers separated by a comma
# and then uses a loop to add the numbers
def addNums():
# Input the numbers from the user
numbers = eval(input('Input some numbers separated by a comma: '))
# Initialize a variable to use to add the numbers
total = 0
# Loop through the numbers to add them all to total
for num in numbers:
total = total + num
# Print the result to the shell
print('The total of the numbers is:',total)
addNums()
# Exercise 2 Change program to get average of 3 scores and change the comments
# names, etc to match the new program.
# avg2.py
# A simple program to average two exam scores
# Illustrates use of multiple input
def avg3():
print("This program computes the average of three exam scores.")
score1, score2, score3 = eval(input("Enter three scores separated by a comma: "))
average = (score1 + score2 + score3) / 3
print("The average of the scores is:", average)
avg3()
# Exercise 4 Modify program to compute and print a table of Celsius
# values and the Fahreneit equivalent every 10 degrees from 0 to 100.
# convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell
def convert():
print("This program prints a table of celsius and fahrenheit temperatures")
print("every 10 degrees from 0C to 100C")
celsius = 0
fahrenheit = 9/5 * celsius + 32
for i in range(0, 101, 10):
newcelsius = i
newfahrenheit = 9/5 * newcelsius + 32
print("celsius", newcelsius, "fahrenheit", newfahrenheit)
convert()
# Exercise 5 Modify the program so that years is a user input
# futval.py
# A program to compute the value of an investment
# carried 10 years into the future
def futval():
print("This program calculates the future value")
print("of a 10-year investment.")
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annual interest rate: "))
yr = eval(input("Enter the number of years: "))
for i in range(yr):
principal = principal * (1 + apr)
print("The value in 10 years is:", principal)
futval()
# Last exercise (not in the book) Write a program that inputs
# numbers separated by a comma and then uses a loop to add the
# inverse (1/x) of the numbers, i.e. (1/x + 1/x + ...), and to add
# the square (x ** 2) of each number (x ** 2 + x ** 2 + ...).
def addInverse():
numbers = eval(input("Input some numbers seperated by a comma: "))
inverseTot = 0
squareTot = 0
for num in numbers:
inverseTot = inverseTot + 1/num
squareTot = squareTot + num ** 2
print("Inverse Total: ", inverseTot, "Square Total: ", squareTot)
addInverse()
|
57fa6892c9c72deeecddc089a6e92ba2e8eb12a8 | hayley01145553/Web_Scraping_Project | /NationalParkVisitation/NationalParkVisitation/spiders/np_visitation_spider.py | 4,356 | 3.515625 | 4 |
from scrapy import Spider
from NationalParkVisitation.items import NationalparkvisitationItem
# for문 이름
# for문 입장료
# 이름, 입장료를 zip으로 묶어서 튜플로 되고 이거를 List에 넣음
# 만든 최종 리스트를 가지고 item에 넣어서 yield
class NPVisitationSpider(Spider):
name = "np_visitation_spider"
allowed_urls = ['https://www.nps.gov']
start_urls = ['https://www.nps.gov/aboutus/visitation-numbers.htm']
def parse(self, response):
part = response.xpath('//div[@class="table-wrapper"]')[1]
item = part.xpath('./table//tr')
print("##############")
print(item)
for i,v in enumerate(item):
if(i==0):
continue
item = NationalparkvisitationItem()
num = v.xpath('./td[1]//text()').extract_first()
park_name=v.xpath('./td[2]//text()').extract_first()
visits_number = v.xpath('./td[3]//text()').extract_first()
item['num'] = num
item['park_name'] = park_name
item['visits_number'] = visits_number
yield item
'''
park_name_list = []
park_info_list = []
#get park name list
for i,v in enumerate(part):
print("i:",i)
if(i==0):
continue
else:
print("-"*30)
#park_name= i.xpath('./h3/text()').getall()
#park_name= i.xpath('./h3').getall()
park_name= v.xpath('.//h3/text()').getall()
#print(park_name)
park_name_list.extend(park_name)
#print("="*30,"park_name_list","="*30)
print(park_name_list, " np name count : " ,str(len(park_name_list)))
#print("check value: ", v.xpath('./div[@class="table-wrapper"]/table//tr/td/b/text()'))
#print("check value: ", v.xpath('./div[@class="table-wrapper"]/table').getall())
info_per_park = v.xpath('./div[@class="table-wrapper"]/table')
# per park
for j in info_per_park:
per_park_list = [];
info_per_row = j.xpath('.//tr')
# per row(time)
for i2,k in enumerate(info_per_row):
per_row_list = [];
if(i2==0):
continue
time = k.xpath('.//td[1]//text()').extract_first()
annual_pass=k.xpath('.//td[2]//text()').extract_first()
per_vehicle = k.xpath('.//td[3]//text()').extract_first()
per_person = k.xpath('.//td[4]//text()').extract_first()
per_motorcycle = k.xpath('.//td[5]//text()').extract_first()
per_row_list.append(time)
per_row_list.append(annual_pass)
per_row_list.append(per_vehicle)
per_row_list.append(per_person)
per_row_list.append(per_motorcycle)
per_park_list.append(per_row_list)
print("-per_row_list-: ", per_row_list)
park_info_list.append(per_park_list)
print("=per_park_list=: ", per_park_list)
print("=park_info_list=: ", park_info_list, " np info count : " ,str(len(park_name_list)))
item = BestbuyItem()
item['user'] = user
item['rating'] = rating
item['title'] = title
item['text'] = text
item['helpful'] = helpful
item['unhelpful'] = unhelpful
item['product'] = product
item['question'] = question
yield item
park_merge_info_list = [(i, j) for i, j in zip(park_name_list,park_info_list)]
print("="*30)
print(park_merge_info_list)
print("="*30)
for z in park_merge_info_list:
for y in z[1]:
item = NPEntranceFeeItem()
#print(y)
#print(y[0])
item['park_name'] = z[0]
item['park_name'] = z[0]
item['time'] = y[0]
item['annual_pass'] = y[1]
item['per_vehicle'] = y[2]
item['per_person'] = y[3]
item['per_motorcycle'] = y[4]
yield item
#print(i)
# rows.get_attribute("innerHTML")
for row in rows[1:]:
RDate = row.xpath('./td[2]/a/text()').extract_first()
Title = row.xpath('./td[3]/b/a/text()').extract_first()
PBudget = row.xpath('./td[4]/text()').extract_first()
DomesticG = row.xpath('./td[5]/text()').extract_first()
WorldwideG = row.xpath('./td[6]/text()').extract_first()
item = BudgetItem()
item['RDate'] = RDate
item['Title'] = Title
item['PBudget'] = PBudget
item['DomesticG'] = DomesticG
item['WorldwideG'] = WorldwideG
yield item
'''
# for문 이름
# for문 입장료
# 이름, 입장료를 zip으로 묶어서 튜플로 되고 이거를 List에 넣음
# 만든 최종 리스트를 가지고 item에 넣어서 yield
|
f56efd9750752337e58469f3574c36307419a031 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2194/60617/289423.py | 531 | 3.921875 | 4 | def find_Primes():
row=input().split(" ")
left=int(row[0])
right=int(row[1])
res=[]
for i in range(left,right+1):
if i==1:
continue
if(is_Prime(i)):
res.append(i)
for num in res:
if num!=res[-1]:
print(num, end=" ")
else:
print(num)
def is_Prime(x):
for i in range(2,x):
if x%i==0:
return False
return True
if __name__=='__main__':
T=int(input())
for i in range(0,T):
find_Primes() |
75d1077dfec745448caa021389e5d2acc48ff12f | saulQuirogaDVL/Estadistica | /Estadistica.py | 7,883 | 3.640625 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
datos = input('Coloque la ruta del archivo txt: ')
cantDatos=list()
ListaSO=np.loadtxt(datos)
#elimina los repetidos de la lista
def eliminar_repetidos(lista):
nueva=[]
for elemento in lista:
if not elemento in nueva:
nueva.append(elemento)
return nueva
ListaSR=eliminar_repetidos(ListaSO)
#ordena los elementos de la lista(Bubble)
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
bubbleSort(ListaSR)
tam=range(len(ListaSO))
tam2=range(len(ListaSR))
for i in tam2:
cont=0
for j in tam:
if ListaSR[i]==ListaSO[j]:
cont+=1
cantDatos.append(cont)
def Calcular_Frecuencia(ListaF):
suma=0
tamanio=range(len(ListaF))
for i in tamanio:
suma += ListaF[i]
return suma
totalDatos=Calcular_Frecuencia(cantDatos)+1
#media arimetica
def Calcular_Media(ListaD):
suma=0
cont=0
tamanio=range(len(ListaD))
for u in tamanio:
suma+=(ListaD[u])
cont+=1
return suma/cont
Media_Aritmetica=Calcular_Media(ListaSO)
#mediana
def Calcular_Mediana(ListaD):
tamanio=len(ListaD)
mitad=(tamanio%2)
medio=int(tamanio/2)
if(mitad==1):
return ListaD[medio]
else:
return (ListaD[medio]+ListaD[medio-1])/2
bubbleSort(ListaSO)
Mediana=Calcular_Mediana(ListaSO)
#moda
def Calcular_Moda(ListaD,ListaF):
val_max=0
fre_max=0
valor_final=""
tamanio=range(len(ListaF))
for i in tamanio:
if ListaF[i]>fre_max:
fre_max=ListaF[i]
val_max=ListaD[i]
valor_final=val_max
elif ListaF[i]==fre_max:
valor_final="no tiene moda"
return valor_final
Moda=Calcular_Moda(ListaSR,cantDatos)
#media geometrica
def Calcular_Geometrica(ListaD):
suma=1
cont=0
tamanio=range(len(ListaD))
for i in tamanio:
suma*=ListaD[i]
cont+=1
return suma**(1 /cont)
Media_Geometrica=Calcular_Geometrica(ListaSO)
#media armonica
def Calcular_Armonica(ListaD):
suma=0
cont=0
tamanio=range(len(ListaD))
for i in tamanio:
suma+=1/ListaD[i]
cont+=1
return cont/suma
Media_Armonica=Calcular_Armonica(ListaSO)
#desviacion media
def Calcular_Desviacion(ListaD):
suma=0
valor=0
cont=0
tamanio=range(len(ListaD))
for i in tamanio:
valor=ListaD[i]-Media_Aritmetica
if(valor<0):
valor=valor*-1
suma+=valor
cont+=1
return suma/cont
Desviacion=Calcular_Desviacion(ListaSO)
#Desviacion estandar
def Calcular_Desviacion_Estandar(ListaD):
suma=0
valor=0
cont=0
tamanio=range(len(ListaD))
for i in tamanio:
valor=(ListaD[i]-Media_Aritmetica)**2
suma+=valor
cont+=1
if(cont<=30):
cont-1
return math.sqrt(suma/cont)
Desviacion_Estandar=Calcular_Desviacion_Estandar(ListaSO)
#varianza
def Calcular_Varianza(desv_est):
return desv_est**2
Varianza=Calcular_Varianza(Desviacion_Estandar)
#dispersion relativa
def Calcular_Dispercion(desv_est,med_arit):
return (desv_est/med_arit)*100
Dispercion=Calcular_Dispercion(Desviacion_Estandar,Media_Aritmetica)
#momento respecto de 0
def Calcular_Momento(ListaD,NDM):
suma=0
cont=0
tamanio=range(len(ListaD))
for i in tamanio:
suma+=ListaD[i]**NDM
cont+=1
return suma/cont
momento_uno=Calcular_Momento(ListaSO,1)
momento_dos=Calcular_Momento(ListaSO,2)
momento_tres=Calcular_Momento(ListaSO,3)
momento_cuatro=Calcular_Momento(ListaSO,4)
#momento respecto de cualquier origen
def Calcular_Momento_X(ListaD,NDM,const):
suma=0
cont=0
tamanio=range(len(ListaD))
for i in tamanio:
suma+=(ListaD[i]-const)**NDM
cont+=1
return suma/cont
constante=1
momento_uno_x=Calcular_Momento_X(ListaSO,1,constante)
momento_dos_x=Calcular_Momento_X(ListaSO,2,constante)
momento_tres_x=Calcular_Momento_X(ListaSO,3,constante)
momento_cuatro_x=Calcular_Momento_X(ListaSO,4,constante)
#momento respecto a la media
momento_dos_M=momento_dos_x-(momento_uno_x**2)
momento_tres_M=momento_tres_x-((3*momento_uno_x)*momento_dos_x)+(2*(momento_uno_x**3))
momento_cuatro_M=momento_cuatro_x-((4*momento_uno_x)*momento_tres_x)+((6*(momento_uno_x**2))*momento_dos_x)-(3*(momento_uno_x**4))
#sesgo
def Calcular_Sesgo(med,mod,desv_est,median):
if(mod=="no tiene moda"):
return (3*(med-median))/desv_est
else:
return (med-mod)/desv_est
def Calcular_Direccion_Sesgo(valor):
if(valor>0):
return "derecha"
else:
return "izquierda"
def Calcular_Distribucion_Sesgo(valor):
if(valor<0):
valor=valor*-1
if(valor==0):
return "simetrica"
elif(valor>0 and valor<=0.10):
return "ligeramente sesgado"
elif(valor>0.10 and valor<=0.30):
return "moderadamente sesgado"
elif(valor>0.30 and valor<=1):
return "marcadamente sesgado"
#Sesgo=round(Calcular_Sesgo(Media_Aritmetica,Moda,Desviacion_Estandar,Mediana),2)
Sesgo=(momento_tres_M)/(Desviacion_Estandar**3)
if(Sesgo>0):
Sesgo=(round(Sesgo-3,3))
else:
Sesgo=(round(Sesgo,3))
Direccion_Sesgo=Calcular_Direccion_Sesgo(Sesgo)
Distribucion_Sesgo=Calcular_Distribucion_Sesgo(Sesgo)
#curtosis
Curtosis=(momento_cuatro_M)/(Desviacion_Estandar**4)
if(Curtosis>0):
Curtosis=(round(Curtosis-3,3))
else:
Curtosis=(round(Curtosis,3))
Distribucion_Curtosis=""
if(Curtosis<0):
Curtosis=Curtosis*-1
if(Curtosis==0.263):
Distribucion_Curtosis="Mesocutica"
elif(Curtosis>0.263):
Distribucion_Curtosis="Leptocurtica"
elif(Curtosis<0.263):
Distribucion_Curtosis="Platicurtica"
#histogramas
X=[x for x in range(len(ListaSR))]
plt.bar(ListaSR,X,label='Datos 1',width=0.5,color='lightblue')
plt.title('Gradico de barras')
plt.ylabel('Frecuencias')
plt.xlabel('Datos')
plt.legend()
plt.show()
#C:\Users\hp\Documents\Univalle\Estadistica Computacional\Proyecto_Final
print("La media aritmetica es: "+str(round(Media_Aritmetica,2)))
print("La mediana es: "+str(Mediana))
print("La moda es: "+str(Moda))
print("La media geometrica es:"+str(round(Media_Geometrica,2)))
print("La media armonica es:"+str(round(Media_Armonica,2)))
print("La desviacion media es: "+str(round(Desviacion,2)))
print("La desviacion estandar es: "+str(round(Desviacion_Estandar,2)))
print("La dispercion absoluta: "+str(round(Desviacion_Estandar,2)))
print("La dispecion relativa es: "+str(round(Dispercion,2))+"%")
print("Momentos respecto de 0:")
print("momento uno: "+str(momento_uno))
print("momento dos: "+str(momento_dos))
print("momento tres: "+str(momento_tres))
print("momento cuatro: "+str(momento_cuatro))
print("Momentos respecto de cualquier origen (X="+str(constante)+")")
print("momento uno X: "+str(momento_uno_x))
print("momento dos X: "+str(momento_dos_x))
print("momento tres X: "+str(momento_tres_x))
print("momento cuatro X: "+str(momento_cuatro_x))
print("Momentos respecto a la media")
print("momento dos M: "+str(momento_dos_M))
print("momento tres M: "+str(momento_tres_M))
print("momento cuatro M: "+str(momento_cuatro_M))
print("Sesgo: "+str(Sesgo))
print("el sesgo es "+str(Distribucion_Sesgo)+" hacia la "+str(Direccion_Sesgo))
print("Curtosis: "+str(Curtosis))
print("la curtosis es: "+str(Distribucion_Curtosis))
|
58d5e9a9b60b2d6df8364a05a1c804ba932fc062 | anasmorahhib/Master-Data-Science-FSSM | /02.Data mining/ex2-Euclidean-distance-between-two-images/euclidean-distance-between-two-images.py | 1,258 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[14]:
# importing libraries
import numpy as np
import math
import matplotlib.image as img
# In[15]:
# two images to calculate the distance between them
# imgread for transform image tu vector
testImage = img.imread("img-1.png")
testImage2 = img.imread("img-2.png")
# In[16]:
# the image dimensions
# in this example 32*32 it's the pixel number of height and width of the image
# 3 is the main color number (RGB) example: [0,0,0] is [0 red, 0 green and 0 blue] -> so this pixel is black
testImage.shape
# In[17]:
# Euclidean distance using the numpy library
print('Euclidean distance:', np.linalg.norm(testImage - testImage2))
# In[18]:
# Euclidean distance without library
def calculdist() :
pixels = testImage.shape[0] * testImage.shape[1] * testImage.shape[2]
distance = 0
for i in range(0, testImage.shape[0]):
for j in range(0, testImage.shape[1]):
for k in range(0, testImage.shape[2]):
distance += (testImage[i][j][k] - testImage2[i][j][k])**2
# if the return is 0, then these are the same images
return {"distance" : distance, "sqrt distance": math.sqrt(distance), "percentage": distance/pixels }
print(calculdist())
|
41ad32a17795ce209a9c1499b325b76d514a2bf9 | YeonggilGo/python_practice | /SWEA/D1/2056_calendar.py | 611 | 3.8125 | 4 | thirty_one = [1, 3, 5, 7, 8, 10, 12, [31]]
thirty = [4, 6, 9, 11, [30]]
twenty_eight = [2, [28]]
total_month = [thirty, thirty_one, twenty_eight]
T = int(input())
for tc in range(1, T + 1):
date = input()
year = date[:4]
month = date[4:6]
day = date[6:]
ans = 0
found = False
for each_month in total_month:
if int(month) in each_month:
found = True
if int(day) > each_month[-1][0]:
ans = -1
break
if not found:
ans = -1
if not ans:
ans = f'{year}/{month}/{day}'
print(f'#{tc} {ans}')
|
0f7648d450847448cdd1d25a6e3b4f8669fc424e | Yobretaw/AlgorithmProblems | /Py_leetcode/049_anagrams.py | 579 | 3.875 | 4 | import sys
import math
from collections import defaultdict
"""
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
"""
def anagrams(strs):
n = len(strs)
if n < 2:
return []
strs.sort()
m = defaultdict(list)
for s in strs:
sorted_s = ''.join(sorted([c for c in s]))
m[sorted_s].append(s)
res = []
for key, val in m.iteritems():
if len(val) > 1:
res.extend(val)
return res
|
30cd8f3f83ffaf07e7afec123aab072c553d9067 | Paychokxxx/flask_store_app_with_test | /test.py | 466 | 3.59375 | 4 | import json
# serializing JSON / making data dump / save
# python objs ==> JSON objs
json_string = """
{
"researcher": {
"name": "Ford Prefect",
"species": "Betelgeusian",
"relatives": [
{
"name": "Zaphod Beeblebrox",
"species": null
}
]
}
}
"""
# loads from JSON encoded data ==> python objects
# deserializing JSON / read
data = json.loads(json_string)
print(type(data))
print(data) |
537c1bdcd7affb468122d794230d32c2d2bdf61a | oplaf/sandbox | /sandbox4.py | 382 | 3.875 | 4 | import random
def main():
file = open("silly.txt", 'r')
read_file = file.readlines()
random_line = random.choice(read_file)
print(random_line)
def reverser():
rev_file = open("reversable.txt", 'r')
read_rev_file = rev_file.readlines()
to_insert = read_rev_file[1]
print(f"welcome to {to_insert}, Fantastic student")
#reverser()
main() |
41f3e90e0d9c12e9cfecec43da911ac9bc0f6d19 | AlbertoReal/Practicas_python | /pr5/pr5ejer9.py | 612 | 4.0625 | 4 | #Alberto Real Gomez: practica 5 ejer 8: trinagulo ancho
entrada1=int(input("altura del rectangulo"))
entrada2=int(input("lado del rectangulo"))
for i in range (entrada1):
if i==0:
for j in range (entrada2):
print("*",end="")
elif i==entrada1-1:
for j in range (entrada2):
print("*",end="")
else:
for j in range (entrada2):
if j==0:
print("*",end="")
elif j==entrada2-1:
print("*",end="")
else:
print(" ",end="")
print ("\n")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.