blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
da208b91fc0a69c00027e586d6e02a74a6cadb85 | harshitbhat/Data-Structures-and-Algorithms | /GeeksForGeeks/DS-Course/001-BitwiseOperators/004.leftShift.py | 309 | 3.984375 | 4 | '''
Left Shift Operator ( << ): It shifts the bit left by the amount specified and adds 0 in same amount to the right side of the number, thus it multiplies the number.
i.e x << y, this implies that resultant is x * (2^y)
'''
x = 3
print(x << 1) # 6
print(x << 2) # 12
print(x << 3) # 24
print(x << 4) # 48 |
5f3ca88b3366568b983118f161fb80c9f9f4880f | Zahidsqldba07/python_course_exercises | /TEMA 2_CONDICIONALES/Condicionales/ej2.5.py | 520 | 4.09375 | 4 | #!/usr/bin/python3
#Programa que te dice de una entrada de tres numeros cual es mayor
try:
num1=int(input("Introduce un número: "))
num2=int(input("Introduce un número: "))
num3=int(input("Introduce un número: "))
if num1 > num2 and num1 > num3:
print("El numero " + str(num1) + " es mayor")
elif num2 > num1 and num2 > num3:
print("El numero " + str(num2) + " es mayor")
elif num3 > num1 and num3 > num2:
print("El numero " + str(num3) + " es mayor")
except:
print("Introduce números, por favor") |
337a56ee750ded41572f55120085f69a0b162681 | jefethibes/Aulas | /Python/Python/ExeLista24.py | 673 | 4.1875 | 4 | '''24 - Receba duas listas e exiba a união destas listas e a intercalação destas listas,
isto é, 1º da 1ª lista, 1º da 2ª lista, 2º da 1ª lista, 2º da 2ª lista.'''
lista1 = []
lista2 = []
lista_intercalada = []
print('Digite 5 elementos para a lista 1:')
for i in range(5):
lista1.append(input('Elemento {}: '.format(i)))
print('Digite 5 elementos para a lista 2:')
for i in range(5):
lista2.append(input('Elemento {}: '.format(i)))
print('A união das listas: {}'.format(lista1 + lista2))
for i, x in zip(lista1, lista2):
lista_intercalada.append(i)
lista_intercalada.append(x)
print('Lista intercalada: {}'.format(lista_intercalada))
|
c35b4f4a265ac6fb6351f8900a4d988b34f761cf | boaass/KKB | /PrerequesiteTest/Spiral Memory/main.py | 1,387 | 4.25 | 4 | # -*-coding:utf-8 -*-
# You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the
# grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward.
# For example, the first few squares are allocated like this:
# 17 16 15 14 13
# 18 5 4 3 12
# 19 6 1 2 11
# 20 7 8 9 10
# 21 22 23 ---> ...
# While this is very space-efficient (no squares are skipped), requested data must be carried back to
# square 1 (the location of the only access port for this memory system) by programs that can only move up, down,
# left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and
# square 1.
# For example:
# Data from square 1 is carried 0 steps, since it's at the access port.
# Data from square 12 is carried 3 steps, such as: down, left, left.
# Data from square 23 is carried only 2 steps: up twice.
# Data from square 1024 must be carried 31 steps.
# How many steps are required to carry the data from the square identified in
# your puzzle input all the way to the access port?
# How to test your answer:
# If you input: 100000 Your Answer should be: 173
# If you input: 2345678 Your Answer shouldbe: 1347
def countSteps(num):
if __name__ == '__main__':
countSteps(100000) # 173
countSteps(2345678) # 1347 |
253506493ba7aaa3c96220575f6bba56cc953eb8 | ccruz182/Python | /classes/computed_attr.py | 943 | 3.578125 | 4 | class Color():
def __init__(self):
self.red = 50
self.green = 75
self.blue = 100
def __getattr__(self, attr):
if attr == "rgbcolor":
return (self.red, self.green, self.blue)
elif attr == "hexcolor":
return "#{0:02x}{1:02x}{2:02x}".format(self.red, self.green, self.blue)
else:
raise AttributeError
def __setattr__(self, attr, val):
if attr == "rgbcolor":
self.red = val[0]
self.green = val[1]
self.blue = val[2]
else:
super().__setattr__(attr, val)
def __dir__(self):
return ("red", "green", "blue", "rgbcolor", "hexcolor")
def main():
my_color = Color()
print(my_color.rgbcolor)
print(my_color.hexcolor)
my_color.rgbcolor = (100, 200, 9)
print(my_color.hexcolor)
print(dir(my_color))
if __name__ == "__main__":
main()
|
9b2ea0618af53ecfa3681d71223c91cbe9c1c97a | gangtaehwan/wikidocs-chobo-python | /ch03/simpleInterest.py | 437 | 3.625 | 4 | def simple_interest(p, r, t):
return int(p * r * t)
def simple_interest_amount(p, r, t):
return int(p * (1 + r * t))
if __name__ == '__main__':
# Quiz 1
# ex 1
print(simple_interest(10000000, 0.03875, 5))
# ex 2
print(simple_interest(1100000, 0.05, 5/12))
# Quiz 2
# ex 1
print(simple_interest_amount(10000000, 0.03875, 5))
# ex 2
print(simple_interest_amount(1100000, 0.05, 5/12))
|
0a09ae29470df5e0c78fa527c1a21d894bf6b8b7 | AFRothwell/Initial-Commit | /AdventOfCode/Day 2 Part 1.py | 2,121 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 1 16:02:59 2021
@author: Andrew Rothwell
"""
'''
--- Day 2: Password Philosophy ---
Your flight departs in a few days from the coastal airport; the easiest way
down to the coast from here is via toboggan.
The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day.
"Something's wrong with our computers; we can't log in!" You ask if you can
take a look.
Their password database seems to be a little corrupted: some of the passwords
wouldn't have been allowed by the Official Toboggan Corporate Policy that was
in effect when they were chosen.
To try to debug the problem, they have created a list (your puzzle input) of
passwords (according to the corrupted database) and the corporate policy when
that password was set.
For example, suppose you have the following list:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
Each line gives the password policy and then the password. The password policy
indicates the lowest and highest number of times a given letter must appear
for the password to be valid. For example, 1-3 a means that the password must
contain a at least 1 time and at most 3 times.
In the above example, 2 passwords are valid. The middle password, cdefg, is
not; it contains no instances of b, but needs at least 1. The first and third
passwords are valid: they contain one a or nine c, both within the limits of
their respective policies.
How many passwords are valid according to their policies?
'''
list = [str(x) for x in open("day 2 input.txt", "r").readlines()]
invalid_passwords = []
valid_passwords = []
for i in list:
policy = (i.split(": ")[0])
password1 = (i.split(": ")[1])
password = password1.splitlines()[0]
policy_range = policy.split(" ")[0]
policy_character = policy.split(" ")[1]
range_lower = int(policy_range.split("-")[0])
range_upper = int(policy_range.split("-")[1])
count = password.count(policy_character)
if count not in range(range_lower,range_upper + 1):
invalid_passwords.append(i)
else:
valid_passwords.append(i)
print(len(valid_passwords)) |
61dd764e56119cf38a9bcd22d442bd960a6b4530 | travismyers19/Vulnerable_Buildings | /get_soft_story_images.py | 2,357 | 3.671875 | 4 | # This script takes addresses from a csv file and gets the
# associated street view image and places it in the specified folder.
# the image is saved as "row.jpg", where row is the row number
# from the csv file.
from Modules.addresses import Addresses
from Modules.imagefunctions import write_image_to_file
import os
import argparse
def get_soft_story_images(image_folder, csv_filename, address_column, start_index, end_index, api_key_filename)
addresses = Addresses(api_key_filename)
addresses.read_addresses_from_csv(csv_filename, address_column=address_column)
for address_index in range(start_index, end_index):
image = addresses.get_image(address_index)
if image is None:
continue
write_image_to_file(image, os.path.join(image_folder, str(address_indeximage) + '.jpg'))
if __name__ == '__main__':
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
parser.add_argument(
"--api_key_filename", type=str, default='api-key.txt',
help = "The file location of a text file containing a Google API Key. Default is 'api-key.txt'.")
parser.add_argument(
"--image_folder", type=str, default='Data',
help = "The directory in which to save the labeled images. Default is 'Data")
parser.add_argument(
"--addresses_filename", type=str, default='Addresses/Soft-Story-Properties.csv',
help = "The file location of the csv file containing the addresses. Default is 'Addresses/Soft-Story-Properties.csv")
parser.add_argument(
"--address_column", type=int, default=4,
help = "The column in the csv file which corresponds to the addresses. Default is 4.")
parser.add_argument(
"--start_row", type=int, default=0,
help = "The row of the csv file to start at. Default is 0.")
parser.add_argument(
"--end_row", type=int, default=5000,
help = "The row of the csv file to end at. Default is 5000.")
flags = parser.parse_args()
api_key_filename = flags.api_key_filename
image_folder = flags.image_folder
csv_filename = flags.addresses_filename
address_column = flags.address_column
start_index = flags.start_row
end_index = flags.end_row
get_soft_story_images(image_folder, csv_filename, address_column, start_index, end_index, api_key_filename) |
e4219830969b332f808a1d22011db7dc9fefe644 | bossjoker1/algorithm | /pythonAlgorithm/Practice/2181合并零之间的节点.py | 855 | 3.671875 | 4 | # 我的解法,还行
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp, pre = head.next, head.next
while temp:
if temp.val == 0:
pre.next = temp.next
pre = temp.next
else:
if temp.next:
pre.val += temp.next.val
temp = temp.next
return head.next
# dl的原地修改,nb!
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
ans, temp = head, head.next
s = 0
while temp:
if temp.val != 0:
s += temp.val
else:
ans.next.val = s
ans = ans.next
s = 0
temp = temp.next
ans.next = None
return head.next |
0cd764409147e88bdc7202270f34c031b7ecf61b | madisonhoover4/cs1301 | /lab2.py | 7,436 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Georgia Institute of Technology - CS1301
Lab2 - API and Requests module - due Thursday, Mar. 30, 2017
"""
import requests
import time
from collections import Counter
__author__ = "MADISON HOOVER"
__collaboration__ = """ I worked on this assignment alone using only this semester's course materials. """
"""
Get an account from themoviedb.org. Go to this link and create an account: https://www.themoviedb.org/?_dc=1489731496
assign your API key to the variable below
"""
API_KEY = "852a00b89a5132fece98911b4c1a1fcf"
base_url = "https://api.themoviedb.org/3/movie/"
"""
Function name: getMovieTitle
Parameters: an int representing the ID of a movie
Returns: a string representing the original title of the movie
Description: Write a function that takes in the ID of a movie, makes an API call, and returns the <str> original title of the movie related to the ID passed in.
"""
def getMovieTitle(movieId):
fullURL = base_url + str(movieId) + "?api_key=" + API_KEY
r = requests.get(fullURL)
movieinfo = r.json()
try:
name = movieinfo['original_title']
return name
except:
return None
# DONE2
"""
Function name: getTopTenMovies
Parameters: **No parameters**
Returns: a list containing the original titles of the top ten rated movies
Description: Write a function that makes an API call, and returns the <str> original title of the top ten rated movies.
"""
def getTopTenMovies():
fullURL = base_url + "top_rated" + "?api_key=" + API_KEY
r = requests.get(fullURL)
toprated = r.json()
print(toprated)
list1 = []
for num in range(0,9):
list1.append(str(toprated['results'][num]['original_title']))
return list1
# DONE2
"""
Function name: getTopMoviesInRange
Parameters: an int representing the startYear (inclusive) of the range, an int representing the endYear (exclusive) of the range
Returns: a list containing the original titles of the top three rated movies that were released between the two years passed in.
Description: Write a function that takes in a two ints representing the start (inclusive) and the end (exclusive) of a period of time, and returns the top three rated movies that were released within the period of time specified by the parameters.
To get the top rated movies, make an API call similar to the one you did for getTopTenMovies. Then, you should go through the movies, and append the first three movies that have a releasedDate between the specified time period.
Notes:
Since the movie API has tons of movies in their Database, they have an optional parameter called page for their GetTopRated endpoint. If you make the API call without specifying a value for the page parameter, it will be 1 by default, giving you the first couple of top rated movies.
The movies are splitted into different "pages" (basically, into different JSONs) because having all the movies in a single endpoint would return a really heavy JSON.
For this function, the problem you could face is that probably the top three movies that were released in a specific time range won't be in the first page.
Hence, after you iterate through all the movies in the json returned by the endpoint with page 1, if you haven't found the top three movies, you will have to make an API call to get the top rated movies in page 2, and iterate through those movies.
It is also probable that the top three movies in the specified time period aren't in the second page, so you will have to make an API call to get the movies in the next page, and so on until you find them.
The iteration and the API calls to the next pages are given to you in the base code. Consequently, you just have to write the code to iterate through the movies for a single endpoint and append the movies that fall within the time period.
"""
# ################################ #
# TODO: Function 3: getTopMoviesInRange #
# ################################ #
def getTopMoviesInRange(startYear, endYear):
parameters = {"api_key": API_KEY}
topRatedUrl = "top_rated"
response = requests.get(base_url + topRatedUrl, params=parameters)
jsonData = response.json()
jsonMovieList = jsonData["results"]
topList = []
page = 1
while len(topList) < 3 and page < jsonData["total_pages"]:
'''TODO: Complete the function to find the top three rated movies in the time range specified by the parameters
'''
for movie in jsonMovieList:
a = movie['release_date']
year = a.split('-')[0]
year = int(year)
if year in range(startYear, endYear) and len(topList)<3:
topList.append(movie['original_title'])
page += 1
parameters["page"] = page
response = requests.get(base_url + topRatedUrl, params=parameters)
jsonData = response.json()
jsonMovieList = jsonData["results"]
time.sleep(0.3)
return topList
# DONE2
"""
Function name: getMoviesByGenre
Parameters: a list of movie Ids <ints>, and a genre <str>
Returns: a list containing the original title <str> of the movies passed in that belong to this genre
Description: Write a function that takes in a list of movie Ids and a genre. Make API calls to get information of each movie in the list by using its Id, and append the original title of the movie it belongs to the genre passed in.
"""
# ########################## #
# TODO: Function 4: getMoviesByGenre #
# ########################## #
def getMoviesByGenre(movieIdList, genre):
newlist = []
for name in movieIdList:
fullURL = base_url + str(name) + "?api_key=" + API_KEY
r = requests.get(fullURL)
movieinfo = r.json()
for dict in movieinfo['genres']:
if dict['name'] == genre:
newlist.append(str(movieinfo['original_title']))
return newlist
# DONE2
# should I add try except for these too?
"""
Function name: mapProductionCompaniesToMovies
Parameters: a list of movie Ids <ints>, and a list of production companies <strings>
Returns: a dictionary {keys are strings: values are lists of strings }
Description: Write a function that takes in a list of movie Ids and a list of production companies. Each movie has a list companies that were involved in their production. Your task is to create a dictionary were the keys are the production companies in the list passed in, and the values are lists containing the original titles of the movies that were produced by the corresponding company./
"""
# ############################ #
# TODO: Function 5: mapProductionCompaniesToMovies #
# ############################ #
def mapProductionCompaniesToMovies(movieIdList, companyList):
finaldict = {}
for company in companyList:
movielist = []
for movieId in movieIdList:
fullURL = base_url + str(movieId) + "?api_key=" + API_KEY
r = requests.get(fullURL)
movieinfo = r.json()
companylist = movieinfo['production_companies']
for num in range(0,len(companylist)):
if companylist[num]['name'] == company:
movielist.append(movieinfo['original_title'])
finaldict[str(company)] = movielist
return finaldict
# DONE2
#should I add try except for this too?
|
76e13b5ceaea6b9712b606579080561031567b10 | adamgiesinger/face_recognition | /recognize_single_image.py | 2,892 | 3.859375 | 4 | import face_recognition
from PIL import Image, ImageDraw, ImageFont
import os
import sys
# This is an example of running face recognition on a single image
# and drawing a box around each person that was identified.
# i.e. python .\recognise.py knownPeople/
pathToKnownPeopleImages = sys.argv[1] # known persons
outputFolderPath = sys.argv[2] # path where the processed image will be saved
inputImagePath = sys.argv[3] # input image with persons on it
print("Command line argument is " + inputImagePath)
# Create arrays of known face encodings and their names
known_face_encodings = []
known_face_names = []
for filename in os.listdir(pathToKnownPeopleImages):
image = face_recognition.load_image_file(pathToKnownPeopleImages + filename)
face_encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(face_encoding)
file_name = os.path.splitext(filename)[0]
known_face_names.append(file_name)
# Load an image with an unknown face
unknown_image = face_recognition.load_image_file(inputImagePath)
# Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
# Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
# See http://pillow.readthedocs.io/ for more about PIL/Pillow
pil_image = Image.fromarray(unknown_image)
# Create a Pillow ImageDraw Draw instance to draw with
draw = ImageDraw.Draw(pil_image)
# Loop through each face found in the unknown image
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
font_type = ImageFont.truetype("arial.ttf", 40)
# If a match was found in known_face_encodings, just use the first one.
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
# Draw a box around the face using the Pillow module
draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))
# Draw a label with a name below the face
text_width, text_height = draw.textsize(name, font=font_type)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))
draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255), font=font_type)
# Remove the drawing library from memory as per the Pillow docs
del draw
# Display the resulting image
# pil_image.show()
# You can also save a copy of the new image to disk if you want by uncommenting this line
base=os.path.basename(inputImagePath)
print(base)
pil_image.save(outputFolderPath + base)
# os.path.splitext(imageFileName)[0]
|
64c47a7c534c4b9c19a05c95c0f35157f4eb039c | mindful-ai/18012021PYLVC | /day_02/transcripts/tr_loops.py | 4,054 | 3.890625 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> s = "python"
>>> for c in s:
print("Oracle")
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
>>> for c in s:
print(s + " ----> " + "Oracle")
python ----> Oracle
python ----> Oracle
python ----> Oracle
python ----> Oracle
python ----> Oracle
python ----> Oracle
>>> for c in s:
print(c + " ----> " + "Oracle")
p ----> Oracle
y ----> Oracle
t ----> Oracle
h ----> Oracle
o ----> Oracle
n ----> Oracle
>>>
>>> for item in ["red", "green", "blue"]:
print(item, ' ', len(item))
red 3
green 5
blue 4
>>> for item in ("red", "green", "blue"):
print(item, ' ', len(item))
red 3
green 5
blue 4
>>>
>>> D = {"name":'Anil', "age":35, "company": "Oracle" }
>>> D
{'name': 'Anil', 'age': 35, 'company': 'Oracle'}
>>> for i in D:
print(i)
name
age
company
>>> for i in D.keys():
print(i)
name
age
company
>>> for i in D.values():
print(i)
Anil
35
Oracle
>>> for i in D.keys():
print(i + ' ------> ' + str(D[i]))
name ------> Anil
age ------> 35
company ------> Oracle
>>>
>>> for i in D.keys():
print(i , ' ------> ' , D[i])
name ------> Anil
age ------> 35
company ------> Oracle
>>> for i in D.keys():
print(i + ' ------> ' + D[i])
name ------> Anil
Traceback (most recent call last):
File "<pyshell#34>", line 2, in <module>
print(i + ' ------> ' + D[i])
TypeError: can only concatenate str (not "int") to str
>>>
>>> for item in D.items():
print(item)
('name', 'Anil')
('age', 35)
('company', 'Oracle')
>>>
>>> for key, value in D.items():
print(key, value)
name Anil
age 35
company Oracle
>>>
>>> D1 = {}
>>> for key, value in D.items():
D1.setdefault(value, key)
'name'
'age'
'company'
>>> D1
{'Anil': 'name', 35: 'age', 'Oracle': 'company'}
>>>
>>> for s in set("mississippi"):
print(s)
i
p
m
s
>>>
>>> # ----------------------------------------
>>>
>>> N = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> for n in N:
print(5, ' X ', n, ' = ', 5 * n)
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
>>>
>>>
>>>
>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(30, 40))
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
>>> list(range(10, 100, 2))
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
>>> list(range(100, 90, -1))
[100, 99, 98, 97, 96, 95, 94, 93, 92, 91]
>>> for n in range(11):
print(5, ' X ', n, ' = ', 5 * n)
5 X 0 = 0
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
>>> for n in range(1,11):
print(5, ' X ', n, ' = ', 5 * n)
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
>>>
>>>
>>>
>>>
>>> i = 1
>>> while i <= 10:
print(5, ' X ', i, ' = ', 5 * i)
i += 1
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
>>>
>>>
>>> # ----------------------------- Loop controls
>>>
>>>
>>> for c in "computer":
print(c, end=' ')
c o m p u t e r
>>> for c in "computer":
print(c, end='|')
c|o|m|p|u|t|e|r|
>>>
>>>
>>> ['u', 'i', 'x']
['u', 'i', 'x']
>>>
>>> for c in "computer":
if c in ['u', 'i', 'x']:
break
print(c, end='|')
c|o|m|p|
>>> for c in "computer":
if c in ['u', 'i', 'x']:
continue
print(c, end='|')
c|o|m|p|t|e|r|
>>>
|
3b502aefb3fbc20bdf29e0ae1240f2da5cb048dc | Lightman-EL/Python-by-Example---Nikola-Lacey | /N6_While_Loop/045.py | 128 | 4.0625 | 4 | total = 0
while total <= 50:
number = int(input("Input a number: \n"))
total += number
print("The total is ", total) |
f0c78f03dac86220cf439f55e87adbc3851b959e | rafaelperazzo/programacao-web | /moodledata/vpl_data/94/usersdata/250/55602/submittedfiles/mediaLista.py | 188 | 3.671875 | 4 | # -*- coding: utf-8 -*-
n=int(input('tamanho da lista:'))
a=[]
soma=0
for i in range (0,n,1):
a.append(int(input('valores da lista:')))
soma=soma+a[i]
media=soma/(len(lista))
|
67a0b069e1bfb8aebf90b0a79672a0bb4ab95bec | Udayan92/MyCodes | /hw2.py | 4,033 | 4 | 4 | # Name:
# Section:
# hw2.py
##### Template for Homework 2, exercises 2.0 - 2.5 ######
# ********** Exercise 2.0 **********
def f1(x):
print x + 1
def f2(x):
return x + 1
# ********** Exercise 2.1 **********
def outcome(player1, player2):
if player1 == 'rock' and player2 == 'rock':
print "TIE"
elif player1 == 'rock' and player2 == 'paper':
print "paper beats rock.player2 wins"
elif player1 == 'rock' and player2 == 'scissors':
print "rock beats scissors.player1 wins."
elif player1 == 'paper' and player2 == 'paper':
print "TIE"
elif player1 == 'paper' and player2 == 'rock':
print "paper beats rock.player1 wins."
elif player1 == 'paper' and player2 == 'scissors':
print "scissors cut paper.player2 wins."
elif player1 == 'scissors' and player2 == 'scissors':
print "TIE"
elif player1 == 'scissors' and player2 == 'rock':
print "rock beats scissors.player2 wins."
elif player1 == 'scissors' and player2 == 'paper':
print "scissors cut paper.player2 wins."
else:
print "Invalid choice."
##### YOUR CODE HERE #####
print "Welcome to rock,paper,scissors game."
print "What do you select,player1?rock,paper or scissors?"
player1 = raw_input()
print "And what do you select,player2?rock paper or scissors?"
player2 = raw_input()
outcome(player1, player2)
# Test Cases for Exercise 2.1
outcome('rock', 'rock')
outcome('rock', 'paper')
outcome('scissors', 'paper')
outcome('abc', 'xyz')
# ********** Exercise 2.2 **********
# Define is_divisible function here
def is_divisible(m, n):
if m % n == 0:
return True
else:
return False
# Test cases for is_divisible
## Provided for you... uncomment when you're done defining your function
print is_divisible(10, 5) # This should return True
print is_divisible(18, 7) # This should return False
#print is_divisible(42, 0) # What should this return?
# Define not_equal function here
def not_equal(a, b):
if a - b == 0:
return True
else:
return False
# Test cases for not_equal
not_equal(3, 3)
not_equal(4, 5)
# ********** Exercise 2.3 **********
## 1 - multadd function
def multadd(a, b, c):
return (a*b) + c
## 2 - Equations
##### YOUR CODE HERE #####
import math
return math.sin(pi/4) + (cos(pi/4))/2
return math.ceil(276/19) + 2 * math.log(12, 7)
# Test Cases
# angle_test =
# print "sin(pi/4) + cos(pi/4)/2 is:"
# print angle_test
# ceiling_test =
# print "ceiling(276/19) + 2 log_7(12) is:"
# print ceiling_test
## 3 - yikes function
##### YOUR CODE HERE #####
def yikes(x):
import math
return x*(math.e)**(-x) +(1 - (math.e)**(-x))**0.5
# Test Cases
# x = 5
# print "yikes(5) =", yikes(x)
# ********** Exercise 2.4 **********
## 1 - rand_divis_3 function
##### YOUR CODE HERE #####
def rand_divis_3():
import math
import random
x = random.randint(0, 100)
if x % 3 == 0:
return True
else:
return False
# Test Cases
##### YOUR CODE HERE #####
## 2 - roll_dice function - remember that a die's lowest number is 1;
#its highest is the number of sides it has
##### YOUR CODE HERE #####
def roll_dice(s, n):
import random
while (n!=0):
print random.randint(1, s)
n = n-1
print "Thats all folks!!"
# Test Cases
roll_dice(6,3)
roll_dice(10, 100)
roll_dice(5, 3)
##### YOUR CODE HERE #####
# ********** Exercise 2.5 **********
# code for roots function
def roots(a, b, c):
import math
d = b**2 - 4*a*c
if d<0:
print "The roots are complex.Cannot proceed further."
exit()
else
r1 = (-b + d**0.5)/(2*a)
r2 = (-b - d**0.5)/(2*a)
print "The roots of the equation are %r and %r" %(r1, r2)
# Test Cases
##### YOUR CODE HERE #####
|
d6a67a96ac198bddc2c634be05585b785c478f17 | math77/Algorithms | /alg12.py | 197 | 4.21875 | 4 | temp_fahrenheit = float(input("Digite uma temperatura em Fahrenheit\n"))
temp_celsius = ((temp_fahrenheit-32)*5)/9
print("A temperatura {}F é igual a {}ºC".format(temp_fahrenheit, temp_celsius))
|
72c1c97e234fd9f3ccde990bb06f225a6841409a | b1ueskydragon/PythonGround | /leetcode/p0205/isomorphic_strings_test.py | 695 | 3.515625 | 4 | import unittest
from .isomorphic_strings import Solution as A
class IsomorphicStringsTest(unittest.TestCase):
def test_true(self):
a = A()
self.assertTrue(a.isIsomorphic("egg", "add"))
self.assertTrue(a.isIsomorphic("paper", "title"))
self.assertTrue(a.isIsomorphic("egggggga", "addddddc"))
self.assertTrue(a.isIsomorphic("", ""))
self.assertTrue(a.isIsomorphic("x", "y"))
self.assertTrue(a.isIsomorphic("aaabbb", "bbbaaa"))
def test_false(self):
a = A()
self.assertFalse(a.isIsomorphic("gge", "add"))
self.assertFalse(a.isIsomorphic("foo", "bar"))
self.assertFalse(a.isIsomorphic("bar", "foo"))
|
1a1ee020e0be358ff99cee82739868a0333393c2 | DanielBrito/ufc | /Monitoria - Fundamentos de Programação/Lista 4 - Ítalo/18_potencia.py | 451 | 3.921875 | 4 | # Questão 18 - Lista 4 (Ítalo)
def potencia(x, n):
if x==0 or x==1 or n==1:
return x
if n==0:
return 1
if n<0:
return 1/potencia(x,-n)
val = potencia(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
base = int(input("Digite a base: "))
expoente = int(input("Digite o expoente: "))
print("\nResultado =", potencia(base, expoente))
|
6b28d8019957b930b545ce7d6c99012d529704f9 | MelodyChu/Juni-Python-Practice | /replit_practice2.py | 3,608 | 4.1875 | 4 | """a = int(input()) # 1234
b = a % 10 # =4
c = ((a - b)/10) % 10 # 1230/10 = 123; 123/10 % = 3
print (c*10 + b) """
"""# Find tens digit
a = int(input())
b = a % 10 #single digit
c = ((a - b)/10) % 10 #1230
print (c) """
"""
# Given 3 digit number find sum of digits
a = int(input()) # 123
b = a % 10 # single digit # 3
c = ((a - b)/10) % 10 # tens digit #2
d = (a - c*10 - b)/100 # 123 - 20 - 3 / 100
print (b + c + d) """
"""
# given float, print number to right of decimal
a = float(input()) #1.79
b = 10 * a #17.9
c = int(b) % 10
print (c)
"""
"""
# create function such that kilometers / route length = number of days
n = int(input()) #4
m = int(input()) # 8
print (int(m/n) + 1)
700
"""
"""
a = int(input()) #20
b = int(input()) #21
c = int(input()) #22
num_desksa = int(a / 2) + (a % 2)
num_desksb = int(b / 2) + (b % 2)
num_desksc = int(c / 2) + (c % 2)
print (num_desksa + num_desksb + num_desksc)
"""
# Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
"""
a = int(input())
b = int(input())
c = int(input())
if a == b and a == c:
print ('3')
elif a == b or a == c:
print ('2')
else:
print ('0')
"""
"""
# chessboard question: can only move horizontally & vertically; needs to be able to do it in one step
xaxis = int(input()) # 1-8
yaxis = int(input()) # 1-8
newx = int(input())
newy = int(input())
if xaxis == newx and abs(newy - yaxis) == 1:
print ("YES")
elif yaxis == newy and abs(newx - xaxis) == 1: #if y coordinate says same moves horizontally
print ("YES")
elif xaxis == newx and yaxis == newy: # if chess piece doesn't move
print ("YES")
else:
print ("NO")
"""
"""
a = int(input())
b = int(input())
for i in range(a,b+1):
print (i)
"""
"""
N = int(input())
result = 0
for i in range(1,N+1):
result += i ** 3
print (result)
"""
"""
a = int(input())
result = 1
for i in range(1,a+1):
result *= i
print (result)
"""
"""
to revisit:
alist = [5,0,700,0,200,2]
result = 0
for i in alist:
for j in alist:
if i + j == 0:
result += 1
print (result)
"""
"""
a = int(input()) # 3
result = 0
factorial = 1
for i in range(1,a+1):
factorial *= i # store the factorial before it
result += factorial # we want 1 + (2*1) + (3*2*1)
print (result)
"""
"""
# why is it printing 64 when I input 50?
N = int(input())
i = 0
while i ** 2 < N:
i += 1
print (i ** 2)
"""
"""
a = int(input()) # not less than 2
i = 2
while i > 1:
i += 1
if a % i == 0:
print (i)
break
"""
"""
x = int(input())
n = 0
while 2 ** n <= x:
n += 1
print (n, 2 ** n)
"""
"""
# need to check this
miles1 = int(input())
miles2 = int(input())
totalmiles = miles1
d = 0
while totalmiles <= miles2:
totalmiles *= 1.1
d += 1
print (d)
"""
"""
# 6.5: for loop here gives me 4;
a = [1,7,9,0,5]
result = 0
for i in a:
if i != 0:
result += 1
print (result)
# while loop
"""
"""
a = [1,7,9,0,5]
result = 0
i =
while i != 0 in a: # while i not equal in 0 in the list..
result += 1
print (result)
"""
"""
x = int(input())
n = 0
while 2 ** n <= x:
n += 1
print (n-1, 2 ** (n-1))
# or
n = 0
while True:
if 2** <= x:
n+=1
else:
break
"""
"""
miles1 = int(input())
miles2 = int(input())
totalmiles = miles1
d = 0
while totalmiles <= miles2:
totalmiles *= 1.1
d += 1
print (d)
"""
result = 0
while True:
a = int(input())
if a > result:
result = a
elif a == 0:
break
print (result)
|
3c639b552af6c69051dd973d6e47dcb8970d1ea7 | tab1tha/Beginning | /subclassList.py | 642 | 4.0625 | 4 | #in this program,a subclass is created which inherits the attributes of the built in class;list.
class Counterlist(list):
def __init__(self,*args):
super().__init__(*args)#the super function is used to initialise the superclass(es)
self.counter=0
def __getitem__(self, index):
self.counter += 1
return super(CounterList, self).__getitem__(index)
cl=Counterlist(range(10))
print(cl)
cl.counter #this value starts from zero and increments itself whenever a value in the list is accessed.e.g.
#after performing a calculation such as cl[4]+cl[5],cl.counter=2 since the list was accessed twice.
|
3ce1ae8fb2c61f03ff5cc9f91a711f3314ae6c26 | YutaGoto/daily_atcoder | /2021-01/abc153_d.py | 162 | 3.578125 | 4 | n = int(input())
c = 0
base = 1
while True:
c += base
if n == 1:
print(c)
exit()
else:
n = n // 2 + n % 2
base *= 2
|
868617839ea8bb08b64021b760d3411c1910ac5f | lilbond/bitis | /day3/abstract.py | 329 | 3.9375 | 4 |
import abc
class ABCClass(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def __str__(self):
raise NotImplementedError('users must define __str__ to use this base class')
class MyAbstractClass(ABCClass):
pass
# def __str__(self):
# return 'here i am!'
a = MyAbstractClass()
print(a)
|
c9f4f26c7af0e2935a332fa942b4b56af4d6bdc7 | jiacovacci/py_exam | /dict.py | 145 | 4.1875 | 4 | #!/usr/bin/python3
# DATA TYPE Examples
print('dictionary example')
x = {"name" : "John", "email" : "[email protected]"}
print (x['name'])
print(type(x))
|
86455b3dfe936a558be2016f80b70268321327de | brysonpayne/teachkids | /ch03/Challenge2_ColorMeSpiralled.py | 1,045 | 4.59375 | 5 | # ColorMeSpiralled.py
import turtle # set up turtle graphics
t=turtle.Pen()
turtle.bgcolor('black')
# Set up a list of any 10 valid Python color names
colors=['red', 'yellow', 'blue', 'green', 'orange',
'purple', 'white', 'gray', 'brown', 'sea green']
# ask the user's name using turtle's textinput popup window
your_name = turtle.textinput("Enter your name", "What is your name?")
# ask the number of sides
sides = int(turtle.numinput("Number of sides",
"How many sides do you want (1-10)?", 5, 1, 10))
# draw a spiral of the name on the screen, written 100 times
for x in range(100):
t.pencolor(colors[x%sides%10]) # rotate through the 10 colors
t.penup() # don't draw the regular spiral lines
t.forward(x*4) # just move the turtle on the screen
t.pendown() # now, write the user's name, bigger each time
t.write(your_name, font=("Arial", int( (x*2 + 4) / 4), "bold") )
t.left(360/sides+2) # turn left 360/sides+2 degrees for sides
|
05c564510bfdd0152f7d02fb01bef29dfb87b644 | MalahovMV/Neuron_network | /BP/main.py | 545 | 3.671875 | 4 | from Neuron import neuron
def main(rate_learn):
rate_learn = rate_learn
e = 0.00001
y_true = 0.3
input_x = [1, 2]
network = neuron(rate_learn, y_true, input_x)
while True:
network.calculate_values()
network.calculate_error()
print("Epoch= %2d" % network.epoch, " y=%7F" % network.y_calculate, ' Error=', network.result_error)
if abs(network.result_error) < e: break
network.change_weights()
#print(network.y_calculate, network.epoch)
if __name__ == '__main__':
main(1) |
513c99ec2c59aec595e6e62e1361f2d5483f06a5 | sebastianlettner/tf-graph-tool | /tf_graph_tool/components/recurrent/binary_lstm/binary_stochastic_neuron/bsn_stochastic_model.py | 2,459 | 3.703125 | 4 | """ The stochastic model of the neuron. """
import tensorflow as tf
from tensorflow.python.framework import ops
import bsn_literals
class BsnStochasticModel(object):
"""
The BsnStochasticModel class provides tensors for sampling the preprocessed input ranging
from (0, 1) to either 0 or 1.
THere is also a round operation provided which is of course not stochastic.
"""
@classmethod
def produce(cls, x, tf_graph, method=bsn_literals.BERNOULLI):
"""
Args:
x(tensor): Preprocessed input of the neuron.
method(str): Method used for the mapping.
Returns:
x_discrete(tensor): Tensor which will evaluate to either 0 or 1.
"""
if method == bsn_literals.BERNOULLI:
return BsnStochasticModel.bernoulli(x, tf_graph)
elif method == bsn_literals.ROUND:
return BsnStochasticModel.round(x, tf_graph)
else:
raise ValueError("Unrecognized method for stochastic sampling: " + method)
@classmethod
def bernoulli(cls, x, graph):
"""
Uses a tensor whose values are in (0,1) to sample a tensor with values in {0, 1}.
E.g.:
if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise,
and the gradient will be pass-through (identity).
Args:
x(tensor): The tensor we want to round
Returns:
x_sampled(tensor): Mapped tensor.
"""
with ops.name_scope("BernoulliSample") as name:
with graph.gradient_override_map({"Ceil": "Identity", "Sub": "BernoulliSample_ST"}):
return tf.ceil(x - tf.random_uniform(tf.shape(x)), name=name)
@classmethod
def round(cls, x, graph):
"""
Rounds a tensor whose values are in (0,1) to a tensor with values in {0, 1},
using the straight through estimator for the gradient.
Args:
x(tensor): The tensor we want to round
Returns:
x_rounded(tensor): Rounded tensor.
NOTE: Not a stochastic operation. Just for the purpose of experimenting.
"""
with ops.name_scope("BinaryRound") as name:
with graph.gradient_override_map({"Round": "Identity"}):
return tf.round(x, name=name)
@ops.RegisterGradient("BernoulliSample_ST")
def bernoulli_sample_st(op, grad):
return [grad, tf.zeros(tf.shape(op.inputs[1]))]
|
3daf5fb969c1a3bcc401545fd18189004130ba02 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4464/codes/1734_2503.py | 206 | 3.609375 | 4 | from math import *
n = int(input("Fale a quantidades de termos da serie, macho: "))
soma = 4/1
cont = 1
while (cont < n):
soma = soma + (-1)**cont * (4/(cont*2+1))
cont = cont + 1
print(round(soma,8)) |
a9915a6586403bb57f670c76ae55fdacc69e0786 | functioncall/rescue-habit | /core/node/node.py | 1,112 | 4.15625 | 4 | class Node(object):
"""
A node instance contains a list of: next and previous nodes.
The basic unit of a Graph data structure.
"""
def __init__(self, name, data, nxt, pre):
"""
:param name: <str>
:param data: <object>
:param nxt: <list>
:param pre: <list>
"""
self.name = name
self.data = data
self.nxt = nxt
self.pre = pre
def addNext(self, nxt):
"""
:param nxt: new route to be added next to this node
:return: this instance
"""
self.nxt.append(nxt)
return self
def addPre(self, pre):
"""
:param pre: new route to be added previous to this node
:return: self
"""
self.nxt.append(pre)
return self
def getCurrent(self):
"""
:return: name of the current node
"""
return self.name
def getNext(self, fn):
"""
:param fn: sorter function which accepts a list as an argument
:return: one item from the list
"""
return fn(self.nxt) |
f62f534fe5c6a985d1b422419319683196353f5d | karanj1994/trafficDataAnalysis | /notebooks/trafficDataScrape.py | 4,069 | 3.703125 | 4 |
# https://www.dataquest.io/blog/web-scraping-tutorial-python/ - reference for Beautiful Soup Training
import requests # Gets the HTML from a webpage
from bs4 import BeautifulSoup # Used to parse HTML
import csv
highwayRankingWebpage = requests.get("https://reason.org/policy-study/24th-annual-highway-report/24th-annual-highway-report-executive-summary/")
extractMainWebPage = BeautifulSoup(highwayRankingWebpage.content, 'html.parser')
allStateCategories = extractMainWebPage.find_all('span', class_='highway-report-state-ranks--category-title')
allCategoryLinks = list(allStateCategories)
# list(allStateCategories)[1].find_all('a', href=True)
eachLink = 0
while eachLink < len(allCategoryLinks):
categoryWebpage = "https://reason.org" + str(list(allStateCategories)[eachLink].find_all('a', href=True)[0]['href'])
print("Weblink is this: " + categoryWebpage)
# print(categoryWebpage)
categorySpecificWebpage = requests.get(categoryWebpage)
extractStateWebpage = BeautifulSoup(categorySpecificWebpage.content, 'html.parser')
tableRanking = extractStateWebpage.find_all('table', class_='tablesorter')
outputData = []
if (len(list(tableRanking)[0].find_all('td')) != 153):
print("Skipping this webpage. Doesn't have the data we need.")
eachLink += 1
continue
extractHeader = list(extractStateWebpage.find_all('h5', class_='table-title'))[0].get_text()
# print(extractHeader)
allRankingsSorted = list(tableRanking)[0].find_all('td')
eachStateData = 0
while (eachStateData < len(allRankingsSorted)):
outputData.append(list(allRankingsSorted)[eachStateData].get_text())
eachStateData += 1
new_list=[]
i=0
while i<len(outputData):
new_list.append(outputData[i:i+3])
i+=3
print(new_list)
with open("data/" + extractHeader + ".csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(new_list)
eachLink += 1
# print(len(allStateOverallRanksCount))
# list(allStateOverallRanks.find_all('a', href=True))[0]['href']
# eachState = 0
# while eachState < len(allStateOverallRanksCount):
# print("State being checked: " + list(allStateOverallRanks.find_all('a', href=True))[eachState].get_text())
# stateWebpage = "https://reason.org" + list(allStateOverallRanks.find_all('a', href=True))[eachState]['href']
# print("Weblink is this: " + stateWebpage)
# stateSpecificWebpage = requests.get(stateWebpage)
# extractStateWebpage = BeautifulSoup(stateSpecificWebpage.content, 'html.parser')
# stateStatsValue = extractStateWebpage.find_all('span', class_='highway-report-state-ranks--category-value')
# stateStatsTitle = extractStateWebpage.find_all('span', class_='highway-report-state-ranks--category-title')
# print(stateStatsValue[0].get_text())
# print(stateStatsTitle[0].get_text())
# eachState += 1
# print(len(list(allStateOverallRanks)[0].find_all('a', href=True)))
# firstVal = list(allStateOverallRanks)[0].find_all('a', href=True)[0]['href']
# # Append reason.org in front of every href string
# #firstVal = list(allStateOverallRanks)[0].find_all('a')[0].get_text()
# print(firstVal)
# trafficWebPage = requests.get("https://reason.org/policy-study/24th-annual-highway-report/alabama/")
# extractWebPage = BeautifulSoup(trafficWebPage.content, 'html.parser')
# allAlabamaRanks = extractWebPage.find_all('span', class_='highway-report-state-ranks--category-value')
# # print(allAlabamaRanks)
# firstVal = list(allAlabamaRanks)[0]
# print(len(list(allAlabamaRanks)))
# secondVal = list(firstVal.children)[0]
# print(secondVal)
# val1 = secondVal.get_text()
################
#page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html")
# #soup = BeautifulSoup(page.content, 'html.parser')
# # print(soup.prettify()) # Prints out the html content of webpage in clean way
# # print(list(soup.children))
# htmlBody = list(soup.children)[2]
# # print(htmlBody)
# paragraphData = list(htmlBody.children)[3]
# print(paragraphData) |
496b999de9fca738abffe346be78c739c54770a8 | nowlansavage/python-challenge | /PyPoll/main.py | 1,904 | 3.78125 | 4 | import os, csv
#initiate variables
num_votes = 0
candidates = []
unique_candidates = []
most_votes = 0
#name file path
csvpath=os.path.join('Resources','election_data.csv')
#read csv file
with open(csvpath) as datafile:
csvreader = csv.reader(datafile)
#skip header row
header = next(csvreader)
#Loop through data
for row in csvreader:
#get number of votes
num_votes +=1
#get all candidates
each_candidate = row[2]
#get list of unique candidates
if each_candidate not in candidates:
unique_candidates.append(each_candidate)
#Add candidates to voting list
candidates.append(each_candidate)
#print results to terminal
print('Election Results')
print('-------------------------')
print(f'Total Votes: {num_votes}')
print('-------------------------')
#create text file
textpath=os.path.join('analysis','analysis.txt')
#write text file
textfile = open(textpath, "a")
#print results to text file
textfile.write("Election Results\n")
textfile.write('-----------------------------\n')
textfile.write(f'Total Votes: {num_votes}\n')
textfile.write('-----------------------------\n')
#loop through unique candidates to get votes for each candidate
for candidate in unique_candidates:
#get the vote count
candidate_votes = candidates.count(candidate)
#get percentage of vote
percent_vote = "{:.3%}".format(candidate_votes / num_votes)
#print votes by candidate
print(f'{candidate}: {percent_vote} ({candidate_votes})')
textfile.write(f'{candidate}: {percent_vote} ({candidate_votes})\n')
#find the winner
if candidate_votes > most_votes:
most_votes = candidate_votes
winner = candidate
#print winner
print('-------------------------')
print(f'Winner: {winner}')
print('-------------------------')
textfile.write('-----------------------------\n')
textfile.write(f'Winner: {winner}\n')
textfile.write('-----------------------------\n') |
8e481e58fb41326850b35942b97d81dec95e5418 | tzyl/project-euler | /23.py | 649 | 3.828125 | 4 | def is_abundant(n):
"""Returns true if natural number n is abundant."""
if n < 12:
return False
factors = [1]
for x in xrange(2, int(n ** 0.5) + 1):
if n % x == 0:
if x ** 2 == n:
factors.append(x)
else:
factors.append(x)
factors.append(n / x)
return sum(factors) > n
abundant_numbers = [x for x in xrange(28123) if is_abundant(x)]
sum_of_two_abundant = set([x + y for x in abundant_numbers
for y in abundant_numbers if x + y < 28123])
print sum(filter(lambda x: x not in sum_of_two_abundant, xrange(28123)))
|
33b5f6d0706ac2abbf8b053f24af840ff380f064 | HuangYongBo/Messy | /learn_python/class/demo_project.py | 1,298 | 3.703125 | 4 | #!/usr/bin/env python3
#coding:utf-8
import sys,random
class Home(object):
def __init__(self,name,area,location):
self.name = name
self.area = area
self.location = location
self.furniture_count=0
self.furniture=[]
print("构造房子:%s"%(self.name))
print("房子位于:%s占地面积:%d"%(self.location,self.area))
def __del__(self):
print("房子已被拆迁")
def add_furniture(self,item):
self.furniture.append(item)
print("%s 添加家具 %s"%(self.name,item.furniture_type))
def show_furniture(self):
print("已有家具:%s"%(str(self.furniture)))
def boom(self):
for tmp in self.furniture:
tmp.kill_myself()
class Furniture(object):
__count=0
def __init__(self,new_type,new_area):
self.furniture_type = new_type
self.area = new_area
print("构造家具%s"%(self.furniture_type))
def __del__(self):
print("%s已经被销毁"%(self.furniture_type))
def kill_myself(self):
self.__del__()
def __str__(self):
pass
desk=Furniture("desk",2)
chair=Furniture("chair",2)
bed=Furniture("bed",4)
myhouse=Home("大富翁别墅",200,"北京市 朝阳区 长安街666号")
myhouse.add_furniture(desk)
myhouse.add_furniture(chair)
myhouse.add_furniture(bed)
del desk
del bed
del chair
myhouse.boom()
print(sys.getrefcount(myhouse.furniture))
|
3aa72886c3cf9e7e3cd62d610de1d137ce1a50b3 | lonelyarcher/leetcode.python3 | /BackTrack_Pruning_1307. Verbal Arithmetic Puzzle.py | 4,441 | 4.1875 | 4 | """ Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, results.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10. """
"""
First is DFS problem, it will take O(10!) * 5 * 7, TLE, if not pruning well
1. native solution: assign characters along the words and results, if sum(words) == results, then succeed, the problem is backtrack too later only at the final step.
2. better solution is vertical calculation on each digit from smallest/right to largest/left or by columns
like
SEND
+ MORE
------
MONEY
first columnL DEY, then NRE, EON SMO, __M, each column we pruning the invalid branches. It will get much faster. ~ 1000ms
When we do the DFS, key part is to assign a dictionary for { char: digit[0-9] }, by back track, we use only one dict, try unused 0 to 9, and if leading character can't be 0
Recursively, if one of assignment succeed, we return true. after recursive call one dfs, we reset the dict assignment to None. After try all possibilities, none succeeds, then we return False
for column we recursive call each assignment
after all assigned in this column i, we calculate the result[i] - word[0][i] - ..- word[n][i], buy reduce function tools on operator.sub
if the reduce result equals to zero, we return as recursive dfs call on i + 1 column until reach len(result), all columns cleared then return True at the final recursion, result is of course longer than any of word
for easy implementation:
1. we reverse the words and result, then we can naturally make i beginning with 0
2. put all leading character into a set, easy to exclude the invalid assignment zero to them
3. put carry in dfs carry arguments, because we may have carry to higher digits
"""
from typing import List
import operator
from functools import reduce
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
d = {k: None for s in words + [result] for k in s }
leading = {w[0] for w in words} | {result[0]}
rev = [result[::-1]] + [w[::-1] for w in words]
def dfs(i, carry) -> bool:
if i == len(result): return carry == 0
col = [r[i] for r in rev if i < len(r)]
used = set(d.values())
for c in set(col):
if d[c] == None:
for v in (i for i in range(c in leading, 10) if i not in used):
d[c] = v
if dfs(i, carry): return True # recursion on the same column i, for next assignment
d[c] = None # backtrack on each column like here
return False
res = reduce(operator.sub, (d[c] for c in col)) + carry
if res % 10 == 0: return dfs(i + 1, res//10) # move the recursion to next column i + 1
else: return False
return dfs(0, 0)
print(Solution().isSolvable(words = ["A","B"], result = "A")) # True
print(Solution().isSolvable(words = ["SEND","MORE"], result = "MONEY")) # True
print(Solution().isSolvable(words = ["SIX","SEVEN","SEVEN"], result = "TWENTY")) # True
print(Solution().isSolvable(words = ["THIS","IS","TOO"], result = "FUNNY")) # True
print(Solution().isSolvable(words = ["LEET","CODE"], result = "POINT")) # False |
247e4b45197456ba6468aabec1b625402319ca6e | mingming733/LCGroup | /Sen/Length_of_Last_Word.py | 856 | 3.75 | 4 | class Solution:
# @param {string} s
# @return {integer}
# def lengthOfLastWord(self, s):
# s = s.split(" ")
# print s
# for i in range(len(s) - 1, -1, -1):
# if s[i] != " " and s[i] != "":
# return len(s[i])
# return 0
def lengthOfLastWord(self, s):
length, preLength = 0, 0
for letter in s:
if letter == " ":
if length != 0:
preLength = length
length = 0
else:
pass
else:
length += 1
if length == 0: # there are multiple words
return preLength
else:
return length # there is only one word and not whitespace behind it
s = " ab abc "
i = Solution()
print i.lengthOfLastWord(s) |
fb21fdadf71c5772d2c94985f6a96248ffa9ef39 | Aasthaengg/IBMdataset | /Python_codes/p02713/s749235371.py | 211 | 3.5625 | 4 | import math
a = int(input())
lis =[]
ans = 0
for x in range(1,a+1):
for y in range(1, a+1):
lis.append(math.gcd(x,y))
for z in range(1, a+1):
for l in lis:
ans += math.gcd(z,l)
print(ans) |
0a716517744146d4dd316129612a863abf4cc072 | axlbrandonbezerra/Python | /hipotenusa.py | 544 | 3.8125 | 4 | #Autor: Axl Brandon Rodrigues
'''Calcula o comprimento da hipotenusa'''
from math import hypot
while True:
try:
co = float(input('Digite o comprimento do Cateto Oposto: '))
except ValueError:
print('Digite apenas valores numéricos!')
else:
break
while True:
try:
ca = float(input('Digite o comprimento do Cateto Adjacente: '))
except ValueError:
print('Digite apenas valores numéricos!')
else:
break
print(f'O comprimento da Hipotenusa é {hypot(co, ca):.2f}')
|
f884ae24524855140f7bb8353596a631ff5a6f3d | gp-antennas/PythonBicone | /BiconeClasses.py | 3,706 | 3.734375 | 4 | #Classes for Bicone Algorithm
import numpy as np
import random
class Individual:
def __init__(self, chromosome = None, fitness = 0.0):
self.fitness = fitness #Fitness Score of the Individual
if chromosome is None: #Genetic material for the Individual
self.chromosome = []
else:
self.chromosome = chromosome
#THESE FUNCTIONS PASS VALUES TO THE GROUP CLASS
def pass_chromosome(self):
return(self.chromosome)
def pass_fitness(self):
return self.fitness
#INITIAL GENERATION CHROMOSOME GENERATOR
def generate_chromosome(self, data):
radius_1 = random.uniform(data['min_radius'],data['max_radius'])
length_1 = random.uniform(data['min_length'], data['max_length'])
angle_1 = random.uniform(data['min_angle'], data['max_angle'])
radius_2 = random.uniform(data['min_radius'],data['max_radius'])
length_2 = random.uniform(data['min_length'], data['max_length'])
angle_2 = random.uniform(data['min_angle'], data['max_angle'])
self.chromosome = [radius_1, length_1, angle_1, radius_2, length_2, angle_2]
#This describes a generation which is an object that is an array of Individuals as defined above
class Group:
def __init__(self, individual_array = None, group_size = 0, number_of_genes = 6):
self.group_size = group_size #This is the number of individuals in a group or generation
if individual_array is None:
self.individual_array = [] #This is the array that contains arrays of chromosomes
self.number_of_genes = number_of_genes #For asymmetric bicone this is 6: r_1,l_1,a_1,r_2,l_2,a_2
#CREATE FIRST GENERATION
def generate_new_group(self,dict):
for i in range(self.group_size):
individual = Individual()
individual.generate_chromosome(dict)
self.individual_array.append(individual)
#CREATE GROUPS FOR SUBSEQUENT GENERATIONS
def add_individual(self, chromosome, fitness):
individual = Individual(chromosome = chromosome, fitness = fitness)
self.individual_array.append(individual)
self.group_size += 1
#DATA RETURNS
def return_size(self):
return self.group_size
def return_number_of_genes(self):
return(self.number_of_genes)
def return_fitness(self,individual):
return(self.individual_array[individual].pass_fitness())
def return_chromosome(self, individual):
return(self.individual_array[individual].pass_chromosome())
def print_all(self):
for i in range(self.group_size):
print(self.return_chromosome(i))
#USED IN THE MUTATION OPERATOR
def gene_mutator(self, individual, gene, data):
chromosome = self.individual_array[individual].pass_chromosome()
radius_1 = random.uniform(data['min_radius'],data['max_radius'])
length_1 = random.uniform(data['min_length'], data['max_length'])
angle_1 = random.uniform(data['min_angle'], data['max_angle'])
radius_2 = random.uniform(data['min_radius'],data['max_radius'])
length_2 = random.uniform(data['min_length'], data['max_length'])
angle_2 = random.uniform(data['min_angle'], data['max_angle'])
choice_array = [radius_1, length_1, angle_1, radius_2, length_2, angle_2]
chromosome[gene] = choice_array[gene]
return chromosome
|
359f2cc12436ff498469168080245c9be452e2bc | junekim00/ITP115 | /Assignments/ITP115_A8_Kim_June/ITP115_A8_Kim_June.py | 4,683 | 4.1875 | 4 | # June Kim
# ITP115, Fall 2019
# Assignment 7
# [email protected]
# This program allows for a game of tic-tac-toe.
import random
import TicTacToeHelper
# checking to see if spot is open or not
def isValidMove(boardList, spot):
if boardList[spot] == "x" or boardList[spot] == "o":
return False
else:
return True
# updating board to match move
def updateBoard(boardList, spot, playerLetter):
boardList[spot] = playerLetter
# extra credit pretty board
def printPrettyBoard(boardList):
for x in range(3):
for y in range(3):
number = 3 * x + y
if y != 2:
print(" " + str(boardList[number]) + " |", end="")
else:
print(" " + str(boardList[number]), end="")
print("\n", end="")
if x != 2:
print("------------")
# gameplay
def playGame():
counter = 0
xTurn = True
board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
check = TicTacToeHelper.checkForWinner(board, counter)
computer = input("Would you like to play against a computer? (y/n)").lower()
if computer != "y" and computer!= "n":
print("Invalid option!")
computer = input("Would you like to play against a computer? (y/n)").lower()
# play against computer
if computer == "y":
while check == "n":
# start game
printPrettyBoard(board)
# Player X turn
if xTurn == True:
move = int(input("Player x, pick a spot: "))
counter += 1
if isValidMove(board, move) == False:
print("Invalid move, please try again.")
move = int(input("Player x, pick a spot: "))
updateBoard(board, move, "x")
xTurn = False
check = TicTacToeHelper.checkForWinner(board, counter)
else:
move = random.randint(0,8)
counter += 1
while isValidMove(board, move) == False:
move = random.randint(0,8)
else:
updateBoard(board, move, "o")
print("Computer chose " + str(move) + ".")
xTurn = True
check = TicTacToeHelper.checkForWinner(board, counter)
if check == "s":
print("Game Over!\nStalemate reached!")
if check == "x":
print("Game Over!\nPlayer x is the winner!")
elif check == "o":
print("Game Over!\nPlayer o is the winner!")
# extra credit choose which player starts
if computer == "n":
startPlayer = input("Who would you like to start? (x/o)").lower()
while startPlayer != "x" and startPlayer != "o":
print("Invalid option! ")
startPlayer = input("Who would you like to start? (x/o)").lower()
if startPlayer == "x":
xTurn = True
elif startPlayer == "o":
xTurn = False
# actual game
while check == "n":
# start game
printPrettyBoard(board)
# Player X turn
if xTurn == True:
move = int(input("Player x, pick a spot: "))
counter += 1
if isValidMove(board, move) == False:
print("Invalid move, please try again.")
move = int(input("Player x, pick a spot: "))
updateBoard(board, move, "x")
xTurn = False
check = TicTacToeHelper.checkForWinner(board, counter)
else:
move = int(input("Player o, pick a spot: "))
counter += 1
if isValidMove(board, move) == False:
print("Invalid move, please try again.")
move = int(input("Player o, pick a spot: "))
updateBoard(board, move, "o")
xTurn = True
check = TicTacToeHelper.checkForWinner(board, counter)
if check == "s":
print("Game Over!\nStalemate reached!")
if check == "x":
print("Game Over!\nPlayer x is the winner!")
elif check == "o":
print("Game Over!\nPlayer o is the winner!")
# keep going until player wishes to stop
def main():
keepGoing = True
while keepGoing == True:
playGame()
playAgain = input("Would you like to play again? (y/n)").lower()
if playAgain == "n":
keepGoing = False
else:
print("Thanks for playing!")
main()
|
d05deb33e9b3566dfa1e6188979516c3d9c68699 | Ys-Zhou/leetcode-medi-p3 | /201-300/215. Kth Largest Element in an Array.py | 1,033 | 3.8125 | 4 | # Runtime: 1492 ms, faster than 14.63% of Python3 online submissions
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def half_quick_sort(start, end):
if start == end:
return nums[start]
left, right = start, end
while left < right:
if nums[left] < nums[end]:
left += 1
continue
if nums[right] >= nums[end]:
right -= 1
continue
nums[left], nums[right] = nums[right], nums[left]
nums[left], nums[end] = nums[end], nums[left]
if left == len(nums) - k:
return nums[left]
if left < len(nums) - k:
return half_quick_sort(left + 1, end)
if left > len(nums) - k:
return half_quick_sort(start, left - 1)
return half_quick_sort(0, len(nums) - 1)
|
7c55dc7a024ffa65bc89b9855b0120796b616d22 | Rishikesh-G-Kashyap/Launchpad-Assignments | /Problem1.py | 159 | 3.9375 | 4 | name = input("Enter name: ")
age = int(input("Enter Age: "))
year = str((2019 - age)+100)
print("Hey " + name + "! You will turn 100 years old in " + year) |
21337566ed1cd5f8e815aa324fbfc77e7c302771 | samtaitai/py4e | /exercise1003.py | 857 | 4.09375 | 4 | import string
#file = input("Enter a file name: ")
file = input('Enter a flie name: ' )
hand = open(file) #not a method, but function
counts = dict()
#make a list of single words
for line in hand:
#str.maketrans; If three arguments are passed, each character in the third argument is mapped to None.
#every digits and punctuation should be None
line = line.translate(str.maketrans('','',string.digits))
line = line.translate(str.maketrans('','',string.punctuation))
#every uppercase should be lowercase
line = line.lower()
words = line.split()
#word counter in form of dictionary
for word in words:
counts[word] = counts.get(word, 0) + 1
#flip
temp = list()
for k, v in list(counts.items()):
temp.append((v, k))
#sort in decreasing order
temp.sort(reverse=True)
#flip back and print
for k, v in temp:
print(v)
|
e0dbbbe93eca0d132c18e881aaa7770c74f0564e | Vlek/2048 | /2048.py | 2,323 | 3.828125 | 4 | #!/usr/bin/env python3
from random import choice, randint
class Twoohfoureight:
def __init__(self):
self.map = [[0]*4 for i in range(4)]
self._add_random_piece(2)
def print_map(self):
for i in self.map:
#print('\t'.join(map(str, i)))
print(i)
def _add_random_piece(self, num_pieces=1):
for i in range(num_pieces):
available_slots = []
for row in range(4):
for column in range(4):
if self.map[row][column] == 0:
available_slots.append([row, column])
# TODO: Check len of available_slots for a spot.
# if one is not available, then game over.
chosen = choice(available_slots)
self.map[chosen[0]][chosen[1]] = (4 if randint(1, 10) == 1 else 2)
def _rotate(self, rotations=1):
for rotation in range(rotations):
result = [[] for i in range(4)]
for r in range(3, -1, -1):
for c in range(4):
result[c].append(self.map[r][c])
self.map = result
def move(self, direction=0):
"""
This is my favorite part of making the game. I use this list of lists
in order to decide how many times I rotate the game board in order
to do a standard left-to-right move so that the algorithm is super simple
"""
moves = [
[3, 1],
[2, 2],
[1, 3],
[0, 0]
]
self._rotate(moves[direction][0])
for row in range(4):
r = [i for i in self.map[row] if i != 0]
r_result = []
while(len(r)):
num = r.pop(0)
if len(r) and num == r[0]:
num += r.pop(0)
# TODO: Do a 2048 check here to see if the player won?
# this might not be the best place because we could use
# this method to run tests to see if the player has any valid moves
r_result.append(num)
self.map[row] = r_result + [0]*(4-len(r_result))
self._add_random_piece()
self._rotate(moves[direction][1])
self.print_map()
g = Twoohfoureight()
g.print_map()
|
19533558ae8212778f3f3c0a5596dbce44aacfa1 | carden-code/python | /stepik/code_review.py | 1,197 | 4.03125 | 4 | # A sequence of 10 integers is received for processing.
# It is known that the entered numbers do not exceed 10 ** 6 in absolute value.
# You need to write a program that prints the sum of all negative numbers in the sequence and
# the maximum negative number in the sequence.
# If there are no negative numbers, you need to display "NO".
# The programmer was in a hurry and wrote the program incorrectly.
#
# Find all the errors in this program (there are exactly 5 of them).
# Each error is known to affect only one line and can be fixed without changing other lines.
#
# Note 1. The number xx does not exceed 10 ** 6 in absolute value if -10 ** 6 <= x <= 10 ** 6.
#
# Note 2. If necessary, you can add the required lines of code.
#
# mx = 0
# s = 0
# for i in range(11):
# x = int(input())
# if x < 0:
# s = x
# if x > mx:
# mx = x
# print(s)
# print(mx)
#
maximum_negative = -10**6
sum_negative = 0
for _ in range(10):
number = int(input())
if number < 0:
sum_negative += number
if 0 > number > maximum_negative:
maximum_negative = number
if sum_negative == 0:
print('NO')
else:
print(sum_negative)
print(maximum_negative)
|
deb9eb639725ca8cf4abf150161ec37108db96b6 | HaugenBits/CompProg | /ProgrammingChallenges/Chapter_1/CheckTheCheck/ChecktheCheck.py | 4,658 | 3.546875 | 4 | import sys
class ChessBoard:
def __init__(self, cBoard, num):
self.cBoard = cBoard
self.num = num
self.kinginCheck = "no"
self.kingOnBoard = False
def checkForCheck(self):
for y, line in enumerate(self.cBoard):
for x, ele in enumerate(line.strip()):
self.checkTile(ele, x, y)
def setKingInCheck(self, ele):
if isWhite(ele):
self.kinginCheck = "black"
else:
self.kinginCheck = "white"
def checkTile(self, ele, x, y):
if ele == ".":
return
elif ele == "p" or ele == "P":
if checkPawn(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "b" or ele == "B":
if checkBishop(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "r" or ele == "R":
if checkRook(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "n" or ele == "N":
if checkKnight(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "q" or ele == "Q":
if checkQueen(ele, x, y, self.cBoard):
self.setKingInCheck(ele)
elif ele == "k" or ele == "K":
self.kingOnBoard = True
def printResult(self):
if self.kingOnBoard:
print("Game #", self.num, ": ", self.kinginCheck, " king is in check.", sep='')
def inBounds(x, y):
return 0 <= x < 8 and 0 <= y < 8
def isWhite(piece):
return piece.isupper()
def isBlack(piece):
return not piece.isupper()
def isWhiteKing(piece):
return piece == 'K'
def isBlackKing(piece):
return piece == 'k'
def handleInputV1():
lines = sys.stdin.readlines()
boards = []
for i in range(0, len(lines), 9):
boards.append([i.strip() for i in lines[i:i+8]])
return boards
def handleInputV2():
with open("simpleTest.txt", "r") as fil:
lines = fil.readlines()
boards = []
for i in range(0, len(lines), 9):
boards.append([i.strip() for i in lines[i:i+8]])
return boards
def getKnightMoves(x, y):
return [(x+i, y+k) for i, k in [(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2)]]
def getDirections(x, y):
n, w, s, e = (y - 1, x - 1, y + 1, x + 1)
return n, w, s, e
def getDiagonals(x, y):
nw = [(x-i, y-k) for i, k in zip(range(1, x+1), range(1, y+1))]
ne = [(x+i, y-k) for i, k in zip(range(1, 8-x), range(1, y+1))]
sw = [(x-i, y+k) for i, k in zip(range(1, x+1), range(1, 8-y))]
se = [(x+i, y+k) for i, k in zip(range(1, 8-x), range(1, 8-y))]
return [nw, ne, sw, se]
def getCross(x, y):
n = [(x, y-i) for i in range(1, y+1)]
w = [(x-i, y) for i in range(1, x+1)]
s = [(x, y+i) for i in range(1, 8-y)]
e = [(x+i, y) for i in range(1, 8-x)]
return [n, w, s, e]
def checkPawn(pawn, x, y, board):
n, w, s, e = getDirections(x, y)
if isWhite(pawn):
nw = inBounds(w, n) and isBlackKing(board[n][w])
ne = inBounds(e, n) and isBlackKing(board[n][e])
return nw or ne
if isBlack(pawn):
sw = inBounds(w, s) and isWhiteKing(board[s][w])
se = inBounds(e, s) and isWhiteKing(board[s][e])
return sw or se
def checkKnight(ele, x1, y1, board):
area = getKnightMoves(x1, y1)
for x, y in area:
if inBounds(x, y):
current = board[y][x]
whitecheck = isWhite(ele) and current == "k"
blackcheck = isBlack(ele) and current == "K"
if whitecheck or blackcheck:
return True
return False
def checkBishop(piece, x, y, board):
area = getDiagonals(x, y)
return checkPiece(piece, board, area)
def checkRook(piece, x, y, board):
area = getCross(x, y)
return checkPiece(piece, board, area)
def checkQueen(piece, x, y, board):
area = getDiagonals(x, y) + getCross(x, y)
return checkPiece(piece, board, area)
def checkPiece(piece, board, area):
for direction in area:
for xCoord, yCoord in direction:
current = board[yCoord][xCoord]
whitecheck = isWhite(piece) and current == "k"
blackcheck = isBlack(piece) and current == "K"
if whitecheck or blackcheck:
return True
elif current != ".":
break
return False
def main():
boards = handleInputV2()
for val, board in enumerate(boards, 1):
current = ChessBoard(board, val)
current.checkForCheck()
current.printResult()
print()
if __name__ == '__main__':
main()
|
01f5182546b1f85cf48b0eff6996f61be58a8853 | AgguBalaji/MyCaptain123 | /areaofcircle.py | 338 | 4.46875 | 4 | """Calculate and print the area of the circle based on the user's input of the circle's radius"""
#user input--->taking the input only as int type
radius=float(input("Input the radius of the circle :"))
#calculating the area of the circle
area=3.14159*(radius**2)
#output
print(" The area of the circle with radius",radius,"is:",area)
|
dc01aaf3128f71e81e817cb2bce72219de20b4fd | CiceroLino/Learning_python | /Curso_em_Video/Mundo_1_Fundamentos/Usando_modulos_do_python/ex019.py | 536 | 4.09375 | 4 | #Desafio 019 do curso em video
#Programa que sortea um item da lista
#https://www.youtube.com/watch?v=_Nk02-mfB5I&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=20
from random import choice
print()
n1 = str(input('Primeiro item da lista: '))
n2 = str(input('Segundo item da lista: '))
n3 = str(input('Terceiro item da lista: '))
n4 = str(input('Quarto item da lista: '))
n5 = str(input('Quinto item da lista: '))
lista = [n1, n2, n3, n4, n5]
escolhido = choice(lista)
print(f'O item escolhido (ou sorteado) foi {escolhido}')
print()
|
0cf56fe9cd607812d6e10adb0df38f2d6cb8fc96 | kresnajenie/curriculum-python | /4Loop/tebakangka.py | 387 | 3.96875 | 4 | angka_tebakan = 25 #Ini adalah angka yg benar
tebakan = 0 #Untuk menyatakan ada variabel tebakan
while tebakan != 25:
tebakan = int(input("Masukkan tebakan anda: ")) #Pengguna memasukkan tebakan yang nanti akan dievaluasi oleh program
if tebakan < angka_tebakan:
print("terlalu kecil")
if tebakan > angka_tebakan:
print("terlalu besar")
print ("anda benar!") |
50acb25ad11ad2a648774a7f3af8a0c7d869cca4 | ayk-dev/python-fundamentals | /exams/moving_target.py | 1,087 | 3.5625 | 4 | targets = list(map(int, input().split()))
while True:
line = input()
if line == 'End':
break
tokens = line.split()
command = tokens[0]
index = int(tokens[1])
if command == 'Shoot':
power = int(tokens[2])
if 0 <= index < len(targets):
targets[index] -= power
if targets[index] <= 0:
targets.remove(targets[index])
elif command == 'Add':
value = int(tokens[2])
if 0 <= index < len(targets):
targets.insert(index, value)
else:
print('Invalid placement!')
elif command == 'Strike':
radius = int(tokens[2])
start_i = index - radius
end_i = index + radius
if (0 <= start_i < len(targets)) and (0 <= end_i < len(targets)):
for i in range(start_i, end_i + 1):
targets[i] = -1
targets = [t for t in targets if t != -1]
else:
print('Strike missed!')
targets = [str(t) for t in targets]
print('|'.join(targets))
|
3847137f45bd2e9e9a7cdf117d51eefda0c89d8c | kiran-kotresh/Python-code | /replace_vowels_!.py | 133 | 4.15625 | 4 | vowels = 'aeiouAEIOU'
string = 'Hi! Hi!'
for x in string:
if x in vowels:
string = string.replace(x, '!')
print(string)
|
77eb64c6243ad773ab6bf39b4c27200c3e9574c6 | DilipBDabahde/PythonExample | /Assignment_2/Pattern4.py | 350 | 3.984375 | 4 | """
8).Write a program which accept one number and display below pattern.
Input: 5
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
"""
def Pattern4(iNo):
for i in range(0,iNo):
for j in range(0,i+1):
print(j+1,"",end="");
print("");
def main():
ival = int(input("Enter a val: "));
Pattern4(ival);
if __name__ == "__main__":
main();
|
db6802cee6da68cc71141f1e3102c152a6f20d28 | sevdaghalarova/ileri_seviye_moduller | /odev1.py | 722 | 3.515625 | 4 | """Bilgisayarınızdaki tüm mp4,txt ve pdf dosyalarını os modülüyle arayın ve bunların nerede
bulunduklarını ve isimlerini ayrı ayrı
"pdf_dosyalari.txt","mp4_dosyaları.txt","txt_dosyaları.txt" adlı dosyalara kaydedin."""
import os
for klasor_yolu,klasor_islemi,dosya_islemi in os.walk("/Users/sevdaagalarova/Desktop"): # bu yoldaki tum dosyalari getirir
for i in dosya_islemi:
if i.endswith("pdf"): # py ile biten dosyalari ekrana getirir
with open("PDF_dosyalari.txt", "w", encoding="utf-8") as file:
file.write(i+"\n")
elif i.endswith("py"):
with open("py_dosya.txt", "w", encoding="utf-8") as file1:
file1.write(i+"\n")
|
26ee4434e7df5fb3a8bf77ef5ce76ade7df5f213 | S3annnyyy/CS50-problem-set-solutions | /Pset 7/houses/import.py | 927 | 4.09375 | 4 | import csv
from sys import argv
from cs50 import SQL
#check for correct command line arguement
if len(argv) != 2:
print("Usage: python <filename>.csv")
exit()
#correct command line arguement
#database for file characters.csv for SQL
db = SQL("sqlite:///students.db")
#opening characters.csv
with open(argv[1], "r") as csvfile:
#reading file
reader = csv.DictReader(csvfile, delimiter = ",")
for row in reader:
#splitting name of student into first, middle and last
name = row["name"].split()
if len(name) == 3:
db.execute("INSERT INTO students(first , middle , last, house , birth ) VALUES(?, ?, ?, ?, ?)", name[0], name[1], name[2], row["house"], row["birth"])
elif len(name) ==2: #no middle name
db.execute("INSERT INTO students(first , middle , last , house , birth ) VALUES(?, ?, ?, ?, ?)", name[0], None, name[1], row["house"], row["birth"])
|
6fbc2b5bf64aff170506cbaa0be992635012709d | NeaHerforth/Completed-Kattis-Files | /coldputer.py | 322 | 3.890625 | 4 | #! /usr/bin/env python3
import sys
#s=sys.stdin.read().splitlines()
s='''5
-14 -5 -39 -5 -7'''
s=s.splitlines()
#Number of temperatures collected
n=int(s[0])
#Temperatures
temp=s[1].split()
#Find out how many temps are below 0 degrees
count=0
for i in temp:
if int(i)<0:
count +=1
print(count)
#Accepted
|
1e0a761f589fe8f3cfc18b66a54af0437fe2c7fc | chlee1252/dailyLeetCode | /book/problems/impossibleCoin.py | 258 | 3.53125 | 4 | def solution(N, coins):
if 1 not in coins:
return 1
target = 1
coins.sort()
for coin in coins:
if target < coin:
break
target += coin
return target
print(solution(5, [1,2,4,7]))
print(solution(5, [3,2,1,1,9])) |
ff4bad85356533966f79bfa9578452229d8404da | paladino3/AulasPython | /Exercicios/ex017.py | 443 | 4.21875 | 4 | """
Desafio 017
Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo,
calcule e mostre o comprimento da hipotenusa.
"""
from math import pow, sqrt
co=float(input('Digite o tamanho do Cateto Oposto: '))
ca=float(input('Digite o tamanho do Cateto Adjacente: '))
hip=((co**2)+(ca**2))
hip=hip**2;
print('O Cateto Oposto {}, Cateto Adjacente {} e o Tamanho da Hipotenusa {:.0f}'.format(co,ca,hip**2))
|
b621916820d294c82b52a853b5c181ca66a49b44 | nisheshthakuri/Python-Workshop | /JAN 19/Assignment/Tuple/Q4.py | 132 | 4.09375 | 4 | Q.Program to convert a list to a tuple
Solution:
lists = [1, 3, 5, 7, 9, 11]
print(lists)
tup = tuple(lists)
print(tup)
|
343c5be8b96038f6cb987d519d67e108069318ed | compilepeace/DS_AND_ALGORITHMS | /DS_with_python/dynamic_programming/05_min_number_of_squares_reccursion.py | 738 | 3.578125 | 4 | import sys
import math
def isPerfectSquare(n):
root = math.sqrt(n)
result = root - int(root)
if result == 0:
return True
else:
return False
def minNumberOfSquares(n, dp):
if n == 0:
return 0
# In case number is a perfect square
if isPerfectSquare(n):
return 1
result = INT_MAX
for i in range(1, int(math.sqrt(n)) + 1):
if dp[n - i*i] == None:
ans = minNumberOfSquares( n - i*i, dp)
else:
ans = dp[ n - i*i ]
result = min(ans, result)
dp[n] = 1 + result
return dp[n]
INT_MAX = sys.maxsize
n = int(input("Enter the number: "))
dp = [None for i in range(n+1)]
result = minNumberOfSquares(n, dp)
print(f"Minimum number of sum of squares for {n}: {result}")
print(f"dp: {dp}")
|
c0acb074f67b5f0c412d1fd3d0bb27b24651a0eb | rahulvennapusa/PythonLearning | /Basics/EvenOddCehck.py | 213 | 4.21875 | 4 | inp_str = (input("Enter an integer"))
if type(inp_str) == int and inp_str % 2 == 0:
print("Even number")
elif type(inp_str) == int and inp_str % 2 != 0:
print("Odd number")
else:
print("Not a number")
|
4a9786e609017219c6b097848b5d8af650987c53 | niphadkarneha/SummerCamp | /Python Scripts/Intro_to_Python.py | 1,880 | 4.28125 | 4 | # Intro to Python
# The PRINT statement
print("text")
print("Hello, world!")
print("")
print("Suppose two swallows \"carry\" it together.")
print('African or "European" swallows?')
# Mathematical operations
2+2
50 - 5*6
(50 - 5*6) / 4
8 / 5 # division always returns a floating point number
17 / 3 # classic division returns a float
17 // 3 # floor division discards the fractional part
17 % 3 # the % operator returns the remainder of the division
5 * 3 + 2 # result * divisor + remainder
# Variables
print ("Subtotal:")
print (38 + 40 + 30)
print ("Tax:")
print ((38 + 40 + 30) * .09)
print ("Tip:")
print ((38 + 40 + 30) * .15)
print ("Total:")
print (38 + 40 + 30 + (38 + 40 + 30) * .15 + (38 + 40 + 30) * .09)
# Use variables to simplify code
x = (38 + 40 + 30) # create a new variable for x to subsitute (38+40+30)
print (x)
print ("Subtotal:", x) # print the phrase "Subtotal" followed by the new variable value
tax = (x * .09) # create a new variable called "tax"
print ("Tax:", tax) #text strings are enclosed in "", values/variables are not
tip = (x * .15)
print ("Tip:", tip)
total = (x + tax + tip)
print ("Total:", total)
# Parameters
print(sqrt(25)) # This will generate an error message
from math import * # To use math commands, import the math library
print(sqrt(25))
print(sqrt(15 + 10 * 10 + 6))
x = 5
print(sqrt(x + sqrt(16)))
# INPUT statement
age = input("How old are you? ")
age = int(age) #convert text value to an integer
print("Your age is", age)
print("You have", 65 - age, "years until retirement")
# Exercise: write a program to convert temperature from Fahrenheit to Celsius.
# The program should ask the user for input of a Fahrenheit value, which it will then convert to Celsius.
# Hint: formula is : c = ((f-32)*5)/9
|
1a0b4f03018171f6df44ff767fa7313e27d86532 | arkolcz/rpi_weather | /rpi_weather.py | 2,533 | 3.515625 | 4 | import sys
from urllib.error import HTTPError
import urllib.request
import json
import requests
# Globals
IP_INFO_URL = 'http://ipinfo.io/json'
# Keys for dict containing ip based data
COUNTRY = 'country'
CITY = 'city'
HOST_IP = 'ip'
# OpenWeather API url
OW_API_URL = 'https://api.openweathermap.org/data/2.5/weather?q={0}&appid={1}'
def get_weather_data(ip_data: dict, api_key: str) -> dict:
""" Gets weather data from OpenWeather API
Args:
ip_data (dict): Dict contining location data based on IP
api_key (str): OpenWeather API key
Returns:
weather_data (dict): Weather data
"""
city = ip_data[CITY]
url = OW_API_URL.format(city, api_key)
r = requests.get(url)
weather_data = r.json()
return weather_data
def get_ip_info() -> dict:
""" Gets location information based on host ip
Returns:
ip_info (dict): Location data gathered based on IP address
"""
try:
with urllib.request.urlopen(IP_INFO_URL) as response:
ip_info = json.load(response)
except HTTPError as err:
print(f'Can\'t access ip data from {IP_INFO_URL}. \
(Error={err.strerror})')
return ip_info
def get_api_key(f_path: str) -> str:
""" Gets OpenWeather API key from file
Args:
f_path (str): Path to file containg API key
Returns:
api_key (str): Open Weather API key
"""
try:
with open(f_path, 'r') as f:
api_key = f.read().rstrip()
except FileNotFoundError as err:
print(f'Invalid path to file: {f_path}. (Error={err.strerror})')
sys.exit(1)
except Exception as err:
print(f'Could not retrieve API key. (Error={err.strerror})')
sys.exit(1)
return api_key
def main(f_path) -> None:
""" Main function of the program
Args:
f_path (str): Path to file containg API key
"""
api_key = get_api_key(f_path)
ip_info = get_ip_info()
weather = get_weather_data(ip_info, api_key)
print(weather)
def usage() -> None:
""" Prints scripts usage message
"""
message = """
Usage: rpi_weather path-to-file
path-to-file: Path to file that contains your API key
--help: This help message
"""
print(message)
if __name__ == '__main__':
if '--help' in sys.argv:
usage()
sys.exit(0)
if len(sys.argv) < 2:
print('Error: Path to file containing OpenWeather\
API Key must be provided')
usage()
sys.exit(1)
main(sys.argv[1]) |
d658fd72c7b3a4b47b2ebfad103adee4d2be3fd1 | Wizmann/ACM-ICPC | /Leetcode/Algorithm/python/2000/01171-Remove Zero Sum Consecutive Nodes from Linked List.py | 1,045 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeZeroSumSublists(self, head):
l = []
s = set([0])
pre = 0
while head:
pre += head.val
l.append(head)
#print pre, s
while pre in s:
s.remove(pre)
pre = pre - l.pop().val
else:
s.add(pre)
head = head.next
dummyHead = ListNode(-1)
cur = dummyHead
for item in l:
cur.next = item
cur = cur.next
if l:
l[-1].next = None
return dummyHead.next
def makeList(l):
dummyHead = ListNode(-1)
cur = dummyHead
for item in l:
cur.next = ListNode(item)
cur = cur.next
return dummyHead.next
def getList(head):
res = []
while head:
res.append(head.val)
head = head.next
return res
|
7ac93a04e4420e9baee87f842ba846c2628dda61 | tum0xa/algo_and_structures_python | /Lesson_1/4.py | 2,661 | 4.46875 | 4 | """
4. Написать программу, которая генерирует в указанных пользователем границах
● случайное целое число,
● случайное вещественное число,
● случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Программа должна вывести на экран любой
символ алфавита от 'a' до 'f' включительно.
"""
import random
import string
def isfloat(raw_str):
"""Function that return "True" if the input string is a float number.
Keyword arguments:
raw_str -- Raw string for checking
"""
if str(raw_str).count('.') > 1 or str(raw_str).count('.') == 0:
return False
dec_part = str(raw_str).split('.')[0]
float_part = str(raw_str).split('.')[1]
if dec_part.isdecimal() and float_part.isdecimal:
return True
else:
return False
print("You can generate random values for the next cases (depends of your input):\n"
"- for integer numbers;\n"
"- for floating numbers;\n"
"- for english letters. ")
start_value = input("Type a start value for a range: ")
end_value = input("Type an end value for the range: ")
if start_value.isdecimal() and end_value.isdecimal():
if int(end_value) < int(start_value):
temp_value = start_value
start_value = end_value
end_value = temp_value
print(f"Your random integer number is {random.randint(int(start_value), int(end_value))}")
elif isfloat(start_value) and isfloat(end_value):
if float(end_value) < float(start_value):
temp_value = start_value
start_value = end_value
end_value = temp_value
print(f"Your random floating number is {float(start_value) + (float(end_value) - float(start_value)) * random.random()}")
elif len(start_value) == 1 and len(end_value) == 1 and start_value.isalpha() and end_value.isalpha():
if end_value < start_value:
temp_value = start_value
start_value = end_value
end_value = temp_value
# get the list of lowercase letters
alphabet = list(string.ascii_lowercase)
start_value = start_value.lower()
end_value = end_value.lower()
print(f"Your random character symbol is '{random.choice(alphabet[alphabet.index(start_value):alphabet.index(end_value)])}'")
else:
print("Invalid input!")
|
e802e8154b571e52d5a55c68cb99efa9e09f76b2 | Benjaminlii/pythonFirst | /9.面向对象高级.py | 2,639 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Benjamin
# date:2020.11.18 21:06
# 使用__slots__
# 在类内部定义__slots__属性为一个字符串元组可以限制类的属性
class Student(object):
__slots__ = ('name', 'age')
student = Student()
# student.score = 100
# 使用@property
# 在python中使用set_xxx()或者get_xxx()方法对属性进行操作灵活性不如直接对属性进行操作,但直接操作属性有会有安全问题。
# python提供了@property来将一个与方法变成属性,直接取属性就可以转化为调用方法进行get
# 相应的,提供了@xxx.setter装饰器来代替set方法
class People(object):
def __init__(self, age):
self.age = age
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if not isinstance(age, int):
raise ValueError('age must be an integer!')
elif age < 0 or age > 150:
raise ValueError('age must between 0 ~ 150!')
self._age = age
people = People(120)
print (people.age)
# 多继承
# python支持多继承,在类名后面的小括号中添加多个父类名即可
# 定制类
# 之前了解了__slots__这种形如__xxx__的方法或属性的作用
# 还有很多类似的用法
# __str__(self):相当于Java中的toString()方法
# __iter__(self):如果想通过for-in迭代该对象,则需要在__iter__(self)方法中返回该对象本身,
# 并且需要提供一个next(self)方法返回迭代得到的每一个过程量,直到遇到StopIteration错误时退出循环(即在外部进行迭代的循环)
# __getitem__(self, n):如果要将对象按照list一样使用[]根据下标随机访问,需要提供__getitem__(self, n)方法返回sub下表处的元素。
# 如果要处理切片,则需要对n参数进行类型判断
# __getattr__(self, attr):当查找属性时,如果没有找到,就会尝试去__getattr__(self, attr)方法中寻找
# 要让class只响应特定的几个属性,需要在其他的情况下抛出AttributeError的错误,否则会默认返回None
class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
# 类似链表的结构,每一个Chain对象在访问不存在的属性时,都会创造新的chain对象封装一段属性名
# 并通过str进行拼接
chain = Chain().status.user.timeline.list
print (chain)
print (type(chain))
# __call__(self):直接将对象本身作为方法执行时会调用该方法
|
4e3ac3bec34fc5c0bb9c3b00dca4bd5916809497 | pvargos17/python_practice | /week_02/labs/03_variables_statements_expressions/Exercise_09.py | 466 | 4.5625 | 5 | '''
Receive the following arguments from the user:
- miles to drive
- MPG of the car
- Price per gallon of fuel
Display the cost of the trip in the console.
'''
print("""
-------------------------------------------------
TRIP COST CALCULATOR
-------------------------------------------------
""")
def cost(x,y,z):
miles = x
mpg = y
price = z
total_cost = (mpg/miles)*price
return total_cost
print(cost(10,20,5))
|
6b650a9aef5554aaf4306f9a7253c7e9ae67f4b7 | genggng/leetcode | /316-1.py | 1,098 | 3.515625 | 4 | """
6214. 判断两个事件是否存在冲突 显示英文描述
给你两个字符串数组 event1 和 event2 ,表示发生在同一天的两个闭区间时间段事件,其中:
event1 = [startTime1, endTime1] 且
event2 = [startTime2, endTime2]
事件的时间为有效的 24 小时制且按 HH:MM 格式给出。
当两个事件存在某个非空的交集时(即,某些时刻是两个事件都包含的),则认为出现 冲突 。
如果两个事件之间存在冲突,返回 true ;否则,返回 false 。
"""
from typing import List
class Solution:
def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
def time2min(event):
mins = []
for t in event:
h,m = map(int,t.split(":"))
mins.append(h*60+m)
return mins
start1,end1 = time2min(event1)
start2,end2 = time2min(event2)
if end1 < start2 or end2< start1:
return False
return True
event1 = ["01:15","02:00"]
event2 = ["02:00","03:00"]
print(Solution().haveConflict(event1,event2))
|
be00f9ab62bd23184ede35811ebfd9ead23a2561 | TheLostLight/Simple-Scheduler | /src/filegenerator.py | 1,341 | 3.84375 | 4 | import random
from datetime import datetime
# Randomly generates an example file which can be used as
# input in fileread.py
#
# file_name - Name of resulting output file
# nclass - Number of individual class times to generate
# max_time - The maximum latest time a class can end at
def createExampleFile(file_name, nclass, max_time):
result = open(file_name, "w")
result.write("Classes (start_time::end_time) : \n")
for _ in range(0, nclass):
start = random.randint(0, max_time-1)
result.write("(" + str(start) + "::" + str(random.randint(start+1, max_time)) + ")\n")
result.close()
# Saves the result of a scheduling algorithm to a text file
def saveDataToFile(file_name, data):
result = open(file_name, "w")
result.write("File generated " + datetime.now().strftime("%B %d, %Y - %H:%M:%S") + "\n\n")
result.write("Minimum classrooms: " + str(len(data)) + "\n")
result.write("---------\n\n")
for i in range(0, len(data)):
result.write("Classroom " + str(i+1) + ":\n----------------\n")
ind = 1
for class_time in data[i]:
result.write("Class " + str(ind) + ": (" + str(class_time[0]) + "-" + str(class_time[1]) + ")\n")
ind += 1
#result.write("----------------\n")
result.write("\n")
result.close() |
1e58be0c73df6eb43fc620ea2e0a92a1eb9b1c0d | tw-alexander/CodeHS-Intro_To_Computer_Science-Answers-Python | /CodeHs/4.Functions And Exceptions/2.Namespaces in Functions/6.2.6 Adding to a Value.py | 95 | 3.859375 | 4 | num1 = 10
num2 = int(input())
def add_sum():
sum = num1+num2
print(sum)
add_sum()
|
9cf3781afbb5c09fd1db83b2b7435d8fe8654aef | YimoZhu/Numerical-Analysis | /prog3/codeQ1Q2Q3Q4.py | 6,612 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Author: Yimo Zhu
This is for Math 128A programming assignment #3
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
###############################################################################
def q1(a,b,x):
#Take the input vectors a&b to use Recurrence System(3) to evaluate \phi at x
#First lets check wether len(a)+1 = len(b). If not, the input is not valid
if len(a)+1 != len(b):
raise ValueError
#Then if the input is valid:
n = len(a)
m = len(x)
PHI = np.zeros((n+1,m))
k = 0
for x_k in x:
#for each x we recursively compute \phi_0(x_k/) to \phi_n(x_k)
phi = np.zeros(n+1)
counter = 0
while True:
if counter == 0:
phi[counter] = np.sqrt(1/2)
counter = counter + 1
continue
elif counter == 1:
phi[counter] = ((x_k-a[counter-1])*phi[counter-1])/np.sqrt(b[counter])
counter = counter + 1
continue
elif counter <= n:
phi[counter] = ((x_k-a[counter-1])*phi[counter-1]-np.sqrt(b[counter-1])*phi[counter-2])/np.sqrt(b[counter])
counter = counter + 1
continue
else:
break
PHI[:,k] = phi
k = k + 1
return PHI
#---------------------------------------------------------------------
def q2(a,b):
#Take the input vectors a&b to use Recurrence System(3) to get the coefficients of unit legendre polynomials up to degree n
#First lets check wether len(a)+1 = len(b). If not, the input is not valid
if len(a)+1 != len(b):
raise ValueError
#Then if the input is valid:
n = len(a)
S = np.zeros((n+1,n+1))
j = 0
while True:
if j == 0:
S[j,j] = np.sqrt(1/b[j])
j = j + 1
continue
elif j == 1:
S[j,:] = (S[j-1,:]-np.append([0],a[j-1]*S[j-1,:-1]))/np.sqrt(b[j])
j = j + 1
continue
elif j <= n:
S[j,:] = (S[j-1,:]-np.append([0],a[j-1]*S[j-1,:-1])-np.append([0,0],np.sqrt(b[j-1])*S[j-2,:-2]))/np.sqrt(b[j])
j = j + 1
continue
else:
break
return S
#---------------------------------------------------------------------
def q3(a,b):
"""Take the input vectors a&b to use olub-Welsch algorithm to calculate the abiscissas vector x & the weights vector w, each with length n"""
#First lets check wether len(a)+1 = len(b). If not, the input is not valid
if len(a)+1 != len(b):
raise ValueError
#Then if the input is valid:
n = len(a)
#Shape the coefficient matrix A
A = np.zeros((n,n))
row_counter = 0
for a_i in a:
A[row_counter,row_counter] = a_i
if row_counter == 0:
A[row_counter,row_counter+1] = np.sqrt(b[row_counter+1])
elif row_counter == n-1:
A[row_counter,row_counter-1] = np.sqrt(b[row_counter])
else:
A[row_counter,row_counter-1] = np.sqrt(b[row_counter])
A[row_counter,row_counter+1] = np.sqrt(b[row_counter+1])
#Finished filling the values in this row
row_counter = row_counter + 1
continue
#Finished shaping the A. Now compute the eigenvalues
x,Q = np.linalg.eig(A)
w = b[0]*Q[0,:]**2
return x,w
#---------------------------------------------------------------------
def q4(a,b):
#Call the code from q2 to get the coefficients up to degree n
S = q2(a,b)
n = len(a)
x = np.array(sorted(np.roots(S[n,:n+1])))
Phi = np.zeros((n,n))
for j in range(n):
Phi[j,:] = np.polyval(S[j,:j+1],x)
w = 1.0/np.diag(Phi.T.dot(Phi))
return x,w
###############################################################################
#The main programms
"""Question # 1"""
#Now lets generate the 2 plots of \phi_n(x)
for n in [10,50]:
print("Q1 Case n <-- %s"%n)
a = np.zeros(n)
b = np.append([2],np.arange(1,n+1)**2/(4*np.arange(1,n+1)**2-1))
x = np.cos(np.linspace(-np.pi,0,10*n))
phi_n = q1(a,b,x)[-1,:]
fig = plt.figure(figsize=(10,8))
plt.suptitle("Q1 Case n = %s"%n)
plt.plot(x,phi_n)
plt.grid(True)
plt.show()
#---------------------------------------------------------------------
"""Question # 2"""
n = 50
a = np.zeros(n)
b = np.append([2],np.arange(1,n+1)**2/(4*np.arange(1,n+1)**2-1))
S = q2(a,b)
x = np.cos(np.linspace(-np.pi,0,500))
phi10 = S[10,:11]
phi50 = S[50,:51]
#First the plot where n = 10
fig = plt.figure(figsize=(10,8))
plt.suptitle("Q2 Case n = 10")
y10 = np.polyval(phi10,x)
plt.plot(x,y10)
plt.grid(True)
fig = plt.figure(figsize=(10,8))
plt.suptitle("Q2 Case n = 50")
y50 = np.polyval(phi50,x)
plt.plot(x,y50)
plt.grid(True)
plt.show()
#---------------------------------------------------------------------
"""Question # 3"""
n = 10
E = np.zeros(2*n+1)
a = np.zeros(n)
b = np.append([2],np.arange(1,n+1)**2/(4*np.arange(1,n+1)**2-1))
x,w = q3(a,b)
for k in np.arange(0,2*n+1):
E[k] = abs(w.dot(np.cos(k*np.arccos(x))) - (1+(-1)**k)/(1-k**2 +1.0e-18))
xw = pd.DataFrame({'abscissas':x,'weight':w})
print(xw)
xw.to_csv('Q3xwCase10.csv')
print(E)
pd.DataFrame({'E':E}).to_csv('Q3ECase10.csv')
n = 40
E = np.zeros(2*n+1)
a = np.zeros(n)
b = np.append([2],np.arange(1,n+1)**2/(4*np.arange(1,n+1)**2-1))
x,w = q3(a,b)
for k in np.arange(0,2*n+1):
E[k] = abs(w.dot(np.cos(k*np.arccos(x))) - (1+(-1)**k)/(1-k**2 +1.0e-18))
xw = pd.DataFrame({'abscissas':x,'weight':w})
print(xw)
xw.to_csv('Q3xwCase40.csv')
print(E)
pd.DataFrame({'E':E}).to_csv('Q3ECase40.csv')
print('Norm:%s'%np.linalg.norm(E[:80]))
#---------------------------------------------------------------------
"""Question # 4"""
n = 10
E = np.zeros(2*n+1)
a = np.zeros(n)
b = np.append([2],np.arange(1,n+1)**2/(4*np.arange(1,n+1)**2-1))
x,w = q4(a,b)
for k in np.arange(0,2*n+1):
E[k] = abs(w.dot(np.cos(k*np.arccos(x))) - (1+(-1)**k)/(1-k**2 +1.0e-18))
xw = pd.DataFrame({'abscissas':x,'weight':w})
print(xw)
xw.to_csv('Q4xwCase10.csv')
print(E)
pd.DataFrame({'E':E}).to_csv('Q4ECase10.csv')
n = 40
E = np.zeros(2*n+1)
a = np.zeros(n)
b = np.append([2],np.arange(1,n+1)**2/(4*np.arange(1,n+1)**2-1))
x,w = q4(a,b)
for k in np.arange(0,2*n+1):
E[k] = abs(w.dot(np.cos(k*np.arccos(x))) - (1+(-1)**k)/(1-k**2 +1.0e-18))
xw = pd.DataFrame({'abscissas':x,'weight':w})
print(xw)
xw.to_csv('Q4xwCase40.csv')
print(E)
pd.DataFrame({'E':E}).to_csv('Q4ECase40.csv')
print('Norm:%s'%np.linalg.norm(E[:80])) |
7cbc25853699adff4c2aa5cf3aed10a948403e7d | gtsofa/homestudy | /find_fib.py | 324 | 4.0625 | 4 | # find_fib.py
# 1,1,2,3,5,8,13
# The fibonacci sequence is defined by:
# Fn = Fn-1 + Fn-2
# where F0 = 0 and F1 = 1
def fib(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
result = fib(num - 1) + fib(num -2)
return result
print(fib(3))
print(fib(4))
print(fib(5))
|
904a7d4ba0a5a818d416c5c55bd7cbea1e6044f3 | areshta/python-edu | /basic-training-examples/tuple/tuple-1.py | 900 | 4.4375 | 4 | #Python-3 tuple examples
print("\n*** Simple tuple ***\n")
seasons = ("winter", "spring", "summer", "autumn")
print("There are enough tuples in real life.\nSeasons, for example: ", seasons)
print("\n*** Create tuple from list ***\n")
a, b = 3, 4
c = tuple([a,b])
print(c)
print("\n*** Function can return tuple ***\n")
def zero_coord():
return 0,0
zc = zero_coord()
print(zc)
print("\n*** Tuple as a key of a dictionary ***\n")
half_life = { ("uranium",235):7.04e8,
("uranium",238):4.468e9,
("plutonium",239):2.41e4,
("plutonium",240):6500
}
print("Half-life of uranium-238 = ", half_life[("uranium",238)] )
print("\n*** Tuple can include references to changing values ***\n")
tp = ([10],) # if you miss ',' it will be integer in parentheses
print("Tuple includes list. tp[0][0] = ", tp[0][0])
tp[0][0] = -100
print("The list inside tuple was changed. tp[0][0] = ", tp[0][0])
|
0e062c29009d03b26d3d22fd897aead0c786b656 | girishdhegde/aps-2020 | /argsorter.py | 297 | 3.75 | 4 | def argsort(lst):
idx = [i for i in range(len(lst))]
zp = list(zip(lst, idx))
zp.sort()
return list(zip(*zp))[1]
if __name__ == '__main__':
import random
n = int(input())
a = [random.randint(0, 10) for i in range(n)]
print(a)
print(argsort(a))
print(1232) |
c2abeb30d41c27a0e1167d3b371a78e16e0d9a18 | kylederkacz/Exercises | /phonenumbers.py | 814 | 4.15625 | 4 | PHONE_NUMBER_LENGTH = 10
def phone(number):
number = str(int(number))
if len(number) < PHONE_NUMBER_LENGTH:
raise Exception('Invalid phone number')
def calcstrings(number, digit, string):
if digit == PHONE_NUMBER_LENGTH:
print string
else:
for i in 1,2,3:
calcstrings(number, digit+1, string+get_char(int(number[digit]), i))
calcstrings(number, 0, '')
# Get character method
chars = (
('0', '0', '0'),
('1', '1', '1'),
('A', 'B', 'C'),
('D', 'E', 'F'),
('G', 'H', 'I'),
('J', 'K', 'L'),
('M', 'N', 'O'),
('P', 'R', 'S'),
('T', 'U', 'V'),
('W', 'X', 'Y'),
)
def get_char(digit, place):
if digit >= len(chars):
raise Exception('Invalid digit')
if place > 3 or place < 1:
raise Exception('Invalid character location.')
return chars[digit][place-1]
phone(5126187802)
|
fce8265ddac56dc04a11c63db76b0bb68fcad763 | shantelAT/Learningpython | /LearningPython/DataStructurestack.py | 494 | 4.1875 | 4 | #************** Learning Stacks
class Stack():
def __init__ (self, item):
self.itemlist = []
def push(self, item):
self.itemlist.append(item)
def get_stack(self):
return self.itemlist
def pop(self):
return self.itemlist.pop()
def is_list_empty(self):
return self.itemlist == []
s = Stack("A")
c = Stack("C")
s.push("d")
s.push("u")
s.push("m")
s.push("plin")
print(s.get_stack())
print(c.get_stack())
print(c.is_list_empty())
|
395c4bcae4ffd77dc5df3d71fbb008a552336d1e | AbeForty/Dojo-Assignments | /Python/Python Fundamentals/findCharacters.py | 270 | 3.828125 | 4 | word_list = ['hello', 'world', 'my', 'name', 'is', 'Anna']
new_list = []
def findCharacter(char, lst):
for i in range(0, len(lst)):
if word_list[i].find(char) > 0:
new_list.append(word_list[i])
print new_list
findCharacter("o", word_list)
|
fabff8fcda7d846be80709a673ae65c57891a281 | hariesramdhani/pyScripts | /markovize.py | 2,895 | 4.21875 | 4 | #!/usr/bin/python3
"""
Markovize is a program that will let you randomize sentences
from a txt file based on the probability of appearance of
letter that came after the order using Markov's chain rule.
------------------------------------------------------------
PROGRESS : ████████████████████████████████████████████ 91%
---------------------------FUNCTIONS------------------------
getSentences: gets sentences from a file
ngramize: ngramizes the sentences
markovize: returns the possible sentence that can be generated
by Markov's chain rule
------------------------------------------------------------
---------------------------PARAMETERS------------------------
filename: your file name
sentenceLength: Length of sentence to be generated
order: Length of word to be n-grammized, for example order of
3 will return 3-grams of the sentences
------------------------------------------------------------
"""
import random
filename = input('Please enter the filename: ')
order = int(input('Please enter number of order: '))
sentenceLength = int(input('Please enter the length of output sentence: '))
keyword = input('Please enter your keyword: ')
def getSentences(filename):
sentences = ''
with open(filename, 'r') as f:
for line in f:
sentences += line.strip()
return sentences.lower()
#Generating the ngrams from the given sentences or texts
def ngramize(filename, order):
sentences = getSentences(filename)
ngrams = {}
for i in range(len(sentences)-order+1):
gram = sentences[i:i+order]
if gram not in ngrams:
ngrams[gram] = []
if i + order < len(sentences):
ngrams[gram].append(sentences[i+order])
return ngrams, sentences
#Generating random sentences based on the probability of the
#letter appearance
def markovize(keyword, filename, order, sentenceLength):
ngrams, sentences = ngramize(filename, order)
while len(keyword) < order or sentences.find(keyword) == -1:
while len(keyword) < order:
keyword = input('Please enter a longer keyword: ')
while sentences.find(keyword) == -1:
keyword = input('Your keyword was not in the text, please enter another one: ')
currentGram = keyword[-order:]
result = keyword
for i in range(sentenceLength):
possibilities = ngrams[currentGram]
if len(possibilities) == 0:
break
else:
next = random.choice(possibilities)
result += next
currentGram = result[len(result)-order:]
return result
def main():
print(markovize(keyword, filename, order, sentenceLength))
#generate = int(input('Please enter the number of generation: '))
#print(getSentences(filename))
if __name__ == '__main__':
main()
|
8aa5b599f84ee8813645fbd83453dcdc7ea1e5a4 | bobogit/python | /103枚举.py | 456 | 3.765625 | 4 | from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
day1 = Weekday.Sun
print(day1.value)
@unique
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
# 测试:
bart = Student('Bart', Gender.Male)
if bart.gender == Gender.Male:
print('测试通过!')
else:
print('测试失败!') |
4a86f36509a99bdc1a2812a973d958fe1d0f40f6 | EvanMu96/Cipherinpython | /Reverse_Cipher/Reverse.py | 2,735 | 3.828125 | 4 | # Reverse cipher
import sys,pyperclip
__author__ = "Evan Mu"
def main():
my_message = """Alan Mathison Turing was a British mathematician, logician
, cryptanalyst, and computer scientist. He was highly influential in the d
evelopment of computer science, providing a formalisation of the concepts of
"algorithm" and "computation" with the Turing machine. Turing is widely con
sidered to be the father of computer science and artificial intelligence. D
uring World War II, Turing worked for the Government Code and Cypher School
(GCCS) at Bletchley Park, Britain's codebreaking centre. For a time he was
head of Hut 8, the section responsible for German naval cryptanalysis. He
devised a number of techniques for breaking German ciphers, including the
method of the bombe, an electromechanical machine that could find settin
gs for the Enigma machine. After the war he worked at the National Physi
cal Laboratory, where he created one of the first designs for a stored-pr
ogram computer, the ACE. In 1948 Turing joined Max Newman's Computing Lab
oratory at Manchester University, where he assisted in the development of
the Manchester computers and became interested in mathematical biology.
He wrote a paper on the chemical basis of morphogenesis, and predicted o
scillating chemical reactions such as the Belousov-Zhabotinsky reaction,
which were first observed in the 1960s. Turing's homosexuality resulted i
n a criminal prosecution in 1952, when homosexual acts were still illegal
in the United Kingdom. He accepted treatment with female hormones (chemical
castration) as an alternative to prison. Turing died in 1954, just over
two weeks before his 42nd birthday, from cyanide poisoning. An inquest
determined that his death was suicide; his mother and some others believed
his death was accidental. On 10 September 2009, following an Internet
campaign, British Prime Minister Gordon Brown made an official public
apology on behalf of the British government for "the appalling way he was
treated." As of May 2012 a private member's bill was before the House of Lords
which would grant Turing a statutory pardon if enacted."""
print("Reverse Cipher")
translated = reverse_cipher(my_message)
print(translated)
# Copy to clipboard
pyperclip.copy(translated)
def reverse_cipher(plain_text):
translated = ''
i = len(plain_text) - 1
while i >= 0:
translated = translated + plain_text[i]
i -= 1
return translated
if __name__ == '__main__':
main()
|
835d00d1805e089392c8e59959da16241ddbe40c | satrini/python-study | /exercises/exercise-52.py | 250 | 3.875 | 4 | while True:
genrer = str(input("Your genrer: ")).strip().lower()
if genrer == "m" or genrer == "f":
print("Registered with success!")
print(f"Genrer: {genrer}")
break
print("invalid input!")
print("End program..")
|
0326e9dc97c5f8059e1c33efc3c0cc462c0e3b4e | J-AugustoManzano/livro_Python | /ExerciciosAprendizagem/Cap08/c08ex16.py | 166 | 3.796875 | 4 | valores = [1, 2, 3, 4, 5]
soma = 0
for i in valores:
soma += i
print("Somatório = ", soma)
enter = input("\nPressione <Enter> para encerrar... ")
|
1aa58908df9f7d89d18fafc9d12942e6894313d6 | CelvinBraun/snake | /snake.py | 2,559 | 3.84375 | 4 | from turtle import Turtle, Screen
import time
#game settings
window_title = "snake"
background_color = "black"
screen_width = 600
screen_height = 600
move_speed = 0.3
#snake settings
color_of_snake = "green"
shape_of_snake = "square"
size_of_snake = 1
move_distance = 20
#directions
up = 90
left = 180
down = 270
right = 0
class Snake:
def __init__(self):
# initial variables
self.start_pos_x = 0
self.start_pos_y = 0
self.segments = []
self.game_is_on = True
# screen variables
self.screen = Screen()
self.screen.setup(width=screen_width, height=screen_height)
self.screen.bgcolor(background_color)
self.screen.title(window_title)
self.screen.tracer(0)
self.create_snake()
# create initial snake body
def create_snake(self):
for body_part in range(0, 3):
self.add_segment()
# add segement to snake
def add_segment(self):
new_segment = Turtle()
new_segment.color(color_of_snake)
new_segment.shape(shape_of_snake)
new_segment.shapesize(size_of_snake)
new_segment.penup()
new_segment.goto(self.start_pos_x, self.start_pos_y)
self.start_pos_x -= 20
self.segments.append(new_segment)
def extend_snake(self, pos_x, pos_y):
self.start_pos_x = pos_x
self.start_pos_y = pos_y
self.add_segment()
def move(self):
self.screen.update()
time.sleep(move_speed)
for seg in range(len(self.segments) - 1, 0, -1):
new_x = self.segments[seg - 1].xcor()
new_y = self.segments[seg - 1].ycor()
self.segments[seg].goto(new_x, new_y)
self.segments[0].forward(move_distance)
def reset(self):
self.start_pos_x = 0
self.start_pos_y = 0
for seg in range(len(self.segments)):
self.segments[seg].reset()
self.segments.clear()
self.create_snake()
#move directions
def up(self):
heading = self.segments[0].heading()
if heading != down:
self.segments[0].setheading(up)
def down(self):
heading = self.segments[0].heading()
if heading != up:
self.segments[0].setheading(down)
def left(self):
heading = self.segments[0].heading()
if heading != right:
self.segments[0].setheading(left)
def right(self):
heading = self.segments[0].heading()
if heading != left:
self.segments[0].setheading(right) |
af9e8245c8c534b6eee3411d7ad469a8107c5e30 | ayushggarg/classy_crypto_vB | /Transposition.py | 1,002 | 3.625 | 4 | import math
def TranspositionDy(message, key):
#myMessage = 'Cenoonommstmme oo snnio. s s c'
#myKey = 8
key = int(key)
plaintext = decryptMessage(key, message)
return(plaintext + '|')
def decryptMessage(key, message):
numOfColumns = math.ceil(len(message) / key)
numOfRows = key
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
plaintext = [''] * numOfColumns
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
def TranspositionEn(message, key):
#myMessage = 'Common sense is not so common.'
#myKey = 8
key = int(key)
ciphertext = encryptMessage(key, message)
return(ciphertext)
def encryptMessage(key, message):
ciphertext = [''] * key
for col in range(key):
pointer = col
while pointer < len(message):
ciphertext[col] += message[pointer]
pointer += key
return ''.join(ciphertext)
|
98ce7f9e704b8b2c2c1fd06fab846cadc355b2d0 | datasnakes/archives | /Pandas/CleanCSV.py | 1,345 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""This script is designed to remove duplicates from a .csv file and
not which duplicates were removed in a .txt file.
"""
# List of modules used.
import pandas as pd
# Use pandas to read in the dataframe and create lists.
# Read in main file
maf = pd.read_csv('GPCR_Master_Accession_File.csv', index_col=False, dtype=str)
# Read in organisms file and create organisms list
orgs = pd.read_csv('Organisms.csv', index_col=False, dtype=str, header=None)
orglist = list(orgs[0])
# Create dictionary for duplicate values and blank cells/values
dupdict = {} # Dictionary of duplicates based on organisms/columns
nadict = {} # Dictionary of black or n/a cells in the main file
# Create for loop that creates dicts
for org in orglist:
dups = maf.duplicated(org, keep=False)
dupdict[org] = dups
nas = maf[org].isnull()
nadict[org] = nas
# Short definition that turns a dictionary into a csv file
def frametocsv(csvname, data):
"""Short definition that turns a dictionary into a csv file."""
frame = pd.DataFrame.from_dict(data, orient='columns')
frames = [maf.Tier, maf.Gene, frame]
file = pd.concat(frames, axis=1)
file.to_csv(csvname, index=False)
# Create the csv files
frametocsv(csvname='maf_duplicates_by_org.csv', data=dupdict)
frametocsv(csvname='maf_blanks.csv', data=nadict)
|
93691678125915703b19ce2333207405d2f5be7a | Jadams29/Coding_Problems | /Looping/Loop_Print_Odds.py | 359 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 11:48:07 2018
@author: joshu
"""
# Use for loop to iterate through list from 1 - 21
# Use modulus to check if odd or even
# Print out the odd numbers
for i in range(1, 22):
if ((i % 2) != 0):
print("i = ", i)
newlist = [i for i in range(1,22) if (i %2 != 0)]
print(newlist) |
4e3dda89d177ce3750ba96bb3817342a1f7e2c32 | papalos/geekbrains_hw | /lesson_five/lsn5_task1.py | 894 | 3.625 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
# Если есть окончание ввода, значит присутствует цикл записи
# построчный ввод видимо означает, что введенные данные в файле тоже должны отображаться построчно
# в задании не сказано, что файл должен открываться на дозапись
with open('file.gyp', 'w', encoding='utf-8') as f:
while True:
if f.write(input('Введите строку: ')):
f.write('\n')
else:
break
|
de73c99391114cb0d27a7e787219bd2d9649ad7b | Natt7/python-learning | /geekbangpython/if.py | 398 | 3.703125 | 4 | x = 'xyz'
if x == 'abc' :
print(x)
elif x =='xyz' :
print('x = xyz')
else:
print('x no equal')
chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊'
print(chinese_zodiac[-1])
print(chinese_zodiac[0:4])
year = int(input('请输入您的出生年份:'))
print(year % 12)
print(chinese_zodiac[year % 12])
if (chinese_zodiac[year % 12]) == '狗' :
print('狗年运势。。。') |
3de9b9a70e27b8e7eefafa34367be0878b6de3f7 | qetennyson/maththeme_ct18 | /ch3_data_stats/fart.py | 1,047 | 3.84375 | 4 | from collections import Counter
import csv
def read_csv(filename):
farters = []
non_farters = []
maybe_farters = []
with open(filename) as my_file:
reader = csv.reader(my_file)
next(reader)
for row in reader:
if row[2].lower() == 'yes':
farters.append(row[0])
elif row[2].lower() == 'maybe':
maybe_farters.append(row[0])
else:
non_farters.append(row[0])
return farters, maybe_farters, non_farters
farters, maybe_farters, non_farters = read_csv('fart.csv')
print(farters)
print(maybe_farters)
print(non_farters)
def show_farters(farters, maybe_farters, non_farters):
print('Farters')
for animal in farters:
print(f'{animal}')
print('\n\n')
print('Maybe Farters')
for animal in maybe_farters:
print(f'{animal}')
print('\n\n')
print('Non-Farters')
for animal in non_farters:
print(f'{animal}')
print('\n\n')
show_farters(farters, maybe_farters, non_farters) |
a792f43bd5547a57f9f68b4f96828ec125652333 | aswinzz/Simulation-Lab-Assignments | /Lab5/randomGen.py | 1,841 | 3.5625 | 4 | import time
# X(i+1) = (a*X(i) + c) % m
# Mixed Congruence Method
class Mixed:
def __init__(self):
self.a = 48271
self.m = 2147483647
self.c = 1
def generate(self,n):
# seed will be a unique number in each iteration by using current time in micro seconds
seed = (time.time()*1000)
result = []
# Generating N numbers
for i in range(n):
seed = ((self.a * seed) + self.c) % self.m
result.append(seed)
return result
# Additive Congruence Method
class Additive:
def __init__(self):
self.m = 2147483647
def generate(self,n):
increment = 1
# seed will be a unique number in each iteration by using current time in micro seconds
seed = (time.time()*1000)
result = []
# Generating N numbers
for i in range(n):
seed = (seed + increment) % self.m
result.append(seed)
return result
# Multiplicative Congruence Method
class Multiplicative:
def __init__(self):
self.a = 48271
self.m = 2147483647
self.q = 44488
self.r = 3399
def gen(self,n):
result = []
# seed will be a unique number in each iteration by using current time in micro seconds
seed = (time.time()*1000)
# Generating N numbers
for i in range(n):
seed = (seed * self.a) % self.m
result.append(seed)
return result
# number of random numbers to be generated
n = int(input())
# using Multiplicative Congruence
print("\nMultiplicative")
mult = Multiplicative()
print(mult.gen(n))
# using Additive Congruence
print("\nAdditive")
additive = Additive()
print(additive.generate(n))
# using Mixed Congruence
print("\nMixed")
mixed = Mixed()
print(mixed.generate(n))
|
677bd239bef14e5a02487e2f4feacd21cd7a3b11 | Shengjie-Sun/LeetCode | /Algorithms/226-Easy-Invert Binary Tree-[Tree].py | 990 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
else:
# root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t1 and t2:
t1.val += t2.val
if t1.left:
self.mergeTrees(t1.left, t2.left)
else:
t1.left = t2.left
if t1.right
self.mergeTrees(t1.right, t2.right)
else:
t1.right = t2.right
return t1 |
f3780142bcf1aa6590cbedaf476f6493e547d7d8 | makarov-wl24/python-getting | /lesson5-task3.py | 1,538 | 3.671875 | 4 | # Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
# Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
# Выполнить подсчет средней величины дохода сотрудников.
with open('lesson5-task3.txt', 'r+', encoding='utf-8') as file:
line = None
while line != '':
line = (input('Введите фамилию сотрудника и зарплату через пробел (для завершения введите пустую строку): '))
file.write(f'{line}\n')
file.seek(0)
workers = [line.split() for line in file if line != '\n']
print('Вы ввели следующие данные:', workers)
try:
salaries = list(map(lambda el: float(el[1]), workers))
except IndexError:
print('Необходимо вводить фамилию сотрудника и его зарплату через пробел')
except ValueError:
print('Зарплата должна представлять число')
else:
print('Средняя зарплата сотрудников:', round(sum(salaries) / len(salaries), 2))
low_salary_workers = [workers[el][0] for el in range(len(salaries)) if salaries[el] < 20000]
print('Сотрудники с ЗП < 20 000:', low_salary_workers)
|
a65e9891373333a8a6ce1fa9f6c89738a209a06b | Nicole-Bidigaray/Bootcamp-pirple.com | /Python_is_Easy/Importing/Guessing_Game_PartB.py | 626 | 3.65625 | 4 | from random import random
from time import perf_counter
randVal = random()
# print(randVal)
# time.clock() -> timevalue
# time.clock() -> timevalue2
upper = 1.0
lower = 0.0
# guess = 0.5 -> Too Low _> lower 0.5
# guess = 0.9 -> Too High -> uper 0.9
# guess = 0.5
startTime = perf_counter()
while(True):
guess = (upper + lower) / 2 # 0.5 + 0.75 -> 1.25/2 -> 0.675
if guess == randVal:
break
elif guess < randVal:
lower = guess # lower = 0.5; uppper = 1.0
else:
upper = guess # upper = 0.75
endTime = perf_counter()
print(guess)
print("It took us: ", endTime - startTime, "seconds") |
32f06af480f67cdbf9441acb54d494920c6c3f27 | ExploreNcrack/Comput496 | /assignment1/simple_board.py | 3,078 | 4.0625 | 4 | """
simple_board.py
Implements a basic Go board with functions to:
- initialize to a given board size
- check if a move is legal
- play a move
The board uses a 1-dimensional representation with padding
"""
from sys import stdout
import numpy as np
from board_util import GoBoardUtil, BLACK, WHITE, EMPTY, BORDER, \
PASS, is_black_white, coord_to_point, where1d, MAXSIZE
class SimpleGoBoard(object):
def get_color(self, point):
return self.board[point]
def pt(self, row, col):
return coord_to_point(row, col, self.size)
def is_legal(self, point, color):
"""
Check whether it is legal for color to play on point
"""
board_copy = self.copy()
# Try to play the move on a temporary copy of board
# This prevents the board from being messed up by the move
legal = board_copy.play_move(point, color)
return legal
def get_empty_points(self):
"""
Return:
The empty points on the board
"""
return where1d(self.board == EMPTY)
def __init__(self, size):
"""
Creates a Go board of given size
"""
# validate the input for size
assert 2 <= size <= MAXSIZE
# initialize attribute and board
self.reset(size)
def reset(self, size):
"""
Creates a start state, an empty board with the given size
The board is stored as a one-dimensional array
See GoBoardUtil.coord_to_point for explanations of the array encoding
"""
self.size = size
self.NS = size + 1
self.WE = 1
self.current_player = BLACK
self.maxpoint = size * size + 3 * (size + 1)
self.board = np.full(self.maxpoint, BORDER, dtype = np.int32)
self._initialize_empty_points(self.board)
def copy(self):
b = SimpleGoBoard(self.size)
assert b.NS == self.NS
assert b.WE == self.WE
b.current_player = self.current_player
assert b.maxpoint == self.maxpoint
b.board = np.copy(self.board)
return b
def row_start(self, row):
assert row >= 1
assert row <= self.size
return row * self.NS + 1
def _initialize_empty_points(self, board):
"""
Fills points on the board with EMPTY
Argument
---------
board: numpy array, filled with BORDER
"""
for row in range(1, self.size + 1):
start = self.row_start(row)
board[start : start + self.size] = EMPTY
def play_move(self, point, color):
"""
Play a move of color on point
Returns boolean: whether move was legal
"""
assert is_black_white(color)
# Special cases
if point == PASS:
self.ko_recapture = None
self.current_player = GoBoardUtil.opponent(color)
return True
elif self.board[point] != EMPTY:
return False
self.board[point] = color
return True
|
725e47721e379e8a38314baca93a98d58c88df2d | malk321/master-python | /nihongo o benkyoshimashô/kanjis.py | 6,403 | 3.625 | 4 | # -*- coding : utf-8 -*-
from PIL import Image
from random import randrange
from math import ceil
import sys
import psutil
# We ask the player what mode he wants to play
mode = 0
romajis_file = open("romajis.txt",'r')
menu_flag = 1
while (menu_flag == 1) :
while (mode != 1 and mode != 2 and mode != 3 and mode != 4 and mode != 5) :
print("\n\n\n\n##############################\n" + "## ##\n" + "## kanji o benkyôshimashô ##\n" +"## ##\n" + "##############################\n")
print("Choose a game mode\n\n1. From kanjis to romajis\n2. From romajis to kanjis\n3. Reading mode\n4. Writing mode\n\n5. Exit\n")
mode = int(input())
# Exit
if (mode == 5) :
menu_flag = 0
romajis_file.close()
sys.exit()
rounds = 0
while (rounds <= 0) :
print("How many rounds do you want to play ?")
rounds = int(input())
score = 0
rounds_copy = rounds
romajis_list = str(romajis_file.read()).split(" ")
while (rounds > 0) :
# Then we choose a kanji and its romaji transcription for him
i = randrange(len(romajis_list))
romajis = romajis_list[i]
flag = 0
for elt in romajis :
if (elt == "-") :
flag = 1
if (flag == 1) :
romajis = romajis.split("-")
I = i + 1
kanji = Image.open("%s.jpg"%I)
answer = str()
# The player can now play
# 1st mode
if (mode == 1) :
print("Enter one of the possible readings of the following kanji\n")
kanji.show(command = "eog")
answer = str(input())
k = 0
if (flag == 1) :
for elt in romajis :
if (elt == answer) :
k += 1
else :
if (romajis == answer) :
k += 1
if k != 0 :
score += 1
print("\nRight\n\n")
else :
print("\nWrong\n\n")
kanji.close()
# 2nd mode
if (mode == 2) :
j = i
k = i
while (j == i) :
j = randrange(len(romajis_list))
while (k == i) :
k = randrange(len(romajis_list))
J = j + 1
K = k + 1
kanji_j = Image.open("%s.jpg"%J)
kanji_k = Image.open("%s.jpg"%K)
if (flag == 1) :
print("Enter the number of the kanji corresponding to the following readings\n" + ", ".join(romajis) + "\n")
else :
print("Enter the number of the kanji corresponding to the following reading\n" + romajis + "\n")
if (i <= j) :
if (j <= k) :
kanji.show(command = "eog")
kanji_j.show(command = "eog")
kanji_k.show(command = "eog")
elif (k >= i) :
kanji.show(command = "eog")
kanji_k.show(command = "eog")
kanji_j.show(command = "eog")
elif (k <= i) :
kanji_k.show(command = "eog")
kanji.show(command = "eog")
kanji_j.show(command = "eog")
else :
if (j >= k) :
kanji_k.show(command = "eog")
kanji_j.show(command = "eog")
kanji.show(command = "eog")
elif( i <= k) :
kanji_j.show(command = "eog")
kanji.show(command = "eog")
kanji_k.show(command = "eog")
elif( i >= k ) :
kanji_j.show(command = "eog")
kanji_k.show(command = "eog")
kanji.show(command = "eog")
answer = int(input())
if answer == I :
score += 1
print("\nRight\n")
else :
print("\nWrong\n")
# 3rd mode
if (mode == 3) :
meaning_file = open("meaning.txt",'r')
meaning_list = str(meaning_file.read()).split(" ")
meaning = meaning_list[i]
flag = 0
flag2 = 0
for elt in meaning :
if (elt == "-") :
flag = 1
if (elt == "_") :
flag2 = 1
if (flag == 1) :
meaning = meaning.split("-")
for elt in meaning :
if (flag2 == 1) :
elt = " ".join(elt.split("_"))
else :
if (flag2 == 1) :
meaning = " ".join(meaning.split("_"))
kanji.show(command = "eog")
print("Enter one of the possible meaning of the following kanji\n")
answer = str(input())
correct_flag = 0
if (flag == 1) :
for elt in meaning :
if (elt == answer) :
correct_flag += 1
else :
if (answer == meaning) :
correct_flag += 1
if (correct_flag == 0) :
print("\nWrong\n\n")
else :
score += 1
print("\nRight\n\n")
# 4th mode
if (mode == 4) :
meaning_file = open("meaning.txt",'r')
meaning_list = str(meaning_file.read()).split(" ")
meaning = meaning_list[i]
flag = 0
flag2 = 0
for elt in meaning :
if (elt == "-") :
flag = 1
if (elt == "_") :
flag2 = 1
if (flag == 1) :
meaning = meaning.split("-")
for elt in meaning :
if (flag2 == 1) :
elt = " ".join(elt.split("_"))
else :
if (flag2 == 1) :
meaning = " ".join(meaning.Split("_"))
j = i
k = i
while (j == i) :
j = randrange(len(romajis_list))
while (k == i) :
k = randrange(len(romajis_list))
J = j + 1
K = k + 1
kanji_j = Image.open("%s.jpg"%J)
kanji_k = Image.open("%s.jpg"%K)
if (i <= j) :
if (j <= k) :
kanji.show(command = "eog")
kanji_j.show(command = "eog")
kanji_k.show(command = "eog")
elif (k >= i) :
kanji.show(command = "eog")
kanji_k.show(command = "eog")
kanji_j.show(command = "eog")
elif (k <= i) :
kanji_k.show(command = "eog")
kanji.show(command = "eog")
kanji_j.show(command = "eog")
else :
if (j >= k) :
kanji_k.show(command = "eog")
kanji_j.show(command = "eog")
kanji.show(command = "eog")
elif( i <= k) :
kanji_j.show(command = "eog")
kanji.show(command = "eog")
kanji_k.show(command = "eog")
elif( i >= k ) :
kanji_j.show(command = "eog")
kanji_k.show(command = "eog")
kanji.show(command = "eog")
if (flag == 1) :
print("Enter the number of the kanji corresponding to the following meanings\n" + ", ".join(meaning))
else :
print("Enter the number of the kanji corresponding to the following meaning\n" + meaning + "\n")
answer = int(input())
if (answer != I):
print("\nWrong\n\n")
else :
score += 1
print("\nRight\n\n")
for proc in psutil.process_iter() :
if (proc.name() == "display") :
proc.kill()
rounds -= 1
# The game is over
score = ceil(score*1000/rounds_copy)/10
if score < 20 :
print("VERY POOR\n")
elif score < 40 :
print("POOR\n")
elif score < 60 :
print("AVERAGE\n")
elif score < 80 :
print("GOOD\n")
else :
print("EXCELLENT\n")
print("Score : %d\n"%score)
mode = 0
menu_flag = 1
|
5c24d9a8eb608de6f56bee8411cd61ca20337ea8 | rdoyama/coding | /minefield/play.py | 2,937 | 3.9375 | 4 | # import pygame
# import sys
# # initializing the constructor
# pygame.init()
# # screen resolution
# res = (720,720)
# # opens up a window
# screen = pygame.display.set_mode(res)
# # white color
# color = (255,255,255)
# # light shade of the button
# color_light = (170,170,170)
# # dark shade of the button
# color_dark = (100,100,100)
# # stores the width of the
# # screen into a variable
# width = screen.get_width()
# # stores the height of the
# # screen into a variable
# height = screen.get_height()
# # defining a font
# smallfont = pygame.font.SysFont('Corbel',35)
# # rendering a text written in
# # this font
# text = smallfont.render('quit' , True , color)
# while True:
# for ev in pygame.event.get():
# if ev.type == pygame.QUIT:
# pygame.quit()
# #checks if a mouse is clicked
# if ev.type == pygame.MOUSEBUTTONDOWN:
# #if the mouse is clicked on the
# # button the game is terminated
# if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
# pygame.quit()
# # fills the screen with a color
# screen.fill((60,25,60))
# # stores the (x,y) coordinates into
# # the variable as a tuple
# mouse = pygame.mouse.get_pos()
# # if mouse is hovered on a button it
# # changes to lighter shade
# if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
# pygame.draw.rect(screen,color_light,[width/2,height/2,140,40])
# else:
# pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40])
# # superimposing the text onto our button
# screen.blit(text , (width/2+50,height/2))
# # updates the frames of the game
# pygame.display.update()
import pygame as pg
pg.init()
def flip_color():
global bg_white
bg_white = not bg_white
class Button:
def __init__(self, rect, command):
self.color = (255,0,0)
self.rect = pg.Rect(rect)
self.image = pg.Surface(self.rect.size)
self.image.fill(self.color)
self.command = command
def render(self, screen):
screen.blit(self.image, self.rect)
def get_event(self, event):
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
if self.rect.collidepoint(pg.mouse.get_pos()):
self.command()
screen = pg.display.set_mode((800,600))
screen_rect = screen.get_rect()
running = True
bg_white = False
btn = Button((10,10,105,25), flip_color)
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
btn.get_event(event)
if bg_white:
screen.fill((255,255,255))
else:
screen.fill((0,0,0))
btn.render(screen)
pg.display.update() |
638109ba0649efa4a09a249fb751a93c4006c99f | alexandraback/datacollection | /solutions_2449486_0/Python/OverlordAlex/lawnmowing.py | 855 | 3.5625 | 4 | import numpy as np
cases = int(raw_input())
for case in range(cases):
r, c = map(int, raw_input().strip().split())
board = []
done = False
if (r==1) or (c==1):
print "Case #"+str(case+1)+": YES"
done = True
for i in range(r):
row = map(int, raw_input().strip().split())
board.append(row)
if (done): continue
board=np.array(board)
row_maxes = [max(board[i,:]) for i in range(r)]
column_maxes = [max(board[:,i]) for i in range(c)]
for i in range(r):
if (done): break
rmax = row_maxes[i]
for j in range(c):
# find min,pos in row
cmax = column_maxes[j]
#if (board[i][j]==cmax)or(board[i][j]==rmax):
# pass
# # still fine
if (board[i][j]<cmax)and(board[i][j]<rmax):
print "Case #"+str(case+1)+": NO"
done = True
break
if (not done):
print "Case #"+str(case+1)+": YES"
done = True
|
b3ec832ae421fcdb13b36eea7f47f325cdca5323 | klassen-software-solutions/pyutil | /kss/util/strings.py | 488 | 4.0625 | 4 | """Misc. string related utilities."""
def remove_prefix(text: str, prefix: str) -> str:
"""Removes the prefix from the string if it exists, and returns the result."""
if text.startswith(prefix):
return text[len(prefix):]
return text
def remove_suffix(text: str, suffix: str) -> str:
"""Removes the suffix from the string if it exists, and returns the result."""
if suffix != "" and text.endswith(suffix):
return text[:-len(suffix)]
return text
|
47299882939de8ed348daa90c857fc8424aa7624 | Aditya7861/Self | /guess_game.py | 605 | 3.984375 | 4 | import random
original_num = random.randint(2,89)
print(original_num)
def guess_checker(count):
user_guess = int(input("Enter your guess no:-"))
if(user_guess < original_num):
print("Your guess Number is low")
count = count +1
guess_checker(count)
elif(user_guess > original_num):
print("your guess Number is High")
count = count +1
guess_checker(count)
elif(user_guess == original_num):
print("You Guessed Corect number")
print("Yout took these turn {} to correct guess".format(count))
exit
guess_checker(count =0)
|
e228d61643136143614b333cdfbca9705020e082 | PeriGK/DeepLearningND | /NeuralNetworksIntro/KerasIntro/keras_imdb.py | 3,659 | 3.6875 | 4 |
# coding: utf-8
# # Analyzing IMDB Data in Keras
# Imports
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
# get_ipython().run_line_magic('matplotlib', 'inline')
np.random.seed(42)
# ## 1. Loading the data
# This dataset comes preloaded with Keras, so one simple command will get us training and testing data. There is a parameter for how many words we want to look at. We've set it at 1000, but feel free to experiment.
# Loading the data (it's preloaded in Keras)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=1000)
print(x_train.shape)
print(x_test.shape)
# ## 2. Examining the data
# Notice that the data has been already pre-processed, where all the words have numbers, and the reviews come in as a vector with the words that the review contains. For example, if the word 'the' is the first one in our dictionary, and a review contains the word 'the', then there is a 1 in the corresponding vector.
#
# The output comes as a vector of 1's and 0's, where 1 is a positive sentiment for the review, and 0 is negative.
print(x_train[0])
print(y_train[0])
# ## 3. One-hot encoding the output
# Here, we'll turn the input vectors into (0,1)-vectors. For example, if the pre-processed vector contains the number 14, then in the processed vector, the 14th entry will be 1.
# One-hot encoding the output into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0])
# And we'll also one-hot encode the output.
# One-hot encoding the output
num_classes = 2
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape)
print(y_test.shape)
# ## 4. Building the model architecture
# Build a model here using sequential. Feel free to experiment with different layers and sizes! Also, experiment adding dropout to reduce overfitting.
# TODO: Build the model architecture
# TODO: Compile the model using a loss function and an optimizer.
model = Sequential()
model.add(Dense(12, activation='relu', input_dim=1000))
model.add(Dropout(.2))
model.add(Dense(num_classes, activation='sigmoid'))
model.compile(loss = 'mean_squared_error', optimizer='rmsprop', metrics=['accuracy'])
# Building the model architecture with one layer of length 100
# model = Sequential()
# model.add(Dense(512, activation='relu', input_dim=1000))
# model.add(Dropout(0.5))
# model.add(Dense(num_classes, activation='softmax'))
# model.summary()
# # Compiling the model using categorical_crossentropy loss, and rmsprop optimizer.
# model.compile(loss='categorical_crossentropy',
# optimizer='rmsprop',
# metrics=['accuracy'])
# ## 5. Training the model
# Run the model here. Experiment with different batch_size, and number of epochs!
#
# TODO: Run the model. Feel free to experiment with different batch sizes and number of epochs.
model.fit(x_train, y_train, epochs=1000, verbose=0)
# # Running and evaluating the model
# hist = model.fit(x_train, y_train,
# batch_size=32,
# epochs=10,
# validation_data=(x_test, y_test),
# verbose=2)
# ## 6. Evaluating the model
# This will give you the accuracy of the model, as evaluated on the testing set. Can you get something over 85%?
score = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: ", score[1])
|
f969889b844219a7a351c7f595ada2d5cd1841cb | mapozhidaeva/other | /Test_yourself_before_exam/Guess_TERM.py | 1,250 | 3.765625 | 4 | import random
def file_reading(filename):
with open(filename, 'r') as f:
return f.read().split('\n')
terminology = file_reading('Terminology.tsv')
definitions = file_reading('Definitions.tsv')
the_dictionary = dict(zip(terminology, definitions))
print ('Let\'s start the test! (press Enter to end the game)')
print (len(terminology), len(definitions))
answer = 1
while answer != '':
random_term = random.choice(list(the_dictionary.keys()))
print ('\n', the_dictionary[random_term] + ':\n')
one = random.choice(list(the_dictionary.keys()))
while one == random_term:
one = random.choice(list(the_dictionary.keys()))
two = random.choice(list(the_dictionary.keys()))
while two == one or two == random_term:
two = random.choice(list(the_dictionary.keys()))
answers = [random_term, one, two]
right_answer = random_term
random.shuffle(answers)
n = 1
for i in answers:
print ('{}) '.format(n), i, '\n')
n += 1
answer = int(input('Введите ответ: 1, 2 или 3: '))
if right_answer == answers[int(answer) - 1]:
print ('Правильно')
else:
print ('Неверно! Правильный ответ - ', random_term) |
434b60b1dee69da6a2cabe16a577576652745ae1 | zhangler1/leetcodepractice | /哈希表/hash/Group Anagrams49.py | 684 | 3.828125 | 4 | from typing import List,Dict,Tuple
from collections import defaultdict
#python的 list不可hash 必须
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
charCounter=[0]*26
groupdict:Dict[Tuple,List]=defaultdict(list)
for word in strs:
for char in word:
codepoint=ord(char)-ord("a")
charCounter[codepoint]+=1
groupdict[tuple(charCounter)].append(word)
charCounter=[0]*26
return [ groupdict[a] for a in groupdict]
if __name__ == '__main__':
print(Solution().groupAnagrams(["eat","tea","tan","ate","nat","bat"])) |
69d31a0468da80740486fa058f67b4814a97b06b | mbadayil/Ilm | /Insertion_Point.py | 209 | 3.71875 | 4 | def InsPoint(nums, target):
if target in nums:
return nums.index(target)
j=len(nums)-1
for i in range(0,j):
if nums[i]>=target:
return i
print(InsPoint([1,2,5,6],0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.