blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
6df26dde295f7469571316d03b5897b470c9d5ce | jaymax01/web_scraping | /scraping world population table/table_scraping.py | 1,071 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 21:46:11 2021
@author: Max
"""
# Importing libraries for reqesting HTML and scraping the data
import pandas as pd
import requests
from bs4 import BeautifulSoup
# Loading the worldmeters population table and its HTML
url = 'https://www.worldometers.info/world-population/'
page = requests.get(url)
#print(page)
# Parsing the HTML tags for the table
soup = BeautifulSoup(page.text, 'lxml')
#print(soup)
# Finding the HTML tags for the rows of data
table = soup.find('table', class_ = 'table table-striped table-bordered table-hover table-condensed table-list' )
#print(table)
# Storing the table headers in a list
headers = []
for i in table.find_all('th'):
headers.append(i.text)
# Putting all of the other data rows into a dataframe
df = pd.DataFrame(columns=headers)
for i in table.find_all('tr')[1:]:
row = i.find_all('td')
row_list = [j.text for j in row]
df.loc[len(df)] = row_list
# Saving the table as a csv file
df.to_csv('C:/Users/Max/Desktop/web scraping course/table_scraped.csv')
|
1e54ffb0b9b6a4643d5014a5311d394b5d58fbee | 690/Runetrader | /tools/utils.py | 934 | 3.546875 | 4 | from ast import literal_eval
import random
import numpy as np
def random_position(x1, y1, x2, y2):
""" Return a random (x, y) coordinate from a square """
return random.randint(x1, x2), random.randint(y1, y2)
def dynamic_coordinate_converter(parent, child, operator):
if operator == '-':
return [child[0] - parent[0], child[1] - parent[1], child[2], child[3]]
else:
child = literal_eval(child)
return child[0] + parent[0], child[1] + parent[1], child[2], child[3]
def blockshaped(arr, nrows, ncols):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size
If arr is a 2D array, the returned array should look like n subblocks with
each subblock preserving the "physical" layout of arr.
"""
h, w = arr.shape
return (arr.reshape(h//nrows, nrows, -1, ncols)
.swapaxes(1,2)
.reshape(-1, nrows, ncols)) |
c6145249ef56fe9890f142f597766fdb55200466 | Ahmad-Saadeh/calculator | /calculator.py | 810 | 4.125 | 4 | def main():
firstNumber = input("Enter the first number: ")
secondNumber = input("Enter the second number: ")
operation = input("Choose one of the operations (*, /, +, -) ")
if firstNumber.isdigit() and secondNumber.isdigit():
firstNumber = int(firstNumber)
secondNumber = int(secondNumber)
if operation == "*":
print("The answer is {}".format(firstNumber * secondNumber))
elif operation == "/":
print("The answer is {}".format(firstNumber / secondNumber))
elif operation == "+":
print("The answer is {}".format(firstNumber + secondNumber))
elif operation == "-":
print("The answer is {}".format(firstNumber - secondNumber))
else:
print("Invalid Operation!")
else:
print("Invalid Numbers!")
if __name__ == '__main__':
main()
|
1145f9426e46a217bbe2a7f8618eef9beb963028 | skuxy/ProjectEuler | /problem17.py | 2,579 | 3.90625 | 4 | #! /usr/bin/env python
"""
If the numbers 1 to 5 are written out in words:
one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand)
inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens.
For example, 342 (three hundred and forty-two) contains 23 letters and
115 (one hundred and fifteen) contains 20 letters.
The use of "and" when writing out numbers is in compliance with British usage.
"""
from math import floor
NUMBER_TO_WORD_MAP = {
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: "twenty",
30: "thirty",
40: "fourty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety",
100: "hundred",
1000: "thousand"
}
class NumberToWord:
def __init__(self, number):
self.number = number
@staticmethod
def _single_digit(number):
return NUMBER_TO_WORD_MAP[number]
@staticmethod
def _two_digits(number):
if number < 20:
return NUMBER_TO_WORD_MAP[number]
if number % 10 == 0:
return NUMBER_TO_WORD_MAP[number]
decade, single = [int(x) for x in str(number)]
decade *= 10
return "{} {}".format(NUMBER_TO_WORD_MAP[decade], NUMBER_TO_WORD_MAP[single])
def _three_digits(self, number):
if number % 100 == 0:
determinator = int(number/100)
return "{} {}".format(NUMBER_TO_WORD_MAP[determinator], NUMBER_TO_WORD_MAP[100])
hundred_part = floor(number/100)
the_rest = int(str(number)[1:])
return "{} hundred and {}".format(
NUMBER_TO_WORD_MAP[hundred_part],
self._two_digits(the_rest)
)
def get_word(self):
if self.number < 10:
return self._single_digit(self.number)
if self.number < 100:
return self._two_digits(self.number)
if self.number < 1000:
return self._three_digits(self.number)
if self.number == 1000:
return "one " + NUMBER_TO_WORD_MAP[1000] # Ok I'm lazy
sum_str = ""
for a in range(1, 6):
h = NumberToWord(a)
t = h.get_word()
t = ''.join(t.split())
print(t)
sum_str += t
print(len(sum_str))
|
10307facddb2c1bbdd074b4212026f24e7e7b7b3 | skuxy/ProjectEuler | /Problem5.py | 718 | 3.921875 | 4 | # Project Euler: Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# worst.function.name.ever.
def n_evenly_divisible_by_n_to_check(n, n_to_check=20):
for i in range(1, n_to_check + 1):
if n % i != 0:
return False
return True
# Answer: 232792560
# to optimize, check only every 20th number, beginning with 20 :)
if __name__ == "__main__":
number = 20
while not n_evenly_divisible_by_n_to_check(number):
number += 20
print("Number evenly divisible by all number from 1 to 20 is " + str(number))
|
4370c07de04f74ab6b193353c651208359fd7402 | EricSchles/stanford_algo_class | /first_pass/assignment_two/part_one.py | 914 | 3.921875 | 4 | def class_qsort(alist):
left = 0
right = len(alist)-1
while left < right:
mid = (right - left)//2
partition(alist,left,mid)
partition(alist,mid+1,right)
def quick_sort(alist):
if len(alist) <= 1:
return alist, 0
else:
less = []
equal = []
greater = []
pivot = alist[0]
for i in alist:
if i < pivot:
less.append(i)
elif i == pivot:
equal.append(i)
else:
greater.append(i)
new_less,left_count = quick_sort(less)
new_greater, right_count = quick_sort(greater)
left_count += len(less)
right_count += len(greater)
return new_less+equal+new_greater,left_count+right_count
with open("QuickSort_num.txt","r") as f:
arr = f.read().split("\n")
print(len(arr))
_,count = quick_sort(arr)
print(count)
|
3ae8822e763883c09c6dd49325ec331874cf09c7 | josephine151/josephine151.github.io | /python/instructions.py | 982 | 4.09375 | 4 | from random import *
# list of first and last names
names = ["faith", "kathy", "sara", "aleef", "jesus", "lenny"]
last_names = ["smith", "johnson", "duggan", "doe", "riley", "brown"]
# list of names already used
names_used = []
last_names_used = []
#generate all names
for x in range(len(names)):
# get 2 random numbers
random_num1 = randint(0, len(names) - 1)
random_num2 = randint(0, len(last_names) - 1)
# get the name @randomnum index
random_first = names[random_num1]
random_last = last_names[random_num2]
# if random first name was used, pick another
while random_first in names_used:
random_first = names[randint(0, len(names) - 1)]
#if random last name was used, pick another
while random_last in last_names_used:
random_last = last_names[randint(0, len(last_names) - 1)]
# add the names used to their lists
names_used.append(random_first)
last_names_used.append(random_last)
# print the name
print(random_first + " " + random_last)
|
e90d473af4c3813c79b79a197137c95dd0144c6f | hgunawan/python_data_structures | /binary_search/binary_search.py | 1,054 | 4.03125 | 4 | def binary_search0(input_array, value):
"""Your code goes here."""
length = len(input_array)/2
current_index = length
while length > 0:
length = length/2
# print(current_index)
current_value = input_array[current_index]
if(current_value==value):
return current_value
elif(current_value<value):
# print("+")
current_index+=length
elif(current_value>value):
# print("-")
current_index-=length
return -1
def binary_search(input_array, value):
"""Your code goes here."""
low = 0
high = len(input_array)-1
while low <= high:
mid = (low+high)//2
if input_array[mid] == value:
return mid
elif input_array[mid] < value:
low=mid+1
else:
high=mid-1
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print(binary_search(test_list, test_val1))
print(binary_search(test_list, test_val2)) |
04e5e4d754215941401cb1ed5d6446adbdeea7de | Lunreth/pyleecan | /pyleecan/Methods/Output/Output/getter/get_machine_periodicity.py | 1,096 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from math import gcd
def get_machine_periodicity(self):
"""Return / Compute the (anti)-periodicities of the machine in time and space domain
Parameters
----------
self : Output
An Output object
Returns
-------
per_a : int
Number of space periodicities of the machine
is_antisym_a : bool
True if an anti-periodicity is possible after the space periodicities
per_t : int
Number of time periodicities of the machine
is_antisym_t : bool
True if an anti-periodicity is possible after the time periodicities
"""
if (
self.geo.per_a is None
or self.geo.is_antiper_a is None
or self.geo.per_t is None
or self.geo.is_antiper_t is None
):
(
self.geo.per_a,
self.geo.is_antiper_a,
self.geo.per_t,
self.geo.is_antiper_t,
) = self.simu.machine.comp_periodicity()
return (
self.geo.per_a,
self.geo.is_antiper_a,
self.geo.per_t,
self.geo.is_antiper_t,
)
|
9c29aab8e0246210cfe7d562e3a49c42790807c1 | jdowzell/Thesis | /header_check.py | 947 | 3.6875 | 4 | def areAllHeadersPresent(heads):
"""
A function to make sure that all headers required for plotting a Light Curve
are present, and alert the user if any are missing (and which ones).
Input parameter (heads) should be of the form: heads=fits.getheader("file.fits")
"""
# Generic Flag
allgood = True
# List of needed headers
neededHeaders = ['TEFF', 'LOGG', 'TESSMAG',
'TPERIOD', 'TDUR', 'TEPOCH', 'TDEPTH',
'TIME', 'PHASE', 'LC_INIT', 'MODEL_INIT']
# Loop through all headers and see if they are present using a Try/Except block
for i in range (len(neededHeaders)):
try:
heads[neededHeaders[i]]
except:
#print("Header {} not present!".format(neededHeaders[i]))
allgood = False
#else:
# print("{}: {}".format(neededHeaders[i], heads[neededHeaders[i]]))
return allgood
|
ab2c78b99d9943f51e24159e297f5ecc43b412af | Jamlet/python | /ejer1.py | 109 | 3.6875 | 4 | num1 = input("Año nacimiento: ")
num2 = input("Año actual: ")
print("Tu edad es: " + str(num2 - num1))
|
a77a7070703a6fa7456b19e0d71887faeb1aa6f8 | wilber-guy/Project-Euler | /4_Largest_palindrome_product.py | 248 | 3.59375 | 4 | largest_num = 0
for i in range(1,1000):
num = i
for p in range(1,1000):
total = num * p
if total > largest_num:
if str(total) == str(total)[::-1]:
largest_num = total
print(largest_num)
|
5f0d32469ffa9391088cbbe715b209ee3211c466 | jngo102/ECE_203_Project | /main.py | 10,788 | 3.78125 | 4 | from Tkinter import *
import os
import pickle
# Class definition for main map
class Game:
def __init__(self, root):
self.root = root
self.root.title("Space Exploration")
self.canvas = Canvas(self.root, width=1280, height=720)
self.canvas.pack()
# Booleans that will be toggled based on mouse cursor position
self.BaofengGame = False
self.JasonGame = False
self.KathrinaGame = False
self.MohammadGame = False
self.RyanGame = False
self.cursorPos = 500 # Position of cursor when entering player name
self.playerName = [] # List of individual characters when entering player name
self.playerNameCanvas = [] # List of letters on canvas when entering player name
self.FPS = 60 # Number of frames per second that loop() function will run
self.lastIndex = -1 # Initial value of index that changes as player enters/deletes characters in name entry
# Initialization of background, background image, and background animation frame
self.backgroundImage = PhotoImage(file="images/comet/0.gif")
self.background = self.canvas.create_image(0, 0, image=self.backgroundImage, anchor='nw')
self.backgroundFrame = 0
# Initialization of Mercury, Mercury image, and Mercury animation frame
self.MercuryImage = PhotoImage(file="images/Mercury/0.gif")
self.Mercury = self.canvas.create_image(150, 150, image=self.MercuryImage)
self.MercuryFrame = 0
# Initialization of moons, moons image, and moons animation frame
self.moonsImage = PhotoImage(file="images/moons/0.gif")
self.moons = self.canvas.create_image(700, 250, image=self.moonsImage)
self.moonsFrame = 0
# Initialization of Neptune, Neptune image, and Neptune animation frame
self.NeptuneImage = PhotoImage(file="images/Neptune/0.gif")
self.Neptune = self.canvas.create_image(300, 500, image=self.NeptuneImage)
self.NeptuneFrame = 0
# Initialization of rocky, rocky image, and rocky animation frame
self.rockyImage = PhotoImage(file="images/rocky/0.gif")
self.rocky = self.canvas.create_image(1000, 550, image=self.rockyImage)
self.rockyFrame = 0
# Initialization of wormhole, wormhole image, and wormhole animation frame
self.wormholeImage = PhotoImage(file="images/wormhole/0.gif")
self.wormhole = self.canvas.create_image(1100, 200, image=self.wormholeImage)
self.wormholeFrame = 0
# Sets leaderboard text at bottom center of map; includes Boolean that toggles when mouse hovers over text
self.leaderboardText = self.canvas.create_text(640, 700, text="Leaderboard", fill='white', font=('Roboto', 20))
self.leaderboardOn = False
# Warning text used to tell players if their name is too long or not long enough
self.warningText = self.canvas.create_text(640, 500, text="", fill='white', font=('Roboto', 18))
self.canvas.itemconfig(self.warningText, state=HIDDEN)
# Text that tells player to enter name
self.namePrompt = self.canvas.create_text(300, 360, text="Enter your name:", fill='white', font=('Roboto', 24))
# Key bindings for entering/deleting characters when typing name and submitting it
self.root.bind('<Key>', self.enter_name)
self.root.bind('<BackSpace>', self.backspace)
self.root.bind('<Return>', self.start)
# Function bound to <BackSpace> event
def backspace(self, event):
if len(self.playerNameCanvas) > 0:
self.canvas.delete(self.playerNameCanvas[self.lastIndex])
del self.playerNameCanvas[self.lastIndex]
del self.playerName[self.lastIndex]
self.lastIndex -= 1
self.cursorPos -= 25
# Function bound to <Button-1> event
def click(self, event):
if os.name == 'nt':
prefix = ''
elif os.name == 'posix':
prefix = 'python '
if self.BaofengGame:
os.system('%sShipShipRevolution.py' % prefix)
elif self.JasonGame:
os.system('%sSpaceShooter.py' % prefix)
elif self.KathrinaGame:
os.system('%sAsteroidClicker.py' % prefix)
elif self.MohammadGame:
os.system('%sResourceQuest.py' % prefix)
elif self.RyanGame:
os.system('%sMultipleChoiceQuestions.py' % prefix)
elif self.leaderboardOn:
self.display_leaderboard()
# Leaderboard window opens when "Leaderboard" text on map is clicked on
def display_leaderboard(self):
self.leaderboard = Tk()
self.leaderboard.title("Leaderboard")
playerData = pickle.load(open("data/leaderboard.txt", 'rb'))
playerData.sort(key=lambda list: list[1], reverse=True)
Label(self.leaderboard, text="Leaderboard").grid(row=0, columnspan=2)
Label(self.leaderboard, text="Player").grid(row=1, column=0)
Label(self.leaderboard, text="Score").grid(row=1, column=1)
Label(self.leaderboard, text="-=-=-=-=-=-=-=-=-=-=-=-=-").grid(row=2, columnspan=2)
for player in playerData:
i = playerData.index(player)
playerName = player[0]
playerScore = player[1]
nameLabel = Label(self.leaderboard, text=playerName)
nameLabel.grid(row=i+3, column=0)
scoreLabel = Label(self.leaderboard, text=playerScore)
scoreLabel.grid(row=i+3, column=1)
if playerName == self.playerName:
nameLabel.config(font=('bold'))
scoreLabel.config(font=('bold'))
# Function bound to <Key> event
def enter_name(self, event):
if self.cursorPos >= 750:
self.canvas.itemconfig(self.warningText, text="You've reached the character limit.", state=NORMAL)
else:
if event.char.isalnum():
self.letter = self.canvas.create_text(self.cursorPos, 360, text=event.char, fill='white', font=('Roboto', 24))
self.playerNameCanvas.append(self.letter)
self.playerName.append(event.char)
self.cursorPos += 25
self.lastIndex += 1
# Function that loops to animate canvas objects
def loop(self):
self.backgroundFrame += 1
if self.backgroundFrame == len(os.listdir("images/comet")):
self.backgroundFrame = 0
self.backgroundImage = PhotoImage(file="images/comet/%d.gif" % self.backgroundFrame)
self.canvas.itemconfig(self.background, image=self.backgroundImage)
self.MercuryFrame += 1
if self.MercuryFrame == len(os.listdir("images/Mercury")):
self.MercuryFrame = 0
self.MercuryImage = PhotoImage(file="images/Mercury/%d.gif" % self.MercuryFrame)
self.canvas.itemconfig(self.Mercury, image=self.MercuryImage)
self.moonsFrame += 1
if self.moonsFrame == len(os.listdir("images/moons")):
self.moonsFrame = 0
self.moonsImage = PhotoImage(file="images/moons/%d.gif" % self.moonsFrame)
self.canvas.itemconfig(self.moons, image=self.moonsImage)
self.NeptuneFrame += 1
if self.NeptuneFrame == len(os.listdir("images/Neptune")):
self.NeptuneFrame = 0
self.NeptuneImage = PhotoImage(file="images/Neptune/%d.gif" % self.NeptuneFrame)
self.canvas.itemconfig(self.Neptune, image=self.NeptuneImage)
self.rockyFrame += 1
if self.rockyFrame == len(os.listdir("images/rocky")):
self.rockyFrame = 0
self.rockyImage = PhotoImage(file="images/rocky/%d.gif" % self.rockyFrame)
self.canvas.itemconfig(self.rocky, image=self.rockyImage)
self.wormholeFrame += 1
if self.wormholeFrame == len(os.listdir("images/wormhole")):
self.wormholeFrame = 0
self.wormholeImage = PhotoImage(file="images/wormhole/%d.gif" % self.wormholeFrame)
self.canvas.itemconfig(self.wormhole, image=self.wormholeImage)
self.root.after(1000/self.FPS, self.loop)
# Function bound to <Motion> event
def navigate(self, event):
if 40 <= event.x <= 260 and 35 <= event.y <= 265:
self.BaofengGame = True
elif 1020 <= event.x <= 1180 and 115 <= event.y <= 280:
self.JasonGame = True
elif 550 <= event.x <= 865 and 100 <= event.y <= 415:
self.KathrinaGame = True
elif 200 <= event.x <= 500 and 300 <= event.y <= 600:
self.MohammadGame = True
elif 920 <= event.x <= 1090 and 465 <= event.y <= 635:
self.RyanGame = True
elif 560 <= event.x <= 720 and 690 <= event.y <= 710:
self.canvas.itemconfig(self.leaderboardText, fill='red', font=('Roboto', 24))
self.leaderboardOn = True
else:
self.BaofengGame, self.JasonGame, self.KathrinaGame, self.MohammadGame,\
self.RyanGame, self.leaderboardOn = False, False, False, False, False, False
self.canvas.itemconfig(self.leaderboardText, fill='white', font=('Roboto', 20))
# Configuration of various canvas objects and player variables
def start(self, event):
if len(self.playerName) == 0:
self.canvas.itemconfig(self.warningText, text="You must have at least one character for your name.", state=NORMAL)
else:
try:
playerData = pickle.load(open("data/leaderboard.txt", 'rb'))
except:
playerData = []
uniqueNames = 0
playerName = ''.join(self.playerName)
for player in playerData:
player[2] = 0
if playerName == player[0]:
pass
else:
uniqueNames += 1
if uniqueNames == len(playerData):
self.canvas.itemconfig(self.namePrompt, state=HIDDEN)
self.canvas.itemconfig(self.warningText, state=HIDDEN)
for letter in self.playerNameCanvas:
self.canvas.itemconfig(letter, state=HIDDEN)
self.root.unbind('<Key>')
self.root.unbind('<Return>')
self.root.bind('<Motion>', self.navigate)
self.root.bind('<Button-1>', self.click)
self.playerName = ''.join(self.playerName)
playerData.append([self.playerName, 0, 1])
pickle.dump(playerData, open("data/leaderboard.txt", 'wb'))
self.loop()
else:
self.canvas.itemconfig(self.warningText, text="Someone has already chosen that name.", state=NORMAL)
root = Tk()
Project = Game(root)
root.mainloop()
|
30dfcf31f9272f5253b052d4aa342dc05663dded | abdelhadisamir/SIRD_Model | /get_day_of_day.py | 317 | 3.828125 | 4 | from datetime import timedelta, date
def get_day_of_day(n=0):
'''''
if n>=0,date is larger than today
if n<0,date is less than today
date format = "YYYY-MM-DD"
'''
if(n<0):
n = abs(n)
return date.today()-timedelta(days=n)
else:
return date.today()+timedelta(days=n) |
4f603beccd737bea2d9ebd9d92bf3013dc91b9d1 | surajkumar0232/recursion | /binary.py | 233 | 4.125 | 4 | def binary(number):
if number==0:
return 0
else:
return number%2+10 * binary(number//2)
if __name__=="__main__":
number=int(input("Enter the numner which binary you want: "))
print(binary(number)) |
41003f89f2b8940c34a017c9f93ba9ca44e85b52 | CHyuye/ObjectOriented | /ObjectConcept_inherit.py | 5,663 | 4.125 | 4 | # 面向对象编程 —— 继承: 子类拥有父类的所有属性和方法
"""
面向对象三大特点
1、封装 —— 根据职责将属性和方法封装到一个抽象的类中
2、继承 —— 实现代码的重用,相同的代码不用重复的编写
3、多态 —— 不同的对象调用相同的方法,产生不同的执行结果,增加代码的灵活度
"""
# 继承的概念:子类拥有父类的所有属性和方法
# 专业术语:Dog类是Animal的派生类,Animal是Dog类的基类,Dog从Animal类中派生
# 1、单继承
# class Animal:
#
# def eat(self):
# print("吃--")
#
# def drink(self):
# print("喝--")
#
# def run(self):
# print("跑--")
#
# def sleep(self):
# print("睡--")
#
#
# # 继承语法: class 类名(父类名)
# class Dog(Animal):
#
# def bark(self):
# print("汪汪叫")
#
#
# # 子类拥有父类以及父类的父类中封装的所有属性和方法
# class xiaotianquan(Dog):
#
# def fly(self):
# print("我会飞")
#
# # 创建狗对象
# wangcai = Dog()
# wangcai.run()
# wangcai.bark()
#
# # 创建哮天犬的对象
#
# xtq = xiaotianquan()
#
# xtq.fly()
# xtq.sleep()
# 2、方法的重写
"""
当父类的方法实现不能满足子类的需求时,可以对方法进行重写
重写后,在运行时,只会调用子类中的重写的方法,而不再会调用父类封装的方法
重写的两种情况:
1、覆盖父类的方法
2、对父类的方法进行扩展
"""
# class A:
#
# def __init__(self):
#
# self.num1 = 100
# # 父类中的私有属性
# self.__num2 = 200
#
# # 父类中的私有方法
# def __test(self):
# print("父类中的私有方法 %d[公有属性] %d[私有属性]" % (self.num1, self.__num2))
#
# # 父类中的公有属性 —— 将私有属性和私有方法写入公有方法中,
# # 子类就可以通过父类的公有方法间接访问到私有属性和方法
# def test(self):
# print("父类中的公有方法 %d[公有属性] %d[私有属性] " % (self.num1, self.__num2))
#
# self.__test()
#
# def write(self):
# print("I can write English.")
#
# def speak(self):
# print("I can speak English.")
#
#
# class B(A):
#
# def write(self):
#
# # 1、覆盖 —— 在子类中重新编写父类的方法实现
# print("I want write Chain.")
#
# # 2、扩展 —— 子类的方法实现中需要父类的方法实现
# # 扩展方法: super().父类方法名 调用父类的方法执行
# super().write()
#
# # 第二种扩展方法 适用于python2.x
# # 父类名.方法名(self)
# # A.write(self)
# # 注意:如果使用子类调用方法,会出现递归导致死循环
# # B.write(self) # 特别注意不应该出现调用自己情况
#
# # 3、或者编写子类特有的代码实现
# print("I Love You")
#
# def demo(self):
#
# # 1、在子类的对象方法中,不能访问父类中的私有属性
# # print("访问父类的私有属性 %d " % self.__num2)
#
# # 2、不能调用父类的私有方法
# # self.__test()
#
# # 3、访问父类中的公有属性
# print("子类方法访问父类公有属性 %d " % self.num1)
#
# # 4、访问父类中的公有方法
# self.test()
#
#
# people = B()
# print(people)
# people.write()
# people.demo()
# 3、多继承 —— 子类可以拥有多个父类,并且具有父类的属性和方法
# 多继承的新式类和旧式类
"""
新式类: 以object为基类的类,就是新式类
旧式类: 不以object为基类的类,是旧式类
在python3.x中,创建类不指名object,默认会以object为基类
python2.x中,需要指定object为父类继承
建议:如果没有父类,统一继承自object
"""
# class A(object):
#
# def test(self):
#
# print("A -- test 方法")
#
# def demo(self):
#
# print("A -- demo 方法")
#
#
# class B(object):
#
# def test(self):
#
# print("B -- test 方法")
#
# def demo(self):
#
# print("B -- demo 方法")
#
#
# class C(A, B):
#
# # 多继承可以让子类对象,同时拥有多个父类的方法和属性
# pass
#
#
# c = C()
# # 现在A B 类中都有demo方法 test方法,在开发时应该避免这种混淆,尽量不使用多继承
# c.demo()
# c.test()
#
# # python中的 MRO —— 方法搜索顺序
# print(C.__mro__)
# 4、多态 —— 不同的子类对象调用相同的父类方法,产生不同的执行结果
"""
1、多态可以增加代码的灵活度
2、一继承和重写父类的方法为前提
3、是调用方法的技巧,不会影响到类的内部设计
"""
class Dog(object):
def __init__(self, name):
self.name = name
def game(self):
print("%s 蹦蹦跳跳的玩耍···" % self.name)
class XiaotianDog(Dog):
def game(self):
print("%s 飞在天上玩耍···" % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def game_with_dog(self, dog):
print("%s 和 %s 快乐的玩耍···" % (self.name, dog.name))
dog.game()
# 创建狗对象
# wangcai = Dog("旺财")
# 创建子类 哮天犬, 多态:不同的子类对象调用相同的父类方法,产生不同的执行结果
xtq = XiaotianDog("哮天犬")
# 创建小明
xiaoming = Person("小明")
xiaoming.game_with_dog(xtq)
print(Person.__mro__)
|
9a7c37180aeb52ef8192ffffa20261bf89169c2b | CHyuye/ObjectOriented | /python_FileOperation.py | 2,923 | 3.734375 | 4 | # 1、文件基本操作
"""
三个步骤: 一个函数open,三个方法
1、open —— 打开文件,并且返回文件操作对象
2、读,写文件
read —— 将文件内容读取到内存
write —— 将指定内容写入文件
3、关闭文件 close
"""
# 打开文件,默认是只读模式
# file = open("README")
#
# # 读取文件
# # 读取完文件后,文件指针会移动到文件末尾
# text = file.read()
# print(text)
# print(len(text))
#
# print("-" * 30)
#
# # 当执行了一次read方法,读取了内容,再次调用read方法,不能获取到内容
# text = file.read()
# print(text)
# print(len(text))
#
# # 关闭文件
# # 不要忘记关闭文件,会造成系统资源浪费,而且会影响到后续文件访问
# file.close()
# 2、文件指针(知道)
"""
文件指针标记从哪个位置开始读取数据
第一次打开文件,通常文件指针在开始位置
当执行read方法后,文件指针移动到末尾
"""
# 3、打开文件的方式
"""
访问方式:
r —— 只读方式打开文件,默认模式
w —— 只写方式打开文件,如果文件存在,文件内容会被重写覆盖,文件不存在创建文件
a —— 追加方式打开文件,文件存在,文件指针放在文件末尾,写入,文件不存在创建文件
不常用的三种:频繁的移动文件指针,会影响文件的读写效率
r+ —— 以读写方式打开,文件指针放在开头
w+ —— 以读写方式打开,文件存在,文件内容覆盖,不存在,创建文件
a+ —— 以读写方式代开,文件存在,文件指针在末尾,写入,文件不存在创建文件
"""
# open语法: file = open("文件名", "访问方式")
# file = open("README", "a")
#
# file.write("\nI love you")
#
# file.close()
# 4、使用readline 分行读取大文件
# file = open("README")
#
# while True:
# # 读取每一行内容
# text = file.readline()
#
# # 判断是否读到内容
# if not text:
# break
#
# # 每读取一行的末尾都已经加上了 '\n'
# print(text, end="")
#
# file.close()
# 5、复制小文件
# 打开源文件,创建新文件
# read_file = open("README")
# write_file = open("README[复件]", "w")
#
# # 读取源文件,写入新文件
# text = read_file.read()
# write_file.write(text)
#
# # 关闭文件
# read_file.close()
# write_file.close()
# 6、复制大文件
# 打开源文件,创建新文件
# read_file = open("README")
# write_file = open("README[复件]", "w")
#
# # 使用readline 分行读取大文件,减轻内存消耗资源
# while True:
# # 读取每一行内容
# text = read_file.readline()
#
# # 判断是否读到内容
# if not text:
# break
#
# write_file.write(text)
#
# # 关闭文件
# read_file.close()
# write_file.close()
|
572d03f6ffd2cd9582c1ce93dc44f064bcac5a4e | ksambaiah/python | /leet/leet_136.py | 463 | 3.890625 | 4 | #!/usr/bin/env python3
'''
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
'''
def singleNumber(nums):
result = 0;
for i in nums:
result ^= i
print(result)
return result
if __name__ == '__main__':
a = [4,1,3,1,2,2,3,4,5]
print(a)
print(singleNumber(a))
|
9edae297e93650718436858af87ddf2026ca3b1a | ksambaiah/python | /leet/addNumbers.py | 1,025 | 3.8125 | 4 | #!/usr/bin/env python3
''' leetcode 12268 '''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
sumll = ListNode
followup = 0
while l1.next or l2.next:
if l1.next and l2.next:
sumll.val = ( l1.next + l2.next + followup ) % 10
followup = int (( l1.next + l2.next + followup ) // 10)
elif l1.next:
sumll.val = ( l1.next + followup ) % 10
followup = int (( l1.next + followup ) // 10)
elif l2.next:
sumll.val = ( l2.next + followup ) % 10
followup = int (( l2.next + followup ) // 10)
if followup:
sumll.val = followup
return sumll
if __name__ == '__main__':
a = ListNode
a.append(2)
a.append(9)
a.append(4)
b.val = 5
b.next.val = 6
b.next.next.val = 4
r = addTwoNumbers(a, b)
print(r.val, r.next.val, r.next.next.val)
|
65e7f36fb7862257cf9557101f4570273d9fed28 | ksambaiah/python | /misc/enum.py | 120 | 3.625 | 4 | #!/usr/bin/env python3
nums = [-100, -20, 0, 2, 23, 44, 55]
for i, num in enumerate(nums):
print(i)
print(num)
|
52a4c94eacea03a662dffaacb42008bbf80b031c | ksambaiah/python | /pythonds/chap1/binarySearch.py | 697 | 3.859375 | 4 | #!/usr/bin/env python3
import random
def binarySearch(a, left, right, num):
if right >= left:
middle = (right + left) // 2
if a[ middle ] == num:
return middle
elif a [ middle ] > num:
return binarySearch(a, left, middle-1, num)
else:
return binarySearch(a, middle+1, right, num)
else:
return -1
if __name__ == '__main__':
size = 2000
a = []
for i in range(0,size):
if i != 0:
num = a[i-1]
a.append(random.randint(num, num+5000))
else:
a.append(0)
m = a[220]
print(m)
match = binarySearch(a,0,len(a), m)
print(match)
|
a9ee8a83512a5bc4f404b8244a1168a4329ddc2a | ksambaiah/python | /leet/maxSwap.py | 476 | 3.9375 | 4 | #!/usr/bin/env python3
'''
You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
'''
def maxnum(i):
a = 0
t = i
a = []
while t:
a.append(t % 10)
print(a)
t = t // 10
a = rev(a)
max = a[0]
j = 1
for j in a:
if a[j] < max:
max = a[j]
if __name__ == '__main__':
num = 1731
print(num)
print(maxnum(num))
|
31e16b0a88fa71b18df243af4b46ee3030a3c51d | ksambaiah/python | /salesforce/leet_220.py | 1,180 | 3.828125 | 4 | #!/usr/bin/env python3
'''
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
'''
class Solution:
def nextGreaterElement(self, nums1, nums2):
arr = []
for x in nums1:
found = 0
for j in range(len(nums2)):
if x == nums2[j]:
found = 1
elif found and x < nums2[j]:
arr.append(nums2[j])
break
if j == len(nums2) - 1:
arr.append(-1)
return arr
if __name__ == '__main__':
nums1 = [2,4]
nums2 = [1,2,3,4]
print(nums1, nums2)
s = Solution()
print(s.nextGreaterElement(nums1, nums2))
|
698ff141a859099a6a39834f018eee6d55399945 | ksambaiah/python | /leet/leet1534.py | 645 | 3.96875 | 4 | #!/usr/bin/env python3
'''
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
'''
def goodArray(arr,a,b,c):
result = 0
l = len(arr)
for i in range(l-2):
for j in range(i+1,l-1):
for k in range(j+1,l):
a1 = abs(arr[j] - arr[i]) <= a
b1 = abs(arr[j] - arr[k]) <= b
c1 = abs(arr[k] - arr[i]) <= c
if a1 and b1 and c1:
result += 1
return result
if __name__ == '__main__':
arr = [3,0,1,1,9,7]
a = 7
b = 2
c = 3
print(arr,a,b,c)
print(goodArray(arr,a,b,c))
|
86cbf381166e71e7b50d958c67cc156f81426078 | ksambaiah/python | /educative/fr.py | 208 | 4.15625 | 4 | friends = ["xyz", "abc", "234", "123", "Sam", "Har"]
print(friends)
for y in friends:
print("Hello ", y)
for i in range(len(friends)):
print("Hello ", friends[i])
z = "Hello ".join(friends)
print(z)
|
45aff915fec08bc0c3e299c9be9b2796f153abc0 | ksambaiah/python | /educative/ll.py | 2,602 | 4.09375 | 4 | #!/usr/bin/env python3
'''
Linked list and Node implementation in Python3
'''
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
n = Node(data)
if self.head is None:
self = n
return
lastNode = self.head
while lastNode.next is not None:
lastNode = lastNode.next
lastNode.next = n
def prepend(self, data):
n = Node(data)
n.next = self.head
self.head = n
def insert_after_node(self, prev_node, data):
if not prev_node:
print("prev_node doesn't exist, quitting")
n = Node(data)
n.next = prev_node.next
prev_node.next = n
def delete_key(self, key):
curr_node = self.head
d = self.head
if curr_node and curr_node.data == key:
curr_node = curr_node.next
self.head = curr_node
return
prev_node = None
while curr_node and curr_node.data != key:
prev_node = curr_node
curr_node = curr_node.next
if curr_node is None:
return
prev_node.next = curr_node.next
curr_node = None
def delete_pos(self, pos):
curr_node = self.head
if pos == 0:
curr_node = curr_node.next
return
prev_node = None
while pos > 0:
prev_node = curr_node
curr_node = curr_node.next
pos -= 1
if curr_node is None:
return
prev_node.next = curr_node.next
curr_node = None
def __repr__(self):
tmp = self.head
mem = []
while tmp is not None:
mem.append(tmp.data)
tmp = tmp.next
return " -> ".join(mem)
def length(self):
tmp = self.head
n = 0
while tmp is not None:
tmp = tmp.next
n += 1
return n
if __name__ == "__main__":
a = Node("5")
print(a)
b = Node("6")
a.next = b
s = LinkedList()
s.head = a
c = Node("7")
b.next = c
print(s)
s.append("100")
print(s)
s.append("101")
s.prepend("-100")
print(s)
s.insert_after_node(c, "2000")
print(s)
print(s.length())
s.delete_key("-100")
print(s)
s.delete_key("100")
print(s)
s.delete_key("2000")
print(s)
s.delete_pos(2)
print(s)
print(s.length())
|
8345d871035574f880766fc17503c1331fbe62ab | ksambaiah/python | /slidingwindow/sliWind2.py | 688 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
# Maximum sum of contiguous array of size 3
# Not sure how to get minint getting maxint and negating
def slidingWindow2(arr, num):
total = 0
ptotal = 0
for i in range(len(arr)):
if i < num:
total = total + arr[i]
ptotal = total
else:
total = total + arr[i] - arr[i-num]
if ptotal < total:
ptotal = total
print(total,arr[i],arr[i-num])
return ptotal
if __name__ == '__main__':
arr = [4,2,1,7,8,1,2,8,1,0]
key = 3
r = slidingWindow2(arr, key)
print(arr)
print("maximum of 3 adjucent numbers are ", r)
|
7a02b7fb90ff4990ffc97fb57ef4af420db7519d | ksambaiah/python | /misc/merge.py | 546 | 3.734375 | 4 | #!/usr/bin/env python3
def merge(a, b):
i = 0
j = 0
c = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i = i + 1
else:
c.append(b[j])
j = j + 1
while i < len(a):
c.append(a[i])
i += 1
while j < len(b):
c.append(b[j])
j += 1
return c
if __name__ == '__main__':
a = [1, 2, 3, 4, 10, 15, 19, 20, 21]
b = [0, 3, 10, 22, 23, 24, 25,100,900]
print(a)
print(b)
c = merge(a,b)
print(c)
|
55f6c6dd5be7fd981e708927ba51f51c622f9b45 | ksambaiah/python | /leet/palindrome.py | 355 | 3.984375 | 4 | #!/usr/bin/env python3
def isPalindrome( x: int) -> bool:
y = 0
x1 = x
while x:
y = x % 10 + y * 10
x = x // 10
if x1 == y:
return True
else:
return False
if __name__ == '__main__':
print(1234)
print(isPalindrome(1234))
print(1221)
print(isPalindrome(1221))
|
97dff201244de680e04f4a00776ed8a10b35297e | ksambaiah/python | /leet/leet217_1.py | 266 | 3.859375 | 4 | #!/usr/bin/env python3
def containsDuplicate(nums) -> bool:
b = set(nums)
if len(b) == len(nums):
return False
else:
return True
if __name__ == '__main__':
a = [1,2,3,4,1]
print(a)
print(containsDuplicate(a))
|
a6fac80206f0a4db0aff4d33454cf93beb3f2d66 | ksambaiah/python | /files/fileRead.py | 219 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: samkilar
"""
f = open("testfile.txt", "r")
line = f.readline()
while line:
# Take out new line
print(line.rstrip())
line = f.readline()
f.close()
|
0cf3d8481c243de3b9d354ad30ce1a281461aca4 | ksambaiah/python | /educative/find_string_anagrams.py | 439 | 4.375 | 4 | #!/usr/bin/env python3
import itertools
'''
'''
def find_string_anagrams(str, pattern):
arr = []
for p in itertools.permutations(pattern):
p = "".join(p)
#arr.append(str.find(p))
if p in str:
arr.append(str.index(p))
arr.sort()
return arr
if __name__ == '__main__':
str = "thitrisisstringirtritrti"
pattern = "tri"
print(str, pattern)
print(find_string_anagrams(str,pattern))
|
4afc4191fd6650dac57415404d36803373e071e4 | ksambaiah/python | /hackerRank/arraySum.py | 436 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 00:41:04 2020
@author: samkilar
"""
def addArray(arr):
y = 0
for i in range(len(arr)):
y = y + arr[i]
return y
if __name__ == "__main__":
# We are taking array, later we do take some random values
arr = [0, 1, -100, -200, 300, 999999, 9, 99, 0, 2, 22, 45, -9, 99999]
print("Adding all emements of array", addArray(arr)) |
81fe8bfbb8b91b076661c5b80e59c910eaf87a76 | ksambaiah/python | /pythonds/chap1/greatNum.py | 813 | 3.75 | 4 | #!/usr/bin/env python3
''' leet 1431
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.
For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.
'''
def greatNum(arr, num) -> List[bool]:
max = arr[0]
b = []
for i in range(1,len(arr)):
if max < arr[i]:
max = arr[i]
for i in range(len(arr)):
if arr[i] + num >= max:
b.append(True)
else:
b.append(False)
return b
if __name__ == '__main__':
arr = [1,3,4,7,8,9,1,2,3,4,5]
extra = 6
print(arr,extra)
ret = greatNum(arr,extra)
print(ret)
|
ba10c88ad9067c960b174ac2af00eca60b395f8c | Neb2/Text-RPG | /data/enemies.py | 3,955 | 3.578125 | 4 | import random
# generates a random enemy from a txt file.
class Mobs:
def enemy_gen(self, character):
if character.location in ["b6", "c5", "c6", "c7", "d4", "d5", "d6", "d7", "d8", "e5", "e6", "e7", "f5", "f6",
"g6", "h6", "i6", "j6", "k5", "k6", "k7", "l5", "l6", "m6", "m7", "n6", "n7", "o7",
"o8", "o9", "o10", "p10", "q10", "r10"]:
chance = random.randint(1, 101)
if chance in range(96, 101):
name = "Alien"
hp = 100
atk = 10
defence = 10
return Enemy(hp, atk, defence, name, - 0, + 0)
else:
if character.location in ["b6", "c5", "c6", "c7", "d4", "d5", "d6", "d7", "d8", "e5", "e6", "e7", "f5", "f6"]:
if character.d5_event_2:
name = "Strange Man"
hp = 10
atk = 0
defence = 0
character.d5_event_2 = False
else:
file = open("mobs/forest_mobs.txt", "r")
lines = file.readlines()
name = lines[random.randint(0, len(lines) - 1)][:-1]
file.close()
hp = random.randint(80, 110) # 70, 100
atk = random.randint(10, 20) # 15, 25
defence = random.randint(6, 11) # 5, 10
# from enemy class
return Enemy(hp, atk, defence, name, - 0, + 0) # 10, 10
elif character.location in ["g6", "h6", "i6", "j6"]:
file = open("mobs/water_mobs.txt", "r")
lines = file.readlines()
name = lines[random.randint(0, len(lines) - 1)][:-1]
file.close()
hp = random.randint(140, 170) # 110, 140
atk = random.randint(40, 50) # 30, 40
defence = random.randint(12, 15) # 8, 13
return Enemy(hp, atk, defence, name, - 6, + 6) # 10, 10
elif character.location in ["k5", "k6", "k7", "l5", "l6", "m6", "m7", "n6", "n7"]:
file = open("mobs/desert_mobs.txt", "r")
lines = file.readlines()
name = lines[random.randint(0, len(lines) - 1)][:-1]
file.close()
hp = random.randint(180, 210) # 150, 170
atk = random.randint(50, 60) # 45, 55
defence = random.randint(15, 18) # 12, 16
return Enemy(hp, atk, defence, name, - 10, + 10) # 15, 15
elif character.location in ["o7", "o8", "o9", "o10", "p10", "q10"]:
file = open("mobs/cave_mobs.txt", "r")
lines = file.readlines()
name = lines[random.randint(0, len(lines) - 1)][:-1]
file.close()
hp = random.randint(220, 250) # 170, 200
atk = random.randint(60, 70) # 55, 65
defence = random.randint(17, 20) # 14, 17
return Enemy(hp, atk, defence, name, - 12, + 15) # 10, 20
elif character.location in ["r10"]:
name = "Baron of Hell"
hp = 750 # 450
atk = 35 # 60
defence = 25 # 30
return Enemy(hp, atk, defence, name, - 10, + 10) # 30, 30
# enemy class
class Enemy:
def __init__(self, hp, atk, defence, name, atk_l, atk_h):
self.name = name
self.hp = hp
self.max_hp = hp
self.atk = atk
self.atk_l = atk_l
self.atk_h = atk_h
self.defence = defence
|
9f1ad80a37d8ad76083ffaf29b4cf15ab6ddfd96 | Neb2/Text-RPG | /data/save_exit.py | 1,076 | 3.640625 | 4 | import os
import pickle
import sys
def save(character, en1):
from data.menu import game_menu
if os.path.exists("save_file"):
print("Are you sure you want to overwrite your current save? Y/N")
option = input("> ")
if option.lower() == "y":
with open('save_file', 'wb') as f:
pickle.dump(character, f)
print("Game has been saved.")
else:
print("Game hasn't been saved.")
else:
with open('save_file', 'wb') as f:
pickle.dump(character, f)
print("Game has been saved.")
input(">...")
game_menu(character, en1)
def auto_save(character):
with open('save_file', 'wb') as f:
pickle.dump(character, f)
def exit_check(character, en1):
from data.menu import game_menu
os.system("cls")
print("Are you sure you want to exit? Make sure you have saved first. Y/N")
choice = input("> ")
if choice.lower() == "y":
sys.exit()
else:
game_menu(character, en1)
|
bfe2a975900f1efd6c10c1d22e9e4da1593719df | derekb/2018-advent-of-code | /day-05/solution.py | 669 | 3.578125 | 4 | #!/usr/bin/env python
import sys
import string
def reactive_units():
forward = set([f'{char}{char.upper()}' for char in list(string.ascii_lowercase)])
backward = set([f'{char}{char.lower()}' for char in list(string.ascii_uppercase)])
return forward.union(backward)
def react(molecule):
for reaction in reactive_units():
molecule = molecule.replace(reaction, '')
return molecule
molecule = str(sys.stdin.read())
molecule_length = len(molecule)
molecule_diff = 1
while molecule_diff > 0:
molecule = react(molecule)
molecule_diff = molecule_length - len(molecule)
molecule_length = len(molecule)
print(molecule_length) |
fbb36c0dcde24118eea1546ac1f96fc7b0b5f108 | shreeyash-hello/Python-codes | /replace.py | 112 | 3.71875 | 4 | inp=input('enter the string: ')
char = inp[0]
inp = inp.replace(char, '$')
inp = char + inp[1:]
print(inp)
|
f5f0bd3a82563eed93c8e034204dd7c090be67fa | shreeyash-hello/Python-codes | /sorting.py | 1,079 | 4 | 4 | def selection_sort():
A = []
inp = int(input('enter the number of students: '))
for i in range(inp):
enter = float(input(f'enter the percentage of student {i + 1}: '))
A.append(enter)
for i in range(len(A)):
# print(A)
a = i
for j in range(i + 1, len(A)):
if A[a] > A[j]:
a = j
A[i], A[a] = A[a], A[i]
print("Sorted array in selection sort is: ", A)
print('first five greatest marks: ',A[::-1])
def bubble_sort():
A = []
inp = int(input('enter the number of students: '))
for i in range(inp):
# print(A)
enter = float(input(f'enter the percentage of student {i + 1}: '))
A.append(enter)
n = len(A)
for i in range(n - 1):
for j in range(0, n - i - 1):
if A[j] > A[j + 1]:
A[j], A[j + 1] = A[j + 1], A[j]
print("Sorted array in bubble sort is: ", A)
print('first five greatest marks: ',A[::-1])
def main():
bubble_sort()
selection_sort()
if __name__=='__main__':
main()
|
4647a038acd767895c4fd6cdbfcc130ef60a87ce | shreeyash-hello/Python-codes | /leap year.py | 396 | 4.1875 | 4 |
while True :
year = int(input("Enter year to be checked:"))
string = str(year)
length = len(string)
if length == 4:
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!")
break
else:
print("The year isn't a leap year!")
break
else:
print('enter appropriate year')
|
b74ba7ee11dafa4f0482c903eeee240142181873 | bengovernali/python_exercises | /tip_calculator_2.py | 870 | 4.1875 | 4 |
bill = float(input("Total bill amount? "))
people = int(input("Split how many ways? "))
service_status = False
while service_status == False:
service = input("Level of service? ")
if service == "good":
service_status = True
elif service == "fair":
service_status = True
elif service_status == "bad":
service_status = True
def calculate_tip(bill, service):
if service == "good":
tip_percent = 0.20
elif service == "fair":
tip_percent = 0.15
elif service == "bad":
tip_percent = 0.10
tip_amount = bill * tip_percent
print("Tip amount: $%.2f" % tip_amount)
total_amount = bill + tip_amount
print("Total amount: $%.2f" % total_amount)
amount_per_person = total_amount / people
print("Amount per person: $%.2f" % amount_per_person)
calculate_tip(bill, service) |
20c8bf9296f70690fcb550759d1b3e2461b88d6a | 0xJinbe/Exercicios-py | /Ex 051.py | 560 | 4.03125 | 4 | """Altere o programa de cálculo do fatorial, permitindo ao usuário calcular o fatorial várias vezes e limitando o fatorial a números inteiros positivos e menores que 16."""
import math
lista = []
count = 0
qnt = int(input('Digite a quantidade de numeros que deseja entrar: '))
while qnt != count:
numero = float(input("Digite um numero: "))
while numero // 1 != numero or numero < 0 or 0 or numero < 16:
numero = float(input("Digite um número[erro]: "))
print("Fatorial do número digitado: ", math.factorial(numero))
count += 1 |
7626ba157020a6e67630d783a958221ad18ace0d | 0xJinbe/Exercicios-py | /Ex 021.py | 1,241 | 4.3125 | 4 | """Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado;
Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;
Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;
Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;"""
import math
print('Programa que acha as raizes de ax2 + bx + c = 0')
a = int(input('Coeficiente a: '))
if (a==0):
print('A == 0. A equação não é do segundo grau')
else:
b = int(input('Coeficiente b: '))
c = int(input('Coeficiente c: '))
delta = b*b - 4*a*c
if delta < 0:
print('Delta menor que zero, raízes imaginárias.')
elif delta == 0:
raiz = -b/(2*a)
print('Delta=0 , raiz = ', raiz)
else:
raiz1 = (-b + math.sqrt(delta)) / 2*a
raiz2 = (-b - math.sqrt(delta)) / 2*a
print('Raízes: ', raiz1, raiz2) |
6734d25a36b656fea9923b2f73deb3348ee77a1d | 0xJinbe/Exercicios-py | /Ex 041.py | 412 | 3.984375 | 4 | """Faça um programa que leia 5 números e informe a soma e a média dos números.
"""
lista = []
i = 1
while i <= 5:
a = int(input('Informe os numeros: '))
lista.append(a)
media = sum(lista)/len(lista)
soma = sum(lista)
i += 1
print(lista, soma, media)
l = []
for i in range (5):
a = int(input('Informe os valores: '))
l.append(a)
m = sum(l)/len(l)
s = sum(l)
print(l, s, m) |
7c1038a8db99d96fbb4a35323a8f5a2e27d4c8d4 | 0xJinbe/Exercicios-py | /Ex 057.py | 793 | 3.921875 | 4 | """Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato."""
n_eleitores = int(input('Qual o numero total de eleitores? '))
l_candidatos = []
count_A = 0
count_B = 0
count_C = 0
n_repetições = 0
while n_repetições < n_eleitores:
voto = (input('Qual candidato deseja votar? A,B,C: ')).upper()
l_candidatos.append(voto)
n_repetições += 1
print(l_candidatos)
for i in l_candidatos:
if i == 'A':
count_A += 1
elif i == 'B':
count_B += 1
else:
count_C += 1
print(f"A quantidade de pessoas que votou no candidato A é de: {count_A}. Candidato B: {count_B}. Candidato C: {count_C}")
|
d3379c4e3a7e371830181a9c671d33b77048399e | 0xJinbe/Exercicios-py | /Ex 025.py | 652 | 4.125 | 4 | """Faça um Programa para leitura de três notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e presentar:
A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
A mensagem "Aprovado com Distinção", se a média for igual a 10."""
nt_1 = int(input('Entre com valor trimestre 1: '))
nt_2 = int(input('Entre com o valor trimesre 2: '))
nt_3 = int(input('Entre om o valor trimestre 3: '))
tt = nt_1 + nt_2 + nt_3
mm = tt / 3
print(mm)
if mm >= 7:
print('Apr.')
else:
print('Rep.') |
56d6c020e5cd346dcae49b952bfd6b60bf5d8b1c | 0xJinbe/Exercicios-py | /Ex 031.py | 1,131 | 3.640625 | 4 | """Um posto está vendendo combustíveis com a seguinte tabela de descontos:
Álcool:
até 20 litros, desconto de 3% por litro
acima de 20 litros, desconto de 5% por litro
Gasolina:
até 20 litros, desconto de 4% por litro
acima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros vendidos, o tipo de combustível (codificado da seguinte forma: A-álcool, G-gasolina), calcule e imprima o valor a ser pago pelo cliente sabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90.
"""
l_vendidos = float(input('Quantos litros foram vendidos? : '))
comb = input('Qual é o tipo de combustível? (alcooll = a, gasolina = g): ').lower()
p_litros = 0
if comb == 'a':
p_litros = 1.90
if l_vendidos <= 20:
l_vendidos = l_vendidos - (l_vendidos*0.03)
else:
l_vendidos = l_vendidos - (l_vendidos*0.05)
else:
p_litros = 2.50
if l_vendidos <= 20:
l_vendidos = l_vendidos - (l_vendidos*0.04)
else:
l_vendidos = l_vendidos - (l_vendidos*0.06)
preço = l_vendidos*p_litros
print('Preço a pagar é: ', preço,"R$") |
53c4bae226ec0c1fe618f6bad7e74682ea30d227 | IgorKwiatkowski/codecademy-excersises | /sum_digits.py | 582 | 3.5625 | 4 | # def sum_digits(n, result=0):
#
# if n <= 9:
# result += n
# return result
# else:
# result += int(str(n)[0])
# print(result)
# if len(str(n)[1:]) > 0:
# sum_digits(int(str(n)[1:]), result)
def sum_digits(n):
if n <= 9:
return n
last_digit = n % 10
return sum_digits(n // 10) + last_digit
# print(sum_digits(12) == 3)
# print(sum_digits(552) == 12)
print(sum_digits(123456789))
print(sum_digits(123456789) == 45)
#
# print(sum_digits(12))
# print(sum_digits(552))
# print(sum_digits(123456789))
|
8f3f0618149fd6b523685e69c8a7c262e53bc5f1 | sijaannapurna/InfyTQ-DSA | /day1_assgn_2_car_and_service.py | 1,720 | 3.625 | 4 | #DSA-Assgn-2
class Car:
def __init__(self,model,year,registration_number):
self.__model=model
self.__year=year
self.__registration_number=registration_number
def get_model(self):
return self.__model
def get_year(self):
return self.__year
def get_registration_number(self):
return self.__registration_number
def __str__(self):
return(self.__model+" "+self.__registration_number+" "+(str)(self.__year))
#Implement Service class here
class Service:
def __init__(self, car_list):
self.__car_list=car_list
def get_car_list(self):
for car in self.__car_list:
print(car)
def find_cars_by_year(self,year):
car_list_by_year=[]
for car in self.__car_list:
if car.get_year()==year:
car_list_by_year.append(car.get_model())
if len(car_list_by_year)>0:
return car_list_by_year
else:
return None
def add_cars(self,new_car_list):
self.__car_list.extend(new_car_list)
self.__car_list.sort(key=lambda x:x.get_year())
def remove_cars_from_karnataka(self):
self.__car_list=[x for x in self.__car_list if not x.get_registration_number().startswith("KA")]
car1=Car("WagonR",2010,"KA09 3056")
car2=Car("Beat", 2011, "MH10 6776")
car3=Car("Ritz", 2013,"KA12 9098")
car4=Car("Polo",2013,"GJ01 7854")
car5=Car("Amaze",2014,"KL07 4332")
#Add different values to the list and test the program
car_list=[car3, car5]
s1=Service(car_list)
s1.find_cars_by_year(2013)
new_car_list=[car1,car2,car4]
s1.add_cars(new_car_list)
s1.get_car_list()
s1.remove_cars_from_karnataka()
|
fcf99d62f5b4618ce054af060aaf342067ec8ea1 | desireevl/hackerrank-regex-solutions | /applications/utopian_identification_number.py | 211 | 3.90625 | 4 | import re
n_lines = int(input())
for i in range(n_lines):
line = input()
match = re.search(r'^[a-z]{,3}\d{2,8}[A-Z]{3,}', line)
if match:
print('VALID')
else:
print('INVALID')
|
85a0fbe3a7492c11b2cab082b448251deac9edb5 | SebKleiner/Project_ITC_Data_Mining | /user_args.py | 3,467 | 3.671875 | 4 | """
Arg parse and clean results
"""
import argparse
from utils import utils
class UserInputs:
"""Constructs a class from user inputs"""
def __init__(self, input_args):
"""Takes in user/default inputs as attributes"""
self.command = input_args.command[utils['MAGIC_ZERO']]
self.sleep = input_args.sleep
if input_args.topics:
self.topics = [x.lower() for x in input_args.topics]
else:
self.topics = []
self.console = input_args.console
# Set console level
if input_args.console == 'False':
self.console = False
else:
self.console = input_args.console
self.default_topics = [z.lower() for z in utils['URLS']]
def __repr__(self):
"""__repr__"""
return self
def __str__(self):
"""__str__"""
return str(self)
def add(self):
"""This function combines the default search and the additional topics into
a uniform format without duplicates"""
return list(set(self.default_topics + self.topics))
def get_default(self):
"""This function returns a uniform format for the default topics"""
return self.default_topics
def customize(self):
"""This function returns a uniform format for the custom input topics"""
return self.topics
def apply_func(self):
"""Directs command to function"""
function_map = {'default': self.get_default(),
'add': self.add(),
'custom': self.customize()}
return function_map[self.command]
def parse_args():
""" Takes in inputs from argparse and returns inputs from argparse """
parser = argparse.ArgumentParser(f"""Welcome to the Reddit Web Scraper!
\n The default list to scrape is: \n {utils['URLS']}\n Enter -h for help.""")
parser.add_argument('command', choices=['default', 'custom', 'add'],
type=str, nargs=utils['MAGIC_ONE'], help='''Any two word topics should be a single word
(ex: to search 'data science' and 'ML', input : --topics=datascience --topics=ML).
Options include
default, add, custom .\n
default : search only default topics, \n
add: keep default topics and add your own, \n
custom: provide your own topics to search.''')
parser.add_argument("-s", "--sleep", type=int, choices=[utils['MAGIC_ZERO'], utils['MAGIC_ONE'],
utils['MAGIC_TWO']], default=utils['MAGIC_ONE'],
help="Choose seconds to sleep, default = {} (recommended)".format(utils['MAGIC_ONE']))
parser.add_argument("-c", "--console", default='False', choices=['False', 'DEBUG', 'INFO', 'WARNING', 'ERROR'],
action='store',
help="Set logging level for console logs, default is set to 'False'. "
"\nChoices = ['False', 'DEBUG','INFO','WARNING','ERROR'] ")
parser.add_argument('--topics', action='append',
help="Please specify each topic individually with --topics=xxx \n Any topics specified"
"with default function will be ignored.")
input_args = parser.parse_args()
return input_args
|
fa9d388ce7eb2b049aef558bd002d67eff84ef86 | Myeongchan-Kim/NHNNEXT_ML | /elice_1_10_solution.py | 3,612 | 3.578125 | 4 | '''
Introduction to Numpy
조금 지루했나요? 마지막으로 가장 중요한 부분인 Numpy를 이용한 기초 통계처리에 대해 배우겠습니다.
numpy.sum
배열에 있는 모든 원소의 합을 계산해서 리턴합니다.
A = numpy.array([1, 2, 3, 4])
print(numpy.sum(A))
사칙연산
재미있게도 Numpy의 배열에 사칙연산을 그대로 적용할 수 있습니다. 수학에서는 행렬에 숫자를 더하고, 빼고, 곱하고, 나누는 것을 허용하지 않지만 편의를 위해 만들어진 기능입니다. 실제로 큰 데이터를 다루는 통계분석 시에 굉장히 유용한 기능입니다. 배열 A와 스칼라 (scalar) 숫자 n 에 대해 다음과 같은 룰이 적용됩니다:
A + n: 배열의 모든 원소에 n만큼을 더합니다.
A - n: 배열의 모든 원소에 n만큼을 뺍니다.
A * n: 배열의 모든 원소에 n만큼을 곱합니다.
A / n: 배열의 모든 원소에 n만큼을 나눕니다.
다음 예제를 통해 실제로 실습해 보겠습니다.
A = numpy.array([[1, 2], [3, 4]])
print(A + 2)
print(A - 3)
print(A * 2)
print(A / 5)
numpy.mean, median, std, var
통계 처리시 가장 많이 쓰이는 세 가지 기능들입니다. 만약 데이터가 numpy.array로 주어졌다면 코드 한 줄로 데이터의 평균값, 중간값, 표준 편차, 분산을 구할 수 있습니다. 이 외에도, numpy는 통계를 위한 다양한 함수를 제공하고 있으므로 전체 리스트가 궁금하신 분은 Numpy - Statistics를 참조하시기 바랍니다.
A = numpy.array([1, 2, 4, 5, 5, 7, 10, 13, 18, 21])
print(numpy.mean(A))
print(numpy.median(A))
print(numpy.std(A))
print(numpy.var(A))
쉽지요? :)
과제
이제 위에서 배운 함수 중의 일부를 사용하는 연습을 진행해볼까요? 마찬가지로 이전 과제의 마지막 부분부터 시작하겠습니다.
E를 normalize (표준화) 하여 E 안의 모든 원소의 합이 1이 되도록 합니다.
통계처리시에 표준화작업은 매우 중요합니다. 어떤 사건에 대한 관찰 횟수를 가지고 있을때 이것을 확률 분포로 변환하는 것이 필요할 때 표준화를 사용합니다. 예를 들어, 동전이 어떻게 생겼는지에 대한 지식이 없지만 동전을 100번 던졌을 때 앞/뒷면이 나온 횟수를 알고 있다면, 이것을 통해 이 동전에서 앞면 혹은 뒷면이 나올 확률을 유추해 볼 수 있습니다. 확률을 구하는 가장 쉬운 방법은 횟수를 표준화하는 것입니다. 이를테면, 앞/뒷면에 대한 개수 [42, 58][42,58] 를 표준화하면 [0.42, 0.58][0.42,0.58] 이 되므로 실험을 통해 앞면이 나올 확률이 0.420.42, 뒷면이 나올 확률이 0.580.58이라고 설명할 수 있습니다.
위에서 설명한 sum과 사칙연산만을 이용해 표준화를 할 수 있습니다.
함수 matrix_tutorial 에서 표준화한 배열 E의 분산 (variance) 를 리턴합니다.
'''
import numpy
def main():
A = get_matrix()
print(matrix_tutorial(A))
def get_matrix():
mat = []
[n, m] = [int(x) for x in input().strip().split(" ")]
for i in range(n):
row = [int(x) for x in input().strip().split(" ")]
mat.append(row)
return numpy.array(mat)
def matrix_tutorial(A):
A = numpy.array([[1, 4, 5, 8], [2, 1, 7, 3], [5, 4, 5, 9]])
B = A.reshape((6, 2))
B = numpy.concatenate((B, [[2, 2], [5, 3]]), 0)
[C, D] = numpy.split(B, 2, axis=0)
E = numpy.concatenate((C, D), axis=1)
E = E / numpy.sum(E)
return numpy.var(E)
if __name__ == "__main__":
main() |
c5670156343d5f5b21aa6e56155afa368fb42cc8 | natalieborgorez/python_projects | /once_upon_a_time.py | 955 | 3.953125 | 4 | # Strange code by Natalie Borgorez
character_name = 'April'
character_age = 18
#print('Once upon a time there was a lass called ' + character_name + ', ')
#print('she was ' + character_age + ' years old. ')
print('Once upon a time there was a lass called %s, ' % character_name)
print('she was %i years old.' % character_age)
character_name = 'Audrey'
#print('However, she really liked her mother's name, which was ' + character_name + ', ')
#print('and wanted to be older than ' + character_age + '.')
print("However, she really liked her mother's name, which was %s," % character_name)
print("and wanted to be older than %i." % character_age)
character_name = 'Audril'
character_age = 45
print("So she burnt her passport ")
print("and declared herself a %i-year-old woman called %s.\n" % (character_age, character_name))
print(' /| |\\')
print(' / | | \\')
print(' / | | \\')
print('/___| |___\\')
# Strange code by Natalie Borgorez
|
3500f4e3506310d48f80196e03cb8f43d5fe949f | Molexar/akvelon_python_internship_3_Nikita_Potasev | /task_1/utils.py | 503 | 3.796875 | 4 | # Calculating by recursion
def fibonacci_rec(n):
if n == 0 or n == 1 or n == 2:
return 1
return fibonacci_rec(n-1) + fibonacci_rec(n-2)
# Calculating by cached values
fibs = {0: 0, 1: 1, 2: 1}
def fib_cache(n):
if n in fibs:
return fibs[n]
fibs[n] = fib_cache(n-1) + fib_cache(n-2)
return fibs[n]
# Calculating by dynamic programming
def fib_dym(n):
first, second = 0, 1
for __ in range(n):
first, second = second, first+second
return first
|
6c5499a4e2f71f024850a73bc10a738ac82486e4 | MynorSaban1906/Proyecto1_Compi1 | /pru.py | 22,156 | 3.65625 | 4 | from simbolos import *
class Scanner:
lista_tokens = list() # lista de tokens
lista_errores = list() # lista errores lexico
pos_errores = list() # lista de posiciones de errores
# estado = 0
lexema = ""
lista_reservadas=list()
transiciones=list()
def __init__(self):
self.transiciones=list()
self.lista_tokens = list()
self.lista_errores = list()
self.pos_errores = list()
self.estado = 0
self.lexema = ""
self.lista_reservadas=list()
def imprimirTokens(self):
li=""
for i in self.lista_tokens:
li+=str(i)
print(i)
li+="\n"
return li
#--------------------------- ESTADO0 ---------------------------
def analizar(self, cadena):
self.entrada = cadena + "$"
self.estado = 0
self.caracterActual = ''
self.columna=0
self.linea=1
pos = 0 # almacena la posicion del caracter que se esta analizando
#for self.pos in range(0,len(self.entrada)-1):
while pos < len(self.entrada):
self.caracterActual = self.entrada[pos]
# comentario uni linea
if self.caracterActual == "/" and self.entrada[pos+1] == "/" and self.entrada[pos-1]!=":":
comentario=""
pos+=2
while(self.entrada[pos]!="\n"):
comentario +=self.entrada[pos]
pos+=1
path=comentario.split(" ")
if(path[0]=="PATHW:"):
self.path=path[1]
print(F"ARCHIVO : {path[1]}")
else:
print("Comentario : ",comentario)
# /* comentario multiliea
elif self.caracterActual == "/" and self.entrada[pos+1] == "*" :
come=""
pos+=2
while (self.getSizecomentario(pos)!=1):
come+=self.entrada[pos]
pos+=1
pos+=self.getSizeLexema(pos)+1
print(come)
elif self.caracterActual=="\n":
self.linea+=1
self.columna=0
continue
# S0 -> S1 (Simbolos del Lenguaje)
elif self.caracterActual == "{":
self.addToken(Simbolo.llaveIzq, "{",pos)
elif self.caracterActual == "}":
self.addToken(Simbolo.llaveDer, "}",pos)
elif self.caracterActual == ":":
self.addToken(Simbolo.Dpuntos, ":",pos)
elif self.caracterActual == ";":
self.addToken(Simbolo.Pcoma, ";",pos)
elif self.caracterActual == ",":
self.addToken(Simbolo.coma, ",",pos)
elif self.caracterActual == "+":
self.addToken(Simbolo.Mas, "+",pos)
elif self.caracterActual == "-":
self.addToken(Simbolo.Menos, "-",pos)
elif self.caracterActual == "*":
self.addToken(Simbolo.Asterisco, "*",pos)
elif self.caracterActual == "/":
self.addToken(Simbolo.Division, "/",pos)
elif self.caracterActual == "(":
self.addToken(Simbolo.ParentIzq, "(",pos)
elif self.caracterActual == ")":
self.addToken(Simbolo.ParentDer, ")",pos)
elif self.caracterActual == "'":
self.addToken(Simbolo.comillaSimple, "'",pos)
# S0 -> S2 (Numeros)
elif self.caracterActual.isnumeric():
self.estado=0
sizeLexema = self.getSizeDigito(pos)
self.S2(pos, pos+sizeLexema)
pos = pos+sizeLexema
# S0 -> Reservadas | Identificadores
elif self.caracterActual.isalpha() :
self.estado=0
sizeLexema = self.getSizeLexema(pos)
self.analizar_Id_Reservada(pos, pos+sizeLexema)
pos = pos+sizeLexema
continue
# S0 -> '#' -> letra
elif self.caracterActual == "#" and self.entrada[pos+1].isalpha() :
self.estado=0
sizeLexema = self.getSizeLexema(pos)
self.S6(pos, pos+sizeLexema)
pos = pos+sizeLexema
continue
# S0 -> '#' -> numero color hexadecimal
elif self.caracterActual == "#" and self.entrada[pos+1].isalnum():
self.estado=0
sizeLexema = self.getSizeLexema(pos)
self.S6(pos, pos+sizeLexema)
pos = pos+sizeLexema
continue
# S0 -> '.' Q
elif self.caracterActual == "." :
self.estado=0
sizeLexema = self.getSizeLexema(pos)
self.S3(pos, pos+sizeLexema)
pos = pos+sizeLexema
continue
elif self.caracterActual == ":" :
self.estado=0
sizeLexema = self.getSizeLexema(pos)
self.S3(pos, pos+sizeLexema)
pos = pos+sizeLexema
continue
# Otros
elif self.caracterActual == " " or self.caracterActual == "\t" or self.caracterActual == "\r" or self.caracterActual == "\n":
pos += 1 #incremento del contador del while
continue
else:
# S0 -> FIN_CADENA
if self.caracterActual == "$" and pos == len(self.entrada)-1:
if len(self.lista_errores) > 0:
return "corregir los errores"
return "analisis exitoso...!!!"
# S0 -> ERROR_LEXICO
else:
self.pos_errores.append(pos)
print("Error Lexico: ", self.caracterActual)
pos += 1 #incremento del contador del while
if len(self.pos_errores)>0:
return "La entrada que ingresaste fue: " + self.entrada + "\nExiten Errores Lexicos"
else:
return "La entrada que ingresaste fue: " + self.entrada + "\nAnalisis exitoso..!!!"
#======re
def recorri(self):
for x in self.transiciones:
print(x)
#--------------------------- ESTADO2 ---------------------------
def S2(self, posActual, fin):
c = ''
esta=2
while posActual < fin:
c = self.entrada[posActual]
# S2 -> S2 (Numero)
if c.isnumeric():
esta=2
self.lexema += c
if(posActual+1 == fin):
self.addTransicion(c,self.estado,esta)
self.addToken(Simbolo.VALOR, self.lexema,posActual)
self.addTransicion(c,self.estado,esta)
self.estado=esta
# S2 -> S3 (letra)
elif c.isalpha():
esta=2
self.lexema += c
if(posActual+1 == fin):
self.addTransicion(c,self.estado,esta)
self.addToken(Simbolo.ID, self.lexema,posActual)
self.addTransicion(c,self.estado,esta)
self.estado=esta
elif c=="%":
self.lexema += c
if(posActual+1 == fin):
self.addTransicion(c,self.estado,1)
self.addToken(Simbolo.ID, self.lexema,posActual)
self.estado=1
elif c==".":
self.lexema += c
self.addTransicion(c,self.estado,1)
self.estado=1
# S2 -> ERROR_LEXICO
else:
print("Error Lexico: ", c)
posActual += 1
self.recorri()
self.imprimirTokens()
#--------------------------- ESTADO3 ---------------------------
def S3(self, posActual, fin):
c = ''
esta=4
while posActual < fin:
c = self.entrada[posActual]
# S3 -> S3 (letra)
if c.isalpha():
esta=4
self.lexema += c
if(posActual+1 == fin):
self.addToken(Simbolo.ID, self.lexema,posActual)
self.addTransicion(c,self.estado,esta)
self.addTransicion(c,self.estado,4)
self.estado=esta
elif c.isalnum():
esta=4
self.lexema += c
if(posActual+1 == fin):
self.addToken(Simbolo.ID, self.lexema,posActual)
self.addTransicion(c,self.estado,esta)
self.addTransicion(c,self.estado,esta)
self.estado=esta
elif c=="-":
self.lexema += c
self.addTransicion(c,self.estado,5)
self.estado=5
elif c==".":
self.lexema += c
self.addTransicion(c,self.estado,5)
self.estado=5
elif c==":":
self.lexema += c
self.addTransicion(c,self.estado,5)
self.estado=5
elif c=="_":
self.lexema += c
self.addTransicion(c,self.estado,5)
self.estado=5
# S2 -> ERROR_LEXICO
else:
self.pos_errores.append(posActual)
print("Error Lexico: ", c)
posActual += 1
self.imprimirTokens()
self.recorri()
#--------------------------- RESERVADAS/ID ---------------------------
def analizar_Id_Reservada(self, posActual, fin):
for x in range(posActual,fin):
self.lexema += self.entrada[x]
# S0 -> S4 (Palabras Reservadas)
if (self.lexema.lower() == "color"):
self.addToken(Simbolo.color, "color",posActual)
self.addTransicion(self.lexema,self.estado,6)
return
elif(self.lexema.lower() == "border"):
self.addToken(Simbolo.border, "border",posActual)
return
elif(self.lexema.lower() == "text-align"):
self.addToken(Simbolo.textaling, "text-aling",posActual)
return
elif(self.lexema.lower() == "font-weight"):
self.addToken(Simbolo.COLOR, "font-weight",posActual)
return
elif(self.lexema.lower() == "padding-left"):
self.addToken(Simbolo.paddingleft, "padding-left",posActual)
return
elif(self.lexema.lower() == "padding-top"):
self.addToken(Simbolo.paddingtop, "padding-top",posActual)
return
elif(self.lexema.lower() == "line-height"):
self.addToken(Simbolo.lineheight, "line-height",posActual)
return
elif(self.lexema.lower() == "margin-top"):
self.addToken(Simbolo.margintop, "margin-top",posActual)
return
elif(self.lexema.lower() == "margin-left"):
self.addToken(Simbolo.marginleft, "margin-left",posActual)
return
elif(self.lexema.lower() == "display"):
self.addToken(Simbolo.display, "display",posActual)
return
elif(self.lexema.lower() == "top"):
self.addToken(Simbolo.top, "top",posActual)
return
elif(self.lexema.lower() == "float"):
self.addToken(Simbolo.flotante, "float",posActual)
return
elif(self.lexema.lower() == "min-width"):
self.addToken(Simbolo.minwidth, "min-width",posActual)
return
elif(self.lexema.lower() == "font-weight"):
self.addToken(Simbolo.COLOR, "font-weight",posActual)
return
elif(self.lexema.lower() == "background-color"):
self.addToken(Simbolo.backgroundc, "background-color",posActual)
return
elif(self.lexema.lower() == "opacity"):
self.addToken(Simbolo.opacity, "opacity",posActual)
return
elif(self.lexema.lower() == "font-family"):
self.addToken(Simbolo.fontfamily, "font-family",posActual)
return
elif(self.lexema.lower() == "font-size"):
self.addToken(Simbolo.fontsize, "font-size",posActual)
return
elif(self.lexema.lower() == "padding-right"):
self.addToken(Simbolo.paddingright, "padding-right",posActual)
return
elif(self.lexema.lower() == "padding"):
self.addToken(Simbolo.padding, "padding",posActual)
return
elif(self.lexema.lower() == "width"):
self.addToken(Simbolo.width, "width",posActual)
return
elif(self.lexema.lower() == "margin-right"):
self.addToken(Simbolo.marginright, "margin-right",posActual)
return
elif(self.lexema.lower() == "position"):
self.addToken(Simbolo.position, "position",posActual)
return
elif(self.lexema.lower() == "right"):
self.addToken(Simbolo.right, "right",posActual)
return
elif(self.lexema.lower() == "clear"):
self.addToken(Simbolo.clear, "clear",posActual)
return
elif(self.lexema.lower() == "max-height"):
self.addToken(Simbolo.maxheight, "max-height",posActual)
return
elif(self.lexema.lower() == "background-image"):
self.addToken(Simbolo.backgroundi, "background-image",posActual)
return
elif(self.lexema.lower() == "background"):
self.addToken(Simbolo.background, "background",posActual)
return
elif(self.lexema.lower() == "font-style"):
self.addToken(Simbolo.fontstyle, "font-style",posActual)
return
elif(self.lexema.lower() == "font"):
self.addToken(Simbolo.font, "font",posActual)
return
elif(self.lexema.lower() == "padding-bottom"):
self.addToken(Simbolo.paddingbottom, "padding-bottom",posActual)
return
elif(self.lexema.lower() == "height"):
self.addToken(Simbolo.height, "height",posActual)
return
elif(self.lexema.lower() == "margin-bottom"):
self.addToken(Simbolo.marginbottom, "margin-bottom",posActual)
return
elif(self.lexema.lower() == "border-style"):
self.addToken(Simbolo.borderstyle, "border-style",posActual)
return
elif(self.lexema.lower() == "bottom"):
self.addToken(Simbolo.bottom, "bottom",posActual)
return
elif(self.lexema.lower() == "left"):
self.addToken(Simbolo.left, "left",posActual)
return
elif(self.lexema.lower() == "max-width"):
self.addToken(Simbolo.maxwidth, "max-width",posActual)
return
elif(self.lexema.lower() == "min-height"):
self.addToken(Simbolo.minheight, "min-height",posActual)
return
# S0 -> ERROR_LEXICO
self.estado=0
self.lexema = ""
c = ''
while posActual < fin:
c = self.entrada[posActual]
# S0 -> S5 ('#')
if c == "#":
self.lexema += c
# S5 -> S6 (letra)
self.S6(posActual+1, fin)
break
# S0 -> S6 (letra)
elif c.isalpha():
self.S6(posActual, fin)
break
# S0 -> ERROR_LEXICO
else:
self.pos_errores.append(posActual)
print("Error Lexico: ", c)
posActual += 1
# ------------------------ ESTADO 1--------------------------
def S1(self,posActual,inicio):
letra=self.entrada[posActual]
if letra == "{":
self.addTransicion("{",inicio,1)
inicio=1
elif letra == "}":
self.addTransicion("}",inicio,1)
inicio=1
elif letra == ":":
self.addTransicion(":",inicio,1)
inicio=1
elif letra == ";":
self.addTransicion(";",inicio,1)
inicio=1
elif letra == ",":
self.addTransicion(",",inicio,1)
inicio=1
elif letra == "=":
self.addTransicion("=",inicio,1)
inicio=1
elif letra == "+":
self.addTransicion("+",inicio,1)
inicio=1
elif letra == "-":
self.addTransicion("-",inicio,1)
inicio=1
elif letra == "*":
self.addTransicion("*",inicio,1)
inicio=1
elif letra == "/":
self.addTransicion("/",inicio,1)
inicio=1
elif letra == "(":
self.addTransicion("(",inicio,1)
inicio=1
elif letra == ")":
self.addTransicion(")",inicio,1)
inicio=1
elif letra == "'":
self.addTransicion("'",inicio,1)
inicio=1
elif letra=='"':
self.addTransicion('"',inicio,1)
inicio=1
else:
self.columna+=1
print(" ERROR LEXICO S1 ", self.entrada[posActual])
return inicio
#--------------------------- ESTADO6 ---------------------------
def S6(self, posActual, fin):
c = ''
while posActual < fin:
c = self.entrada[posActual]
# S6 -> S6 (letra)
if c.isalpha():
self.lexema += c
if(posActual+1 == fin):
self.addToken(Simbolo.ID, self.lexema,posActual)
# S6 -> S6 (Numero)
elif c.isnumeric():
self.lexema += c
if(posActual+1 == fin):
self.addToken(Simbolo.ID, self.lexema,posActual)
# S6 -> S6 ('-')
elif c == "-":
self.lexema += c
if(posActual+1 == fin):
self.addToken(Simbolo.ID, self.lexema,posActual)
# S6 -> ERROR_LEXICO
else:
self.pos_errores.append(posActual)
print("Error Lexico: ", c)
posActual += 1
#--------------------------- ESTADO_ERROR ---------------------------
#--------------------------- ADD TOKEN ---------------------------
def addToken(self, tipo, valor,pos):
nuevo = Token(tipo, valor,pos)
self.lista_tokens.append(nuevo)
self.lexema=""
self.caracterActual==""
#--------- add transicion -- --------
def addTransicion(self,valor,inicial,final):
nuevo= Transiciones(valor,inicial,final)
self.transiciones.append(nuevo)
#---------------- OBTENIENDO EL TAMAÑO DEL LEXEMA ----------------
def getSizeLexema(self, posInicial):
longitud = 0
for i in range(posInicial, len(self.entrada)-1):
if self.entrada[i] == " "or self.entrada[i] == "="or self.entrada[i] == "{" or self.entrada[i] == "}" or self.entrada[i] == "," or self.entrada[i] == ";" or self.entrada[i] == ":" or self.entrada[i] == "\n" or self.entrada[i] == "\t" or self.entrada[i] == "\r" or self.entrada[i] == "(" or self.entrada[i]==")"or self.entrada[i]=="'" or self.entrada[i] =='"' or self.entrada[i]=="/" or self.entrada[i]=="*"or self.entrada[i] =='+':
if self.entrada[i]!="\n":
self.columna+=1
if self.entrada[i]=="\n":
self.linea+=1
self.columna=0
break
if self.entrada[i]=="\n":
self.linea+=1
elif self.entrada[i].isnumeric() or self.entrada[i].isalpha():
self.columna+=1
longitud+=1
return longitud
#-------------obteniendo tamano de comentario multilinea---
def getSizecomentario(self, posInicial):
longitud=0
for i in range(posInicial, len(self.entrada)-1):
if self.entrada[i] == " " or self.entrada[i] == "{" or self.entrada[i] == "}" or self.entrada[i] == "," or self.entrada[i] == ";" or self.entrada[i] == ":" or self.entrada[i] == "\n" or self.entrada[i] == "\t" or self.entrada[i] == "\r":# or self.entrada[i] == "$":
break
elif self.entrada[i]=="\n":
self.linea+=1
elif self.entrada[i]=="*" and self.entrada[i+1]=="/":
self.linea+=1
print("fin mult",self.linea)
longitud=1
return longitud
#----------OBTENIENDO TAMANIO DE DIGITOS ----
def getSizeDigito(self, posInicial):
longitud = 0
for i in range(posInicial, len(self.entrada)-1):
if self.entrada[i] == " " or self.entrada[i] == "{" or self.entrada[i] == "}" or self.entrada[i] == "," or self.entrada[i] == ";" or self.entrada[i] == ":" or self.entrada[i] == "\n" or self.entrada[i] == "\t" or self.entrada[i] == "\r":
if self.entrada[i]!="\n":
self.columna+=1
if self.entrada[i]=="\n":
self.linea+=1
self.columna=0
break
if self.entrada[i]=="\n":
self.linea+=1
elif self.entrada[i].isnumeric() or self.entrada[i].isalpha():
self.columna+=1
longitud+=1
return longitud
|
5d73028bb1e3d44a55398bac1775a2130e8758c3 | onokatio/nitkc-Python-training | /No6.py | 284 | 4.0625 | 4 | #!/usr/bin/python
inputs = []
while True:
print("input string a >",end='')
a = input()
print("input string b >",end='')
b = input()
if b in a:
print(b,"is exist in ",a)
print("index is", a.find(b))
else:
print(b,"is not exist in ",a)
|
d547858a9796f7da6ddecfc925c01577793976d7 | mhirayama/python | /tutorial/numpy11.py | 608 | 3.65625 | 4 | import numpy as np
array = np.random.randint(0, 100, 20)
print(array)
X = np.sum(array) #配列の総和
print(X)
X = np.mean(array) #配列の平均
print(X)
X = np.var(array) #配列の分散
print(X)
X = np.std(array) #配列の標準偏差
print(X)
X = np.max(array) #最大値
print(X)
X = np.argmax(array) #最大値のインデックス
print(X)
X = np.min(array) #最小値
print(X)
X = np.argmin(array) #最小値のインデックス
print(X)
X = array.dtype #配列のデータ型
print(X)
array = np.random.randn(10)
print(array)
y = np.round(array, 2) #小数点を丸める
print(y)
|
b447fae2e619f5d8779cdc222f6d2796b5e81f54 | mhirayama/python | /tutorial/pandas08.py | 646 | 3.671875 | 4 | import numpy as np
import pandas as pd
#標準正規分布に従った乱数のデータフレームを2個生成
df_1 = pd.DataFrame(data = np.random.randn(5, 5), index = ['A','B','C','D','E'],
columns = ['C1','C2','C3','C4','C5'])
df_2 = pd.DataFrame(data = np.random.randn(5, 5), index = ['F','G','H','I','J'],
columns = ['C1','C2','C3','C4','C5'])
#それぞれのデータフレームを表示
print(df_1)
print(df_2)
print(pd.concat([df_1, df_2])) #2つのデータフレームを縦(行)で結合
print(pd.concat([df_1, df_2], axis = 1)) #2つのデータフレームを縦と横で結合
|
cac0f57c99df4f1d46d0c8334c96b122146e986b | aki202/nlp100 | /chapter6/052.py | 187 | 3.578125 | 4 | import reader
from stemming.porter2 import stem
for word in reader.words():
if word == None:
print('')
continue
stem_word = stem(word)
print('%s\t%s' % (word, stem_word))
|
08318811782f882ed856f2ff1eef82456b94977a | aki202/nlp100 | /chapter6/051.py | 156 | 3.703125 | 4 | import reader
for index, word in enumerate(reader.words()):
if word == None:
print('')
else:
print(word)
#print('[%d] %s' % (index, word))
|
e54410cf9db5300e6ef5c84fd3432b1723c017c6 | MeganTj/CS1-Python | /lab5/lab5_c_2.py | 2,836 | 4.3125 | 4 | from tkinter import *
import random
import math
# Graphics commands.
def draw_line(canvas, start, end, color):
'''Takes in four arguments: the canvas to draw the line on, the
starting location, the ending location, and the color of the line. Draws a
line given these parameters. Returns the handle of the line that was drawn
on the canvas.'''
start_x, start_y = start
end_x, end_y = end
return canvas.create_line(start_x, start_y, end_x, end_y, fill = color,
width = 3)
def draw_star(canvas, n, center, color):
'''Takes in four arguments: the canvas to draw the line on, the number of
points that the star has (a positive odd integer no smaller than 5), the
center of the star, and the color of the star. Draws a star pointed
vertically upwards given these parameters and with a randomly chosen radius
between 50 to 100 pixels. Returns a list of the handles of all the lines
drawn.'''
points = []
lines = []
r = random.randint(50, 100)
center_x, center_y = center
theta = (2 * math.pi) / n
for p in range(n):
x = r * math.cos(theta * p)
y = r * math.sin(theta * p)
points.append((y + center_x, -x + center_y))
increment = int((n - 1) / 2)
for l in range(n):
end_index = (l + increment) % n
lines.append(draw_line(canvas, points[l], points[end_index], color))
return lines
def random_color():
'''Generates random color values in the format recognized by the tkinter
graphics package, of the form #RRGGBB'''
seq = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f']
rand = '#'
for i in range(6):
rand += random.choice(seq)
return rand
# Event handlers.
def key_handler(event):
'''Handle key presses.'''
global stars
global color
global n
key = event.keysym
if key == 'q':
exit_python(event)
if key == 'c':
color = random_color()
if key == 'plus':
n += 2
if key == 'minus':
if n >= 7:
n -= 2
if key == 'x':
for lines in stars:
for line in lines:
canvas.delete(line)
stars = []
def button_handler(event):
'''Handle left mouse button click events.'''
global stars
lines = draw_star(canvas, n, (event.x, event.y), color)
stars.append(lines)
def exit_python(event):
'''Exit Python.'''
quit()
if __name__ == '__main__':
root = Tk()
root.geometry('800x800')
canvas = Canvas(root, width=800, height=800)
canvas.pack()
stars = []
color = random_color()
n = 5
# Bind events to handlers.
root.bind('<Key>', key_handler)
canvas.bind('<Button-1>', button_handler)
# Start it up.
root.mainloop() |
fb565965becf2065b92aea2e4c9099df396f7dce | MeganTj/CS1-Python | /lab4/lab4_d2.py | 1,274 | 3.96875 | 4 | from tkinter import *
def draw_square(canvas, color, length, center):
'''Takes in four arguments: the canvas to draw the square on, the color of
the square, the length of the sides of the square, and the center of the
square. Draws a square given these parameters. Returns the handle of the
square that was drawn on the canvas.'''
center_x, center_y = center
handle = canvas.create_rectangle(center_x - length/2, center_y - length/2,
center_x + length/2, center_y + length/2,
fill = color, outline = color)
return handle
if __name__ == '__main__':
'''Draws four squares of size 100x100 on an 800x800 canvas in each corner.
The square in the upper-left is red, that in the upper-right is green, that
in the lower-left is blue, and the remaining in the lower-right is yellow.
'''
root = Tk()
root.geometry('800x800')
c = Canvas(root, width = 800, height = 800)
c.pack()
draw_square(c, 'red', 100, (50,50))
draw_square(c, 'green', 100, (750,50))
draw_square(c, 'blue', 100, (50,750))
draw_square(c, 'yellow', 100, (750,750))
root.bind('<q>', quit)
root.mainloop()
|
5ba66ebea016f39abea513010890110bfe2329d3 | varbees/snakepy | /food.py | 705 | 3.71875 | 4 | from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.color("darkgrey")
self.speed('fastest')
self.shapesize(stretch_wid = 0.6, stretch_len = 0.6)
self.refresh()
# Experimental code for Bonus food
# def foodsize(self, score):
# if score % 5 != 0:
# self.color('purple')
# self.refresh()
# elif score >=5 and score % 5==0:
# self.color("red")
# self.shapesize(stretch_wid = 1, stretch_len = 1)
# self.refresh()
def refresh(self):
random_x = random.randint(-280, 280)
random_y = random.randint(-280, 280)
self.goto(random_x, random_y)
|
53e0756741f417f26cea140eecd97a6f30bc7802 | stepan-martynov/PY-3_2-1 | /cook-book.py | 1,955 | 3.78125 | 4 | def read_cook_book():
cook_book = {}
cook_book_file_name = input('Введите название файла, где лежит книга рецептов: ')
with open(cook_book_file_name) as f:
while True:
dish_name = f.readline().strip()
if dish_name:
cook_book[dish_name] = []
number_of_dish_items = int(f.readline())
for _ in range(number_of_dish_items):
item = f.readline().split(' | ')
u = {}
u['ingridient_name'] = item[0].strip()
u['quantity'] = int(item[1])
u['measure'] = item[2].strip()
cook_book[dish_name].append(u)
else:
break
return cook_book
def get_shop_list_by_dishes(dishes, person_count, cook_book):
shop_list = {}
for dish in dishes:
for ingridient in cook_book[dish]:
new_shop_list_item = dict(ingridient)
new_shop_list_item['quantity'] *= person_count
if new_shop_list_item['ingridient_name'] not in shop_list:
shop_list[new_shop_list_item['ingridient_name']] = new_shop_list_item
else:
shop_list[new_shop_list_item['ingridient_name']]['quantity'] += new_shop_list_item['quantity']
return shop_list
def print_shop_list(shop_list):
for shop_list_item in shop_list.values():
print('{ingridient_name} {quantity} {measure}'.format(**shop_list_item))
def create_shop_list():
person_count = int(input('Введите количество человек: '))
dishes = input('Введите блюда в расчете на одного человека (через запятую): ').lower().split(', ')
cook_book = read_cook_book()
shop_list = get_shop_list_by_dishes(dishes, person_count, cook_book)
print_shop_list(shop_list)
create_shop_list() |
8d538e4137a49cd2591721869b75fb4022308834 | cpingor/leetcode | /547.省份数量.py | 1,251 | 3.6875 | 4 | #
# @lc app=leetcode.cn id=547 lang=python3
#
# [547] 省份数量
#
# @lc code=start
class UnionFind:
def __init__(self, M):
self.father = {}
for i in range(len(M)):
self.father[i] = None
def find(self, x):
root = x
while self.father[root] != None:
root = self.father[root]
while x != root:
ori_root = self.father[x]
self.father[x] = root
x = ori_root
return root
def union(self, x, y):
root_x, root_y = self.find(x), self.find(y)
print(root_x, root_y)
if root_x != root_y:
self.father[root_x] = root_y
def is_connected(self, x, y):
return x in self.father and y in self.father and self.find(x) == self.find(y)
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
uf = UnionFind(isConnected)
for r in range(len(isConnected)):
for c in range(len(isConnected)):
if isConnected[r][c] == 1 and r != c:\
uf.union(r, c)
res = 0
for key in uf.father:
if uf.father[key] is None:
res += 1
return res
# @lc code=end
|
7250d83b8a2c97c679118c2619e80e246d2158f2 | cpingor/leetcode | /1791.找出星型图的中心节点.py | 1,309 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=1791 lang=python3
#
# [1791] 找出星型图的中心节点
#
# https://leetcode-cn.com/problems/find-center-of-star-graph/description/
#
# algorithms
# Medium (80.64%)
# Likes: 5
# Dislikes: 0
# Total Accepted: 7.2K
# Total Submissions: 8.9K
# Testcase Example: '[[1,2],[2,3],[4,2]]'
#
# 有一个无向的 星型 图,由 n 个编号从 1 到 n 的节点组成。星型图有一个 中心 节点,并且恰有 n - 1 条边将中心节点与其他每个节点连接起来。
#
# 给你一个二维整数数组 edges ,其中 edges[i] = [ui, vi] 表示在节点 ui 和 vi 之间存在一条边。请你找出并返回 edges
# 所表示星型图的中心节点。
#
#
#
# 示例 1:
#
#
# 输入:edges = [[1,2],[2,3],[4,2]]
# 输出:2
# 解释:如上图所示,节点 2 与其他每个节点都相连,所以节点 2 是中心节点。
#
#
# 示例 2:
#
#
# 输入:edges = [[1,2],[5,1],[1,3],[1,4]]
# 输出:1
#
#
#
#
# 提示:
#
#
# 3
# edges.length == n - 1
# edges[i].length == 2
# 1 i, vi
# ui != vi
# 题目数据给出的 edges 表示一个有效的星型图
#
#
#
# @lc code=start
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return set(set(edges[0]) & set(edges[1])).pop()
# @lc code=end
|
01859508e4b130f513d46aa7523c02b879dff1a2 | cpingor/leetcode | /721.账户合并.py | 1,479 | 3.625 | 4 | #
# @lc app=leetcode.cn id=721 lang=python3
#
# [721] 账户合并
#
# @lc code=start
import collections
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def union(self, index1: int, index2: int):
self.parent[self.find(index2)] = self.find(index1)
def find(self, index: int) -> int:
if self.parent[index] != index:
self.parent[index] = self.find(self.parent[index])
return self.parent[index]
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
emailToIndex = dict()
emailToName = dict()
for account in accounts:
name = account[0]
for email in account[1:]:
if email not in emailToIndex:
emailToIndex[email] = len(emailToIndex)
emailToName[email] = name
uf = UnionFind(len(emailToIndex))
for account in accounts:
firstIndex = emailToIndex[account[1]]
for email in account[2:]:
uf.union(firstIndex, emailToIndex[email])
indexToEmails = collections.defaultdict(list)
for email, index in emailToIndex.items():
index = uf.find(index)
indexToEmails[index].append(email)
ans = list()
for emails in indexToEmails.values():
ans.append([emailToName[emails[0]]] + sorted(emails))
return ans
# @lc code=end
|
a42616fae37499e939717c41c293680688f3bcb1 | bryanbeh/Coding-Bits | /IC Hack 2018/ml_disease.py | 3,625 | 3.71875 | 4 | # Mortality Rate model
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the dataset
dataset= pd.read_csv('ml_disease.csv')
x = dataset.iloc[:,:5].values
y = dataset.iloc[:,-2].values
print y
pd.DataFrame(dataset)
#Categorical Data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
"""x[:,1] = labelencoder_x.fit_transform(x[:, 1])
onehotencoder = OneHotEncoder(categorical_features = [1])
x[:,3] = labelencoder_x.fit_transform(x[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [3])
x = onehotencoder.fit_transform(x).toarray()"""
x[:,0] = labelencoder_x.fit_transform(x[:, 0])
onehotencoder = OneHotEncoder(categorical_features = [0])
x[:,2] = labelencoder_x.fit_transform(x[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [2])
x[:,4] = labelencoder_x.fit_transform(x[:, 4])
onehotencoder = OneHotEncoder(categorical_features = [4])
x = onehotencoder.fit_transform(x).toarray()
#Avoiding Dummy Variable Trap
x = x[:,1:]
pd.DataFrame(x)
#Splitting the dataset into Training set and Test set
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)
#Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)"""
from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor(n_estimators = 300,random_state = 0)
regressor.fit(x_train,y_train)
# Predicting the Test Result
y_pred = regressor.predict(x_test)
pd.DataFrame(y_test,y_pred)
import statsmodels.formula.api as sm
x = np.append(arr = np.ones((40,1)).astype(int), values = x, axis = 1) #building b0x0 where x0 = 1
print x
x_opt = x[:,[0,1,2,3,4,5]]
regressor_OLS = sm.OLS(endog = y, exog = x_opt).fit() #fitting the full model with all possible predictors
regressor_OLS.summary()
# Probability of Spread
#Importing the dataset
dataset= pd.read_csv('ml_disease.csv')
x2 = dataset.iloc[:,:5].values
y2 = dataset.iloc[:,-1].values
print y2
pd.DataFrame(dataset)
#Categorical Data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x2 = LabelEncoder()
x2[:,0] = labelencoder_x2.fit_transform(x2[:, 0])
onehotencoder = OneHotEncoder(categorical_features = [0])
x2[:,2] = labelencoder_x2.fit_transform(x2[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [2])
x2[:,4] = labelencoder_x2.fit_transform(x2[:, 4])
onehotencoder = OneHotEncoder(categorical_features = [4])
x2 = onehotencoder.fit_transform(x2).toarray()
#Avoiding Dummy Variable Trap
x2 = x2[:,1:]
pd.DataFrame(x2)
#Splitting the dataset into Training set and Test set
from sklearn.cross_validation import train_test_split
x2_train, x2_test, y2_train, y2_test = train_test_split(x2, y2, test_size = 0.2, random_state = 0)
#Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)"""
from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor()
regressor.fit(x2_train,y2_train)
# Predicting the Test Result
y2_pred = regressor.predict(x2_test)
pd.DataFrame(y2_test,y2_pred)
import statsmodels.formula.api as sm
x2 = np.append(arr = np.ones((40,1)).astype(int), values = x2, axis = 1) #building b0x0 where x0 = 1
print x2
x2_opt = x2[:,[0,1,2,3,4,5]]
regressor_OLS = sm.OLS(endog = y2, exog = x2_opt).fit() #fitting the full model with all possible predictors
regressor_OLS.summary()
|
aa28d546c84fc8d420b7c4204ba4bb324e0ef7ca | khan-pog/all_practicals | /practical_3/password_checker.py | 787 | 3.90625 | 4 | """Module docstring"""
# imports
# CONSTANTS
MIN_LENGTH_OF_PASSWORD = 3
def main(): # DONE: ALL INSIDE MAIN FUNCTION
"""Function docstring"""
# varables...
password = get_password()
# statements...
if len(password) >= MIN_LENGTH_OF_PASSWORD:
print_asterisk(password)
else:
print("the password doesn't meet a minimum length set by a variable.")
def get_password(): #DONE: REFACTORED THE PART THAT GETS THE INPUT FOR PASSWORD
"""Function docstring"""
# statements...
return input("Password > ")
def print_asterisk(password): #DONE: REFACTORED THE PART PRINTS THE ASTERISK
"""Function docstring"""
# statements...
asterisk_of_length_password = ['*'] * len(password)
print(*asterisk_of_length_password)
main()
|
133c23391d22fd3a68d2e050af72c0511e1baaab | khan-pog/all_practicals | /practical_6/guitar_test.py | 908 | 3.875 | 4 | """ Test guitar
Creator: Khan Thompson
Date: 06/09/2021
"""
from practical_6.guitar import Guitar
gibson = Guitar("Gibson L-5 CES", 1922, 16035.40)
gibson.get_age()
print(gibson.get_age()) # Done.
print(gibson.is_vintage()) # Done.
print("My guitars!")
name = input("Name: ")
guitars = []
# Done.
while name != '':
year = input('Year: ')
cost = input('Cost: ')
guitars.append(Guitar(name, int(year), float(cost)))
print('{} ({}) : ${} added.'.format(name, int(year), float(cost)))
name = input("Name: ")
print("These are my guitars:")
guitars.append(Guitar("Gibson L-5 CES", 1922, 16035.40))
guitars.append(Guitar("Line 6 JTV-59", 2010, 1512.9))
for i, guitar in enumerate(guitars, 1):
# Done.
print(
f"Guitar {i}: {guitar.name:{len(guitar.name)}} ({guitar.year}), worth"
f" ${guitar.cost:{len(str(guitar.cost))},.2f}{' (vintage)' if guitar.is_vintage() else ''}")
|
95a22b3bec1f5f7a5aa0111ba1f7a076e4911b99 | khan-pog/all_practicals | /practical_5/hex_colours.py | 971 | 4.03125 | 4 | """Hexadecimal colour lookup # DONE: CREATE A PROGRAM THAT ALLOWS YOU TO LOOK UP HEXADECIMAL COLOUR CODES."""
COLOUR_CODES = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7",
"AntiqueWhite1": "#ffefdb", "AntiqueWhite2": "#eedfcc",
"AntiqueWhite3": "#cdc0b0", "AntiqueWhite4": "#8b8378",
"aquamarine1": "#7fffd4", "aquamarine2": "#76eec6",
"aquamarine4": "#458b74", "azure1": "#f0ffff",
"azure2": "#e0eeee", "azure3": "#c1cdcd", "azure4": "#838b8b",
"beige": "#f5f5dc", "bisque1": "#ffe4c4"}
colour_code = input("colour code: ")
# DONE: ALLOW THE USER TO ENTER NAMES UNTIL THEY ENTER A BLANK ONE TO STOP THE LOOP.
while colour_code != '':
# DONE: ENTERING AN INVALID COLOUR NAME SHOULD NOT CRASH THE PROGRAM.
try:
COLOUR_CODES[colour_code]
except KeyError:
print("please enter valid colour code")
colour_code = input("colour code: ")
|
50f8832c2f1f020ec82bb90e2c6c7204ed0e561e | Manojna52/python_practice | /rrepeated_tuple.py | 176 | 3.671875 | 4 | from collections import Counter
x=(1,2,3,4,5,3,2)
a=list(x)
freq=dict()
freq=dict(Counter(a))
for item in freq:
if freq[item]>1:
print(item)
else:
pass
|
1c48b21164da452476dccac470c5615ddadbb863 | AnnaTashuk/Project1 | /s11.py | 434 | 3.875 | 4 | import re
def findSumReg(fileName):
"""
Returns amount of all numbers in the input file. Ignores letters, non-characters
like punctuation and spaces.
fileName: name of input file
returns: sum of all numbers
"""
return sum([int(num) for num in re.findall('[0-9]+',open(fileName).read())])
'''
test1
findSumReg(r'C:\Users\User\Desktop\Programing\2semestr\done\s1\regex_sum_42.txt')
'''
|
0fc854d7238f12e1cf625fb5d26ff101ca32d44a | hyeokjinson/algorithm | /ps프로젝트/알고리즘/3번.py | 540 | 3.703125 | 4 | from collections import deque
def solution(enter, leave):
answer = [0]*len(enter)
enter=deque(enter)
leave=deque(leave)
stack=[]
for i in range(len(enter)):
if enter[i]==leave[i]:
enter.popleft()
elif enter[i] in stack:
while True:
if enter[i]==stack[0]:
stack.pop(0)
break
else:
else:
stack.append(enter[i])
return answer
enter=[1,3,2]
leave=[1,2,3]
print(solution(enter,leave)) |
7e8552f809d2102a77a0991bbabf40a0fa7af254 | hyeokjinson/algorithm | /ps프로젝트/str/나이순정렬.py | 244 | 3.578125 | 4 | if __name__ == '__main__':
n=int(input())
arr=[]
for i in range(n):
age,name=map(str,input().split())
arr.append((int(age),i,name))
arr.sort(key=lambda x:(x[0],x[1]))
for x,y,z in arr:
print(x,z)
|
56a736abb43922156a58a29f11bc73c669e3ac5f | hyeokjinson/algorithm | /그리디/거스름돈.py | 110 | 3.71875 | 4 | n=int(input())
coin_type=[500,100,50,10]
cnt=0
for coin in coin_type:
cnt+=n//coin
n=n%coin
print(cnt) |
83739ae5597e9731669dbd432df88ed8055d7ffb | hyeokjinson/algorithm | /ps프로젝트/str/ROT13.py | 486 | 3.9375 | 4 | if __name__ == '__main__':
s=input()
tmp=''
for x in s:
if x==' ':
tmp+=' '
elif x.isdigit():
tmp+=x
elif x==x.upper():
if 65<=ord(x)+13<=90:
tmp+=chr(ord(x)+13)
else:
tmp+=chr(ord(x)+13-90+64)
elif x==x.lower():
if 97<=ord(x)+13<=122:
tmp+=chr(ord(x)+13)
else:
tmp+=chr(ord(x)+13-122+96)
print(tmp) |
a01e7f12af7334e03f5c292c8d65fafea0d0a2e0 | hyeokjinson/algorithm | /dfs/bfs/bfs기초.py | 515 | 3.609375 | 4 | from collections import deque
def bfs(graph,start,visited):
q=deque([start])
visited[start]=True
while q:
v=q.popleft()
print(v,end=" ")
for i in graph[v]:
if not visited[i]:
q.append(i)
visited[i]=True
if __name__ == '__main__':
graph=[
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
visited=[False]*9
bfs(graph,1,visited) |
51bf5c6a414fd4be2b1687cf3b20dff8fad54763 | hyeokjinson/algorithm | /deque.py | 355 | 3.78125 | 4 | from queue import Queue
class Deque(Queue):
def __init__(self):
self.input_data=[]
self.output_data=[]
def enqueue_back(self,item):
self.items.append(item)
def dequeue_front(self):
value=self.items.pop(0)
if value is not None:
return value
else:
print("Deque is empty") |
17fc46628b707243b760888a74ae7785f936bea9 | hyeokjinson/algorithm | /삼성기출/큐빙.py | 527 | 3.71875 | 4 | def rotate(area):
t,x,y,z,w=u,
if __name__ == '__main__':
T=int(input())
u=[['w']*3 for _ in range(3)]
d=[['y']*3 for _ in range(3)]
f=[['r']*3 for _ in range(3)]
b=[['o']*3 for _ in range(3)]
l=[['g']*3 for _ in range(3)]
r=[['b']*3 for _ in range(3)]
for _ in range(T):
n=int(input())
s=list(input().split())
for area,dir in s:
rotate(area,dir)
rotate2()
if dir=='-':
rotate(area)
rotate(area) |
c83c80a5ae86d94eddaddfa6e6b6d1341a21d4b9 | hyeokjinson/algorithm | /ps프로젝트/DP/파도반 수열.py | 242 | 3.546875 | 4 | if __name__ == '__main__':
padovan=[0]*100
padovan[0:5]=1,1,1,2,2,3
t=int(input())
for i in range(6,100):
padovan[i]=padovan[i-1]+padovan[i-5]
for _ in range(t):
n=int(input())
print(padovan[n-1]) |
a94d7d1d1c5b7cff38d14d712d6d8cf39738d106 | aparrado/cs207_andres_parrado | /homeworks/HW3/Bank.py | 6,897 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 24 10:15:52 2020
@author: andresparrado
"""
from enum import Enum
class AccountType(Enum):
SAVINGS = 1
CHECKING = 2
class NotEnoughMoney(Exception):
pass
class NegativeAmount(Exception):
pass
class AccountError(Exception):
pass
class WrongTypeAccount(Exception):
pass
# BankAccount class
class BankAccount():
''' This class creates a bank account. The main
methods are withdraw and deposit. You cannot
withdraw more than your balance. Also, you
cannot withdraw or deposit a negative amount.
'''
def __init__(self, owner, accountType):
self.owner = owner
self.accountType = accountType
self.balance = 0
def withdraw(self, amount):
if self.balance - amount < 0:
raise NotEnoughMoney('Cannot withdraw more than balance')
elif amount < 0:
raise NegativeAmount('Cannot withdraw negative amount')
else:
self.balance -= amount
def deposit(self, amount):
if amount < 0:
raise NegativeAmount('Cannot withdraw negative amount')
else:
self.balance += amount
def __str__(self):
if self.accountType == AccountType.CHECKING:
return 'a Checking'
elif self.accountType == AccountType.SAVINGS:
return 'a Savings'
else:
return 'No account'
def __len__(self):
return self.balance
# BankUser class
class BankUser():
def __init__(self,owner):
self.owner = owner
self.checking = None
self.savings = None
def addAccount(self,accountType):
if accountType == AccountType.SAVINGS:
if self.savings != None:
raise AccountError('Bank account of this type already present')
self.savings = BankAccount(self.owner,accountType)
elif accountType == AccountType.CHECKING:
if self.checking != None:
raise AccountError('Bank account of this type already present')
self.checking = BankAccount(self.owner,accountType)
else:
raise WrongTypeAccount('You cannot add this account')
def getBalance(self, accountType):
if accountType == AccountType.SAVINGS:
return self.savings.__len__()
if accountType == AccountType.CHECKING:
return self.checking.__len__()
def deposit(self, accountType, amount):
if accountType == AccountType.SAVINGS:
return self.savings.deposit(amount)
elif accountType == AccountType.CHECKING:
return self.checking.deposit(amount)
else:
raise WrongTypeAccount('You entered an invalid account type')
def withdraw(self, accountType, amount):
if accountType == AccountType.SAVINGS:
return self.savings.withdraw(amount)
elif accountType == AccountType.CHECKING:
return self.checking.withdraw(amount)
else:
raise WrongTypeAccount('You entered an invalid account type')
def __str__(self):
return 'User currently has {} and {} accounts'.format(self.checking,self.savings)
def ATMsession(bankUser):
def Interface():
exit_status = 0
user = bankUser
while exit_status !=1:
print('Hello, {}! What would you like to to today?'\
.format(bankUser.owner))
beginning = input('''Enter option:
\n1)Exit
\n2)Create account
\n3)Check balance
\n4)Deposit
\n5)Withdraw
\nThis is your input: ''')
if beginning == '1':
print('Exiting. Good bye!')
break
# Options for the type of account
typeaccount = input('''Enter option:
\n1)Checking
\n2)Savings
\nThis is your input: ''')
# Setting the type of bank account
if typeaccount == '1':
selected = AccountType.CHECKING
elif typeaccount == '2':
selected = AccountType.SAVINGS
# Creating bank account
if beginning == '2':
if typeaccount == '1':
try:
user.addAccount(selected)
print('Checking account created!')
except Exception as e:
print(e)
elif typeaccount == '2':
try:
user.addAccount(selected)
print('Savings account created!')
except Exception as e:
print(e)
else:
print('Wrong type of account')
# Checking balance. Needs to create a bank account first
if beginning == '3':
try:
print('Your balance in this account is {}'\
.format(user.getBalance(selected)))
except:
print('Please go back and create a bank account first')
# Creating a deposit
if beginning == '4':
amount = input('Please enter your deposit amount: ')
try:
amount = int(amount)
user.deposit(selected, amount)
print('Your amount of {} was succesfully deposited!'\
.format(amount))
print('Your balance in this account is {}'\
.format(user.getBalance(selected)))
except Exception as e:
print(e)
# Creating a withdrawal
if beginning == '5':
amount = input('Please enter your withdrawal amount: ')
try:
amount = int(amount)
user.withdraw(selected, amount)
print('Your amount of {} was succesfully withdrawn!'\
.format(amount))
print('Your balance in this account is {}'\
.format(user.getBalance(selected)))
except Exception as e:
print(e)
return Interface()
session = ATMsession(BankUser('Andrés')) |
15ba68ba65bc99ac0376575155ff45e0c73659e5 | aparrado/cs207_andres_parrado | /homeworks/HW2/HW2-final/P5a.py | 615 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 6 12:38:32 2020
@author: andresparrado
"""
def make_withdrawal(balance):
init_balance = balance
print("Your initial balance is",init_balance)
def withdraw(withdrawal_amount):
if init_balance - withdrawal_amount < 0:
print('This exceeds your amount. Stop.')
return None
else:
new_balance = init_balance - withdrawal_amount
return print("Your new balance is:", new_balance)
return withdraw
balance = 50
wd = make_withdrawal(balance)
wd(60) |
f84fdef224b8a97d88809dcf45fb0f574dc61ed4 | SnarkyLemon/VSA-Projects | /proj06/proj06.py | 2,181 | 4.15625 | 4 | # Name:
# Date:
# proj06: Hangman
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
# print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
# print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
def hangman():
wordlist = load_words()
word = choose_word(wordlist)
l = len(word)
# print l
ans_list = ["_"]*l
print ans_list
numguess = 6
print l, "letters long."
print word
while numguess > 0:
guess = raw_input("Guess a letter or word ")
for letter in guess:
if letter in word:
for num in range(len(word)):
if guess == word[num]:
ans_list[num] = guess
print "You've guessed correctly."
print ans_list
print str(ans_list)
if guess == word:
print("Wow I'm impressed")
if str(ans_list) == word:
print "You've correctly guessed the word. Also, this took like 6 hours to make, so no big deal."
elif guess not in word:
numguess -= 1
print ("Sorry, that's incorrect")
if numguess == 0:
print "sorry, out of tries"
if ans_list == word:
print "You win"
print ans_list
print str(ans_list), "is the string answer list"
hangman() |
fee1d7c30aa228e4859f7a8e2031d4a431466916 | jaanos/zelvje-dirke | /zelva.py | 622 | 3.53125 | 4 | import turtle
class Zelva(turtle.Turtle):
"""
Splošna želva.
"""
def __init__(self, ime, barva='green', hitrost=1):
"""
Konstruira želvo z danim imenom, barvo in hitrostjo.
"""
turtle.Turtle.__init__(self)
self.ime = ime
self.color(barva)
self.speed(hitrost)
def posodobi(self, pozicija):
"""
Posodobi želvo glede na njeno pozicijo.
Privzeto ne naredi nič.
"""
pass
def __str__(self):
"""
Vrne znakovno predstavitev želve z njenim imenom.
"""
return self.ime
|
b9bcd87a3d6d7826a6a74da5c3b63059f6701515 | Anmol1696/klargest | /klargest/models.py | 2,510 | 3.984375 | 4 | """
Models for working with heapq for adding data and keeping track of k largest values
"""
import heapq
class KLargest:
"""
Implements a class to hold min heap of constant length
for k largest values and additional information as keys
Values, stored in `self.values` are the k largest values,
which are stored and indexed as min heap
Keys, stored in `self.keys` are any arbitary objects associated
with the indexed values.
"""
value_index = 0
key_index = 1
def __init__(self, k=0):
self.heap = [] # Min heap of k largest values
if not isinstance(k, int) or k < 0:
raise Exception("k must be a positive int")
self.k = k
@property
def root(self):
"""
Return root of min heap
"""
return self.heap[0][0] if len(self.heap) > 0 else None
@property
def values(self):
"""
Return k largest values, not in any order
"""
return (x[self.value_index] for x in self.heap)
@property
def keys(self):
"""
Return keys related to k largest values, if specified with values
NOTE: For now, only returns single key at index 1
"""
return (x[self.key_index] for x in self.heap if len(x) > 1)
def add(self, num, *args):
"""
If given value is greater than root value,
replace root node and heapify to maintaing min heap of k length
"""
if len(self.heap) < self.k:
heapq.heappush(self.heap, (num, *args))
elif num > self.root:
heapq.heapreplace(self.heap, (num, *args))
@classmethod
def from_input_iter(cls, k, input_iter, extractor=lambda x: x, **kwargs):
"""
From an interger k, and input iterable form cls object and perform interation
iterate over input iterator, to store k largest values in min heap
extractor is the function to extract data from input
Return class object with k largest values
"""
# if k is zero, return zero value object
if k <= 0:
return cls(0)
k_largest = cls(k)
for line in input_iter:
k_largest.add(*extractor(line))
return k_largest
def process_stream_to_get_keys(k, input_iter, **kwargs):
"""
Given input iterable, store k largest value in KLargest
Return KLargest object keys
"""
k_largest = KLargest.from_input_iter(k, input_iter, **kwargs)
return k_largest.keys
|
c5eb6e78abf3f9844428fea2718aa096305df6fd | alexmehandzhiyska/softuni-python-basics | /05-while-loop/06-cake.py | 319 | 3.859375 | 4 | width = int(input())
length = int(input())
pieces = width * length
while pieces > 0:
command = input()
if command == 'STOP':
print(f'{pieces} pieces are left.')
exit()
pieces_eaten = int(command)
pieces -= pieces_eaten
print(f'No more cake left! You need {abs(pieces)} pieces more.') |
12578bebc71a9ea6b10205f8d0ae427ab4ba36ac | alexmehandzhiyska/softuni-python-basics | /04-for-loop/02-half-sum-element.py | 272 | 3.5625 | 4 | n = int(input())
max_num = 0
sum = 0
for i in range(n):
num = int(input())
if num > max_num:
max_num = num
sum += num
if max_num == sum - max_num:
print(f'Yes\nSum = {max_num}')
else:
print(f'No\nDiff = {abs(max_num - (sum - max_num))}') |
fb8bf25c92d07b7b70202eae995b7fe7d0217b08 | alexmehandzhiyska/softuni-python-basics | /06-nested-loops/02-equal-sums-even-odd-position.py | 372 | 3.75 | 4 | num1 = int(input())
num2 = int(input())
valid_nums = []
for num in range(num1, num2 + 1):
num_str = str(num)
sum_odd = int(num_str[1]) + int(num_str[3]) + int(num_str[5])
sum_even = int(num_str[0]) + int(num_str[2]) + int(num_str[4])
if sum_even == sum_odd:
valid_nums.append(num_str)
if len(valid_nums) > 0:
print((' ').join(valid_nums))
|
59673e8c44bd1d903252869f4efa28448791cf60 | alexmehandzhiyska/softuni-python-basics | /03-conditional-statements-advanced/04-fishing-boat.py | 565 | 3.84375 | 4 | budget = int(input())
season = input()
fishers_count = int(input())
rent_prices = { 'Spring': 3000, 'Summer': 4200, 'Autumn': 4200, 'Winter': 2600 }
rent = rent_prices[season]
if fishers_count <= 6:
rent *= 0.9
elif fishers_count <= 11:
rent *= 0.85
else:
rent *= 0.75
if fishers_count % 2 == 0 and season != 'Autumn':
rent *= 0.95
difference = abs(budget - rent)
if budget >= rent:
print(f'Yes! You have {"{:.2f}".format(difference)} leva left.')
else:
print(f'Not enough money! You need {"{:.2f}".format(difference)} leva.') |
f45eb498c0088ee757ea6c2a05d682f300f35100 | CristhianCastillo/introduction-computational-thinking-python | /edades_usuarios.py | 551 | 3.875 | 4 | def run ():
user_name_1 = input("USUARIO_1: Ingresa tu nombre: ")
user_age_1 = int(input("USUARIO_1: Ingresa tu edad: "))
user_name_2 = input("USUARIO_2: Ingresa tu nombre: ")
user_age_2 = int(input("USUARIO_2: Ingresa tu edad: "))
if(user_age_1 > user_age_2):
print(f'{user_name_1} es mayor que {user_name_2}')
elif user_age_2 > user_age_1:
print(f'{user_name_2} es mayor que {user_name_1}')
else:
print(f'{user_name_1} tiene la misma edad de {user_name_2}')
if __name__ == "__main__":
run() |
4055f749736fc7854a3035a60e8c98611cad0de9 | CristhianCastillo/introduction-computational-thinking-python | /abstraccion_funciones.py | 1,532 | 3.84375 | 4 | # Constants
EPSILON = 0.001
# Functions
def exhaustive_search(goal):
result = 0
while result ** 2 < goal:
result += 1
if result ** 2 == goal:
print(f"La raiz cuadrada de {goal} es {result}.")
else:
print(f"{goal} no tiene raiz cuadra exacta.")
def search_approximation(goal, epsilon):
step = epsilon**2
result = 0.0
while abs(goal - result**2) >= epsilon and result <= goal:
result += step
if abs(result**2 - goal) >= epsilon:
print("No se encontro la raiz cuadrada del objetivo.")
else:
print(f"La raiz cuadra de {goal} es {result}.")
def binary_search(goal, epsilon):
low = 0.0
high = max(1.0, goal)
result = (high + low) / 2
while abs(result**2 - goal) >= epsilon:
if result**2 < goal:
low = result
else:
high = result
result = (high + low) / 2
print(f"Al raiz cuadrada de {goal} es {result}.")
def run():
goal = int(input("Ingresa un numero: "))
option = int(input(f"""Selecciona uno de los siguientes metodos para intentar calcular la raiz cuadra del numero {goal}
1. Busqueda Exaustiva, 2. Buscqueda por Aproximaciòn, 3. Busqueda Binaria
Opcion: """))
if option == 1:
exhaustive_search(goal)
elif option == 2:
search_approximation(goal, EPSILON)
elif option == 3:
binary_search(goal, EPSILON)
else:
print("La opcion ingresada no es valida.")
if __name__ == "__main__":
run() |
39c50a39962f9e8e1b0412a6f911e4c08431853b | cheekclapper69/01_Lucky_Unicorn | /03_coffee.py | 1,003 | 3.96875 | 4 |
if token == "unicorn":
# prints unicorn statement
print()
print("***********************************************************")
print("***** Congratulations! it,s a ${:.2f} {}*****".format(UNICORN, token))
print("***********************************************************")
balance += UNICORN # wins $5
elif token == "donkey":
print()
print("---------------------------------------------------------------")
print("| Sorry. it's a {}. You did not win anything this round |".format(token))
print("---------------------------------------------------------------")
balance -= COST # wins nothing (loses $1)
else:
print()
print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
print("< Good try. It's a {}. You won back 50c>".format(token))
print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
balance -= horse_zebra # 'wins' 50c, paid $1 so loses 50c |
5bdd1fc2beb202a1ab028a3569900c3ab34367d3 | Quatroctus/cs362-git-activity | /password.py | 549 | 3.59375 | 4 | from random import choice, shuffle
def gen_password(n: int):
digits = "0123456789"
symbols = "!@#$%^&*()[]{}\|/?><,.`~"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()[]{}\|/?><,.`~0123456789"
a = []
if n > 2:
a.append(choice(digits))
a.append(choice(symbols))
n -= 2
for _ in range(n):
a.append(choice(alphabet))
shuffle(a)
p = "".join(a)
print(p)
return p
if __name__ == "__main__":
gen_password(int(input("Please enter password length: ")))
|
eea72a173f8ca1ed7025bfb5548068ee1fb56603 | dorishay1/Demographic_Data_Analyzer_python_freecodecamp | /demographic_data_analyzer.py | 4,443 | 4.1875 | 4 | import pandas as pd
def calculate_demographic_data(print_data=True):
# Read data from file
df = pd.read_csv('adult.data.csv')
# How many of each race are represented in this dataset? This should be a Pandas series with race names as the index labels.
race_count = df['race'].value_counts()
# What is the average age of men?
mask_male = df['sex'] == 'Male'
average_age_men = round(df[mask_male].age.mean(),1)
# What is the percentage of people who have a Bachelor's degree?
bach_sum = len(df[df['education'] == 'Bachelors'])
total_sum = len(df)
percentage_bachelors = round((bach_sum/total_sum)*100,1)
# What percentage of people with advanced education (`Bachelors`, `Masters`, or `Doctorate`) make more than 50K?
# What percentage of people without advanced education make more than 50K?
# with and without `Bachelors`, `Masters`, or `Doctorate`
H_edu = ['Bachelors', 'Masters', 'Doctorate']
H_edu_df = df[df.education.isin(H_edu)]
H_edu_rich = H_edu_df[H_edu_df['salary'] == '>50K']
higher_education = round(len(H_edu_rich)/len(H_edu_df)*100,1)
L_edu_df = df[~df.education.isin(H_edu)]
L_edu_rich = L_edu_df[L_edu_df['salary'] == '>50K']
lower_education = round(len(L_edu_rich)/len(L_edu_df)*100,1)
# percentage with salary >50K
higher_education_rich = higher_education
lower_education_rich = lower_education
# What is the minimum number of hours a person works per week (hours-per-week feature)?
min_work_hours = df['hours-per-week'].min()
# What percentage of the people who work the minimum number of hours per week have a salary of >50K?
min_work_hours = df['hours-per-week'].min()
mask_min_work = df['hours-per-week'] == min_work_hours
num_min_workers = sum(mask_min_work)
mask_rich = df['salary'] == '>50K'
rich_lazy = df[mask_rich & mask_min_work]
rich_percentage = round((len(rich_lazy)/sum(mask_min_work))*100,1)
# What country has the highest percentage of people that earn >50K?
total_by_state = df['native-country'].value_counts()
country_list = df['native-country'].unique()
temp = []
for country in country_list:
country_mask = df['native-country'] == country
rich_per_country = df[country_mask & mask_rich]
rich_precent_country = round((len(rich_per_country)/sum(country_mask))*100,1)
temp.append([country,rich_precent_country])
perc = pd.DataFrame(temp,columns=['country', 'rich_percentage'])
rich_idx = perc['rich_percentage'].idxmax()
highest_earning_country = perc.iloc[rich_idx].country
highest_earning_country_percentage = perc.iloc[rich_idx].rich_percentage
# Identify the most popular occupation for those who earn >50K in India.
india_mask = df['native-country'] == 'India'
india_rich_df = df[india_mask & mask_rich]
occ_list = india_rich_df['occupation'].value_counts()
top_IN_occupation = occ_list.index[0]
# DO NOT MODIFY BELOW THIS LINE
if print_data:
print("Number of each race:\n", race_count)
print("Average age of men:", average_age_men)
print(f"Percentage with Bachelors degrees: {percentage_bachelors}%")
print(f"Percentage with higher education that earn >50K: {higher_education_rich}%")
print(f"Percentage without higher education that earn >50K: {lower_education_rich}%")
print(f"Min work time: {min_work_hours} hours/week")
print(f"Percentage of rich among those who work fewest hours: {rich_percentage}%")
print("Country with highest percentage of rich:", highest_earning_country)
print(f"Highest percentage of rich people in country: {highest_earning_country_percentage}%")
print("Top occupations in India:", top_IN_occupation)
return {
'race_count': race_count,
'average_age_men': average_age_men,
'percentage_bachelors': percentage_bachelors,
'higher_education_rich': higher_education_rich,
'lower_education_rich': lower_education_rich,
'min_work_hours': min_work_hours,
'rich_percentage': rich_percentage,
'highest_earning_country': highest_earning_country,
'highest_earning_country_percentage':
highest_earning_country_percentage,
'top_IN_occupation': top_IN_occupation
}
|
d7736ee0897218affa62d98dbb4117ff96d59818 | djmgit/Algorithms-5th-Semester | /FastPower.py | 389 | 4.28125 | 4 | # function for fast power calculation
def fastPower(base, power):
# base case
if power==0:
return 1
# checking if power is even
if power&1==0:
return fastPower(base*base,power/2)
# if power is odd
else:
return base*fastPower(base*base,(power-1)/2)
base=int(raw_input("Enter base : "))
power=int(raw_input("Enter power : "))
result=fastPower(base,power)
print result
|
ec12c6c77432475f71ae4f7efb6ef4fc0d80cbcf | KrishanSritharar2000/Modelling-Quantum-Gravity | /turtle/Grid.py | 2,643 | 3.96875 | 4 | #Grid
import turtle
from Main2 import *
pen = turtle.Turtle()
turtle.delay(0)
pen.ht()
turtle.colormode(255)
turtle.tracer(0,0)
def grid(col, row, len_th, mode, coordinates):
width = turtle.window_width()
height = turtle.window_height()
x1 = round((0)- ((col/2)*len_th),0)#These two lines centre the grid
y1 = round((0) + ((row/2)*len_th),0)
x,y = x1,y1
print("X",x,"Y",y)
print("X1",x1+(col*len_th),"Y1",y1+(col*len_th))
pen.begin_fill()
fill(255,255,255)
rect(x1,y1,(col*len_th),(row*len_th))#+len_th/2
pen.end_fill()
if mode.lower() == "random":
for i in range(col*row):
x = random.randint(x1,x1+(col*len_th))
y = random.randint(y1, y1+(row*len_th))
pen.pensize(2)
point(x,y)
pen.pensize(1)
coordinates.append([x,y])
print("Done")
# coordinates_dict[x,y] = i
return coordinates
# return coordinates_dict
else:
for j in range(row):# These two for loops draw the grid
for k in range(col+1):
stroke(0,0,0)# Sets the colour of the line and controls the transparancy of the line (0 is completely transparant, 255 is completely opaque)
if mode.lower() == "square":
rect(x,y,len_th,len_th)
elif mode.lower() == "triangle":
triangle(x,y,x+len_th,y,x+(len_th/2),y+len_th)
x += len_th
y -= len_th
if mode.lower() == "square":
x = x1
elif mode.lower() == "triangle":
if j % 2:
x = x1
else:
x = x1 - (len_th/2)
clear_excess(col, row, len_th)
turtle.update()
def clear_excess(col,row,len_th):
colour = turtle.bgcolor()
pen.pencolor(colour)
pen.pensize(1)
pen.begin_fill()
pen.fillcolor(colour)
rect(((0)-((col/2)*len_th))-len_th*2,((0)+((row/2)*len_th)),len_th*2,len_th*row)
pen.end_fill()
pen.begin_fill()
pen.fillcolor(colour)
rect(((0)+((col/2)*len_th)),((0)+((row/2)*len_th)),len_th*2,len_th*row)
pen.end_fill()
stroke(0,0,0)
## line(((0)+((col/2)*len_th)),((0)-((row/2)*len_th)),((0)+((col/2)*len_th)),((1)+((row/2)*len_th)))
stroke(0,0,0)
## line(((0)-((col/2)*len_th)),((0)-((row/2)*len_th)),((0)-((col/2)*len_th)),((1)+((row/2)*len_th)))
if __name__ == "__main__":
mode = "sqaure"
coord = []
grid(10,10,10,mode,coord)
|
0f40ebd07a5dbce3f230fc2a22ff9b488be6d2b4 | KrishanSritharar2000/Modelling-Quantum-Gravity | /turtle/scipySim2.py | 18,044 | 3.5 | 4 | #Krishan Sritharar
#Random Walks
import random
import turtle
from scipy import spatial
from Grid import *
pen = turtle.Turtle()
turtle.delay(0)
pen.ht()
turtle.colormode(255)
turtle.tracer(0,0)
def setup():
fullScreen()
noLoop()
def point(x,y):
pen.up()
pen.goto(x,y)
pen.down()
pen.dot()
def line(x1,y1,x2,y2):
pen.up()
pen.goto(x1,y1)
pen.down()
angle = pen.towards(x2,y2)
distance = pen.distance(x2,y2)
pen.seth(angle)
pen.forward(distance)
def rect(x1,y1,len_th_1,len_th_2):
pen.up()
pen.goto(x1,y1)
pen.down()
for i in range(2):
pen.forward(len_th_1)
pen.right(90)
pen.forward(len_th_2)
pen.right(90)
pen.up()
def traingle():
pass
def stroke(r,g,b):
col = (r,g,b)
pen.pencolor(col)
def fill(r,g,b):
col = (r,g,b)
pen.fillcolor(col)
def drawLines(walk_num, step_num, col, row, len_th, mode, begin, Pright, Pleft, Pdown, Pup, Prightdown, Prightup, Pleftdown, Pleftup):
xaverage_array = []
yaverage_array = []
avg = []
if mode.lower() == "square":
for num in range(walk_num):
if begin == 1:#start at centre
x = (displayWidth/2)
elif begin == 2:#start at left
x = (displayWidth/2) - ((col/2)*len_th)
elif begin == 3: #start at right
x = (displayWidth/2) + ((col/2)*len_th)
xpos = x
y = (displayHeight/2)
for j in range(step_num):
if x == ((displayWidth/2) - ((col/2)*len_th)) and y == ((displayHeight/2) - ((row/2)*len_th)):#this prevent the line going off the grid
numbers = [0,2]
elif x == ((displayWidth/2) - ((col/2)*len_th)) and y == ((displayHeight/2) + ((row/2)*len_th)):
numbers = [0,3]
elif x == ((displayWidth/2) + ((col/2)*len_th)) and y == ((displayHeight/2) - ((row/2)*len_th)):#these are the corners
numbers = [1,2]
elif x == ((displayWidth/2) + ((col/2)*len_th)) and y == ((displayHeight/2) + ((row/2)*len_th)):
numbers = [1,3]
elif x == ((displayWidth/2) - ((col/2)*len_th)):#these are the edges
numbers = [0,2,3]
elif y == ((displayHeight/2) - ((row/2)*len_th)):
numbers = [0,1,2]
elif x == ((displayWidth/2) + ((col/2)*len_th)):
numbers = [1,2,3]
elif y == ((displayHeight/2) + ((row/2)*len_th)):
numbers = [0,1,3]
else:
numbers = [0,1,2,3]
weights = []
for i in range(len(numbers)):
if numbers[i] == 0:
for k in range(int(Pright*100)):
weights.append(0)
if numbers[i] == 1:
for k in range(int(Pleft*100)):
weights.append(1)
if numbers[i] == 2:
for k in range(int(Pdown*100)):
weights.append(2)
if numbers[i] == 3:
for k in range(int(Pup*100)):
weights.append(3)
number = random.choice(weights)#generates a random number
stroke(0)
pen.pensize(2)(3)
if number == 0:
line(x,y,x+len_th,y)#right
x += len_th
elif number == 1:
line(x,y,x-len_th,y)#left
x -= len_th
elif number == 2:
line(x,y,x,y+len_th)#down
y += len_th
elif number == 3:
line(x,y,x,y-len_th)#up
y -= len_th
avg.append([x,y])
print("Average = ",avg)
stroke(0)
pen.pensize(2)(3)
point(x,y)
xaverage_array.append(x)
yaverage_array.append(y)
## fill(0,0,0)
## textSize(10)
## text(num+1,x,y)#writes a number to link the line to the walk_num
elif mode.lower() == "triangle":
for num in range(walk_num):
if begin == 1:#start at centre
x = (displayWidth/2)
elif begin == 2:#start at left
x = (displayWidth/2) - ((col/2)*len_th)
elif begin == 3: #start at right
x = (displayWidth/2) + ((col/2)*len_th)
xpos = x
y = (displayHeight/2)
for j in range(step_num):
if x == ((displayWidth/2) - ((col/2)*len_th)) and y == ((displayHeight/2) - ((row/2)*len_th)):#this prevent the line going off the grid
numbers = [0,2]#topleft
elif x == ((displayWidth/2) - ((col/2)*len_th)) and y == ((displayHeight/2) + ((row/2)*len_th)):
numbers = [0,3]#bottomleft
elif x == ((displayWidth/2) + ((col/2)*len_th)) and y == ((displayHeight/2) - ((row/2)*len_th)):#these are the corners
numbers = [1,4]#topright
elif x == ((displayWidth/2) + ((col/2)*len_th)) and y == ((displayHeight/2) + ((row/2)*len_th)):
numbers = [1,5]#bottomright
elif x == ((displayWidth/2) - ((col/2)*len_th)) or x == ((displayWidth/2) - ((col/2)*len_th) + (len_th/2)):#these are the edges
numbers = [0,2,3]#left edge
elif y == ((displayHeight/2) - ((row/2)*len_th)):
numbers = [0,1,2,4]#top edge
elif x == ((displayWidth/2) + ((col/2)*len_th)) or x == ((displayWidth/2) + ((col/2)*len_th) - (len_th/2)):
numbers = [1,4,5]#right edge
elif y == ((displayHeight/2) + ((row/2)*len_th)):
numbers = [0,1,3,5]#bottom edge
else:
numbers = [0,1,2,3,4,5]
weights = []
for i in range(len(numbers)):
if numbers[i] == 0:
for k in range(int(Pright*100)):
weights.append(0)
if numbers[i] == 1:
for k in range(int(Pleft*100)):
weights.append(1)
if numbers[i] == 2:
for k in range(int(Prightdown*100)):
weights.append(2)
if numbers[i] == 3:
for k in range(int(Prightup*100)):
weights.append(3)
if numbers[i] == 4:
for k in range(int(Pleftdown*100)):
weights.append(4)
if numbers[i] == 5:
for k in range(int(Pleftup*100)):
weights.append(5)
number = random.choice(weights)#generates a random number
stroke(0)
pen.pensize(2)(3)
if number == 0:
line(x,y,x+len_th,y)#right
x += len_th
elif number == 1:
line(x,y,x-len_th,y)#left
x -= len_th
elif number == 2:
line(x,y,x+(len_th/2),y+len_th)#down right
y += len_th
x += (len_th/2)
elif number == 3:
line(x,y,x+(len_th/2),y-len_th)#up right
y -= len_th
x += (len_th/2)
elif number == 4:
line(x,y,x-(len_th/2),y+len_th)#down left
y += len_th
x -= (len_th/2)
elif number == 5:
line(x,y,x-(len_th/2),y-len_th)#up left
y -= len_th
x -= (len_th/2)
avg.append([x,y])
stroke(0)
pen.pensize(2)(3)
point(x,y)
xaverage_array.append(x)
yaverage_array.append(y)
fill(0)
textSize(10)
text(num+1,x,y)#writes a number to link the line to the walk_num
averageline1(xaverage_array,yaverage_array,xpos)
averageline2(step_num,walk_num,avg,xpos)
def drawLinesRandom(walk_num, step_num, col, row, len_th, begin, coord, Pright, Pleft, Pdown, Pup):
if begin == 1:#start at centre
x = (displayWidth/2)
elif begin == 2:#start at left
x = (displayWidth/2) - ((col/2)*len_th)
elif begin == 3: #start at right
x = (displayWidth/2) + ((col/2)*len_th)
xpos = x
y = (displayHeight/2)
xaverage_array = []
yaverage_array = []
avg = []
print("Coord: ", coord)
point_tree = scipy.spatial.cKDTree(coord)
space = abs(len_th/(row*col))
print("Points = ",point_tree.data[point_tree.query_ball_point([xpos,y],space)])
# def getKeyX(item):
# return item[0]
# def getKeyY(item):
# return item[1]
# coord_x = sorted(coord, key=getKeyX)
# coord_y = sorted(coord, key=getKeyY)
# print()
# print("Coord_x: ",coord_x)
# print()
# print("Coord_y: ",coord_y)
# print("Coordinate 1: ", coord)
# print("")
# print("Coordinates 2: ", coord2)
# print("Nearest To beginning: ",coord2.nearest_key((xpos,y)))
# temp = coord2.nearest_key((xpos,y))
# print("Temp : ",temp)
# temp_x = temp[0]
# temp_y = temp[1]
# print("Temp X :",temp[0])
# print("Temp Y :",temp[1])
# stroke(0,255,0)
# line(temp_x,temp_y,displayWidth/2,y)
# for num in range(walk_num):
# if begin == 1:#start at centre
# x = (displayWidth/2)
# elif begin == 2:#start at left
# x = (displayWidth/2) - ((col/2)*len_th)
# elif begin == 3: #start at right
# x = (displayWidth/2) + ((col/2)*len_th)
# xpos = x
# y = (displayHeight/2)
# prevx,prevy = x,y
# temp_coord_x = []
# temp_coord_y = []
# space = abs(len_th/(row*col))
# # space = 30
# for j in range(step_num):
# while len(temp_coord_x) == 0:
# for i in range(len(coord_x)):
# temp_x = (coord_x[i][0])
# # print("Temp - space: ",(temp_x - space ))
# # print("Temp + space: ",(temp_x + space ))
# if (prevx - space ) <= temp_x <= (prevx + space):
# temp_coord_x.append(coord_x[i])
# space += 2
# print("TempX",temp_coord_x)
# print("ABS",abs(len_th/(row*col)))
# print("new space", space)
# space = abs(len_th/(row*col))
# # space = 30
# while len(temp_coord_y) == 0:
# for i in range(len(coord_y)):
# temp_y = (coord_y[i][0])
# # print("Temp - space: ",(temp_y - space ))
# # print("Temp + space: ",(temp_y + space ))
# if (prevy - space ) <= temp_y <= (prevy + space):
# temp_coord_y.append(coord_y[i])
# space += 2
# print("TempXY",temp_coord_y)
# print("ABS",abs(len_th/(row*col)))
# print("new space", space)
# for i in range(len(temp_coord_x)):
# stroke(255,0,0)
# strokeWeight(5)
# point(temp_coord_x[i][0], temp_coord_x[i][1])
# print("Donex")
# for i in range(len(temp_coord_y)):
# stroke(0,255,0)
# strokeWeight(5)
# point(temp_coord_y[i][0], temp_coord_y[i][1])
# for j in range(step_num):
# if x == ((displayWidth/2) - ((col/2)*len_th)) and y == ((displayHeight/2) - ((row/2)*len_th)):#this prevent the line going off the grid
# numbers = [0,2]
# elif x == ((displayWidth/2) - ((col/2)*len_th)) and y == ((displayHeight/2) + ((row/2)*len_th)):
# numbers = [0,3]
# elif x == ((displayWidth/2) + ((col/2)*len_th)) and y == ((displayHeight/2) - ((row/2)*len_th)):#these are the corners
# numbers = [1,2]
# elif x == ((displayWidth/2) + ((col/2)*len_th)) and y == ((displayHeight/2) + ((row/2)*len_th)):
# numbers = [1,3]
# elif x == ((displayWidth/2) - ((col/2)*len_th)):#these are the edges
# numbers = [0,2,3]
# elif y == ((displayHeight/2) - ((row/2)*len_th)):
# numbers = [0,1,2]
# elif x == ((displayWidth/2) + ((col/2)*len_th)):
# numbers = [1,2,3]
# elif y == ((displayHeight/2) + ((row/2)*len_th)):
# numbers = [0,1,3]
# else:
# numbers = [0,1,2,3]
# weights = []
# for i in range(len(numbers)):
# if numbers[i] == 0:
# for k in range(int(Pright*100)):
# weights.append(0)
# if numbers[i] == 1:
# for k in range(int(Pleft*100)):
# weights.append(1)
# if numbers[i] == 2:
# for k in range(int(Pdown*100)):
# weights.append(2)
# if numbers[i] == 3:
# for k in range(int(Pup*100)):
# weights.append(3)
# number = random.choice(weights)#generates a random number
# stroke(0)
# strokeWeight(3)
# if number == 0:
# line(x,y,x+len_th,y)#right
# x += len_th
# elif number == 1:
# line(x,y,x-len_th,y)#left
# x -= len_th
# elif number == 2:
# line(x,y,x,y+len_th)#down
# y += len_th
# elif number == 3:
# line(x,y,x,y-len_th)#up
# y -= len_th
# avg.append([x,y])
# print("Average = ",avg)
# stroke(0)
# strokeWeight(3)
# point(x,y)
# xaverage_array.append(x)
# yaverage_array.append(y)
# fill(0)
# textSize(10)
# text(num+1,prevx,prevy)#writes a number to link the line to the walk_num
# averageline1(xaverage_array,yaverage_array,xpos)
# averageline2(step_num,walk_num,avg,xpos)
def averageline1(xaverage_array,yaverage_array,xpos):
sum_of_x,sum_of_y = 0,0
for l in range(len(xaverage_array)):
sum_of_x += xaverage_array[l]
sum_of_y += yaverage_array[l]
xaverage = sum_of_x / len(xaverage_array)
yaverage = sum_of_y / len(yaverage_array)
stroke(255,0,0)
strokeWeight(3)
line(xpos,(displayHeight/2),xaverage,yaverage)
def averageline2(step_num,walk_num,average_array,xpos):
x = xpos
y = (displayHeight/2)
prevx = x
prevy = y
xaverage = []
yaverage = []
for i in range(step_num*walk_num):
xaverage.append(average_array[i][0])
yaverage.append(average_array[i][1])
for j in range(step_num):
xaverage_t = xaverage[j::step_num]
yaverage_t = yaverage[j::step_num]
print("Xaverage_t:", xaverage_t)
sum_of_x,sum_of_y = 0,0
for k in range(len(xaverage_t)):
sum_of_x += xaverage_t[k]
sum_of_y += yaverage_t[k]
temp_xaverage = sum_of_x / len(xaverage_t)
temp_yaverage = sum_of_y / len(yaverage_t)
stroke(0,0,255)
line(prevx,prevy,temp_xaverage,temp_yaverage)
prevx = temp_xaverage
prevy = temp_yaverage
def draw():
column = 10
row = 10
space = 40
mode = "square" #"square","triangle","random"
num_of_steps = 1
num_of_walks = 1
begin = 2
name = "Sqaure with Second Average5"
Pdown = 0.20
Pup = 0.20
Pright = 0.30
Pleft = 0.30
Prightdown = 0.10
Prightup = 0.10
Pleftdown = 0.10
Pleftup = 0.10
coordinates = []
# coordinates_dict = NearestDict(2)
turtle.bgcolor("grey")
grid(column,row,space,mode, coordinates)
## if mode.lower() == "square" or mode.lower() == "triangle":
## drawLines(num_of_walks, num_of_steps, column, row, space, mode, begin, Pright, Pleft, Pdown, Pup, Prightdown, Prightup, Pleftdown, Pleftup)
## elif mode.lower() == "random":
## drawLinesRandom(num_of_walks, num_of_steps, column, row, space, begin,coordinates, Pright, Pleft, Pdown, Pup)
## saveFrame("Walk_{}.png".format(name))
if __name__ == "__main__":
draw()
|
719112abb89b446104833235b2022c0a5ed3ad49 | kingspider/CodinGame | /MIME Type.py | 884 | 3.875 | 4 | import sys
import math
minemap = {}
mineext = []
def extension(filename):
""" Function takes a filename reverses it and then gets the extension. """
fileextention = ""
for char in filename:
if char == ".":
fileextention = fileextention[::-1]
return fileextention.lower()
else:
fileextention = fileextention + char
n = int(input()) # Number of elements which make up the association table.
q = int(input()) # Number Q of file names to be analyzed.
for minedata in range(n):
# ext: file extension
# mt: MIME type.
ext, mt = input().split()
ext = ext.lower()
minemap[ext] = mt
mineext.append(ext)
for lines in range(q):
fname = input() # One file name per line.
if extension(fname[::-1]) in mineext:
print(minemap[extension(fname[::-1])])
else:
print("UNKNOWN")
|
47f8774a796e018036c88eadc8b9f8bfbf20348f | JoanMora/UCD-Data-Science-in-Python | /Introduction to Data Science/Lab/overlap.py | 332 | 3.5625 | 4 | import sys
def parseData(File):
try:
f = open(File, "r")
num = set()
for number in f.readlines():
num.add(number.strip())
f.close()
except FileNotFoundError:
print("Warning: File not found")
return num
file1 = parseData(sys.argv[1])
file2 = parseData(sys.argv[2])
print("Overlap: ", file1.intersection(file2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.