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
2d0187fa36da96f8db03db56e6ba363563a4b2d6
zhenzey/machine_learning_project
/Housing_price/feature_engineering.py
6,842
3.546875
4
#! /bin/env/python3 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy from scipy import stats from scipy.stats import norm, skew from scipy.special import boxcox1p import sklearn from sklearn import preprocessing class Feature: def __init__(self, df): self.data_frame = df def visualization(self, column): """ Visualize the scattering plot of certain feature :return: """ x = self.data_frame[column] y = self.data_frame["SalePrice"] fig, ax = plt.subplots() ax.scatter(x, y) plt.ylabel("SalePrice", fontsize=13) plt.xlabel(column, fontsize=13) plt.show() def corr_map(self): """ Plot the heatmap showing the correlation of different features :return: """ corr_mat = self.data_frame.corr() plt.subplots(figsize=(12, 11)) sns.heatmap(corr_mat, vmax=1.0, square=True) plt.show() def y_distribution(self): """ Plot the distribution of y to make sure that it observes Gaussian distribution, if not, transform the data using log :return: """ y = self.data_frame["SalePrice"] sns.distplot(y, fit=norm) plt.show() def log_transformation(self, column): """ Transform the data y(in our case, sale prices) with the form: y -> log(y + c) :return: c which leads to the best fit of normal distribution """ # #r_square_max = 0 # c_max = 0 # print(self.data_frame[column]) # for c in np.logspace(0, int(np.log10(self.data_frame[column].max())), 50): # temp = np.log(c + self.data_frame[column]) # r_square = stats.probplot(temp)[1][2] # if r_square > r_square_max: # c_max = c # r_square_max = r_square # self.data_frame[column] = np.log(self.data_frame[column] + c_max) # res = stats.probplot(self.data_frame[column], plot=plt) # plt.show() # return self.data_frame self.data_frame[column] = np.log1p(self.data_frame[column]) return self.data_frame def missing_value(self, column): """ Input the missing values rule: :return: """ # Case 1 # Features for which "NaN" means "None", e.p. df["Fence"] = "NaN" means the house does not have fence cate = np.array( ["Alley", "Fence", "FireplaceQu", "MiscFeature", "PoolQC", "GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtQual", "BsmtCond", "BsmtExposure", "BsmtFinType1", "BsmtFinType2", "MasVnrType", "MSSubClass"]) if any(cate == column): self.data_frame[column] = self.data_frame[column].fillna("None") # Case 2 # Feature for which "NaN" means 0, e.p. df["GarageArea"] = "NaN" means the area of the garage is 0 # Though it seems the same as case 1, 0 is a numerical value while "None" is a categorical value cate = np.array( ["GarageYrBlt", "GarageArea", "GarageCars", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "TotalBsmtSF", "BsmtFullBath", "BsmtHalfBath", "MasVnrArea"] ) if any(cate == column): self.data_frame[column] = self.data_frame[column].fillna(0) # Case 3 # Feature which is skewed, so we can give the value which is most frequent to replace "NaN" cate = np.array( ["MSZoning", "Electrical", "KitchenQual", "Exterior1st", "Exterior2nd", "SaleType"] ) if any(cate == column): self.data_frame[column] = self.data_frame[column].fillna(self.data_frame[column].mode()[0]) # Case 4, 5, 6, 7 # Feature --- Utilities, for nearly all examples, categorical values are Allpub, so we can drop it # Feature --- Functional, according to data description, "NaN" means typical # Feature --- LotFrontage, the houses in the same neighborhood have similar lot frontage, we assume the lot # frontage observes Gaussian distribution if column == "Utilities": self.data_frame = self.data_frame.drop(["Utilities"], axis=1) elif column == "Functional": self.data_frame[column] = self.data_frame[column].fillna("Typ") elif column == "LotFrontage": self.data_frame[column] = self.data_frame.groupby("Neighborhood")[column].transform( lambda x: x.fillna(np.random.normal(x.mean(), x.std())) ) return self.data_frame def num2cat(self, column): """ Transfer the numerical feature into categorical feature for those features that are really categorical The features includes MSSubClass, overall rank(optional), year and month build/reconstructed e.p. MSSubClass, details can be found in data_description.txt :return: """ cate = np.array(["MSSubClass", "OverallQual", "OverallCond", "YearRemodAdd", "YearBuilt", "GarageYrBlt", "MoSold", "YrSold" ]) #cate = np.array(["MSSubClass", "OverallQual", "MoSold", "YrSold"]) if any(cate == column): self.data_frame[column] = self.data_frame[column].astype(str) return self.data_frame def labelencoder(self, column): """ Using sklearn.preprocessing.labelEncoder to transfer categorical value into numerical values Sklearn.preprocessing.labelEncoder reference:https://scikit-learn.org/stable/modules/generated/ sklearn.preprocessing.LabelEncoder.html :return: """ label = preprocessing.LabelEncoder() cate = np.array(["FireplaceQu", "BsmtQual", "BsmtCond", "GarageQual", "GarageCond", "ExterQual", "ExterCond","HeatingQC", "PoolQC", "KitchenQual", "BsmtFinType1", "BsmtFinType2", "Functional", "Fence", "BsmtExposure", "GarageFinish", "LandSlope", "LotShape", "PavedDrive", "Street", "Alley", "CentralAir", "MSSubClass", "OverallCond", "YrSold", "MoSold"]) if any(cate == column): label.fit(list(self.data_frame[column].values)) self.data_frame[column] = label.transform(list(self.data_frame[column].values)) return self.data_frame def skewed_feature(self, column): """ Dealing with the skewed features using Box Cox transformation Don't worry about the math Ps: log transformation is also working, but when dealing with negative skewed feature, the data should be reflected first :return: """ lam = 0.15 self.data_frame[column] = boxcox1p(self.data_frame[column], lam) return self.data_frame
b8e831219b276d62e3f1d46bc82edfacc536b352
PrashantThakurNitP/python-december-code
/com line arg sum.py
262
3.625
4
from sys import argv print("Inside com line arg sum.py program") count=0 y=0 for x in argv: if x=='com line arg sum.py': continue y=y+int(x) count+=1 print("Total no of argument is {} and the sum of argument is {}".format(count,y))
350e9388ab21ee5c0ad8d09c811bade6f5bfcf16
ANUGEETHA03/Network_Automation
/Registration_login.py
1,985
3.734375
4
from flask import Flask, render_template, redirect, url_for, request data = {} app=Flask(__name__,template_folder="templates") @app.route('/') #Function for displaying the Initial Webpage def intro(): return render_template('intro.html') @app.route('/register.html') #Function for displaying the Register page after clicking register button def register(): return render_template('register.html') @app.route('/login.html') #Function for displaying the Login page after clicking Login button def login(): return render_template('login.html') @app.route('/register_data.html', methods = ['GET','POST']) #Function which GET or retrieves the data(username and password)once we enter the credentials and stores it in register_data.html(virtual location) def register_data(): if request.method == 'GET' : user_name = request.args.get('username','') if user_name not in data.keys(): pass_word = request.args.get('password','') print('Username :' + user_name + ' Password: ' + pass_word) data.update({user_name : pass_word}) print(data) return("Registered Successfully") else: print("Username already exists!!") return("This username is already taken") @app.route('/login_data.html', methods = ['GET','POST']) #Function which check whether the user is already registerd by retrieving data from vitual location login_data.html def login_data(): if request.method == 'GET' : user_name = request.args.get('username','') pass_word = request.args.get('password','') print('Username :' + user_name + ' Password: ' + pass_word) if user_name not in data.keys(): return("This username does not exist,Do you want to register now?") elif(data[user_name] != pass_word): return("Invalid username or password") elif(data[user_name] == pass_word): return render_template('loginSuccess.html', user = user_name) else: return("Internal server error 500") if __name__=='__main__': app.debug =True app.run(host='192.168.44.159',port=80)
20bb2786fcfa8e46ad2eb5af1b5ae6459a392483
sclie001/shellhacks2020
/icebreaker.py
38,463
3.609375
4
from random import randrange def choose_icebreaker(): icebreakers = ['What was your first job?', 'Have you ever met anyone famous?', 'What are you reading right now?', 'If you could pick up a new skill in an instant what would it be?', 'Who’s someone you really admire?', 'Seen any good movies lately you’d recommend?', 'Got any favorite quotes?', 'Been pleasantly surprised by anything lately?', 'What was your favorite band 10 years ago?', 'What’s your earliest memory?', 'Been anywhere recently for the first time?', 'What’s your favorite family tradition?', 'What was the first thing you bought with your own money?', 'What’s something you want to do in the next year that you’ve never done before?', 'Seen anything lately that made you smile?', 'What’s your favorite place you’ve ever visited?', 'Have you had your 15 minutes of fame yet?', 'What’s the best advice you’ve ever heard?', 'How do you like your eggs?', 'Do you have a favorite charity you wish more people knew about?', 'Got any phobias you’d like to break?', 'Have you returned anything you’ve purchased recently? Why?', 'Do you collect anything?', 'What’s your favorite breakfast cereal?', 'What is your most used emoji?', 'What was the worst haircut you ever had?', 'If you were a wrestler what would be your entrance theme song?', 'Have you ever been told you look like someone famous, who was it?', 'If you could bring back any fashion trend what would it be?', 'What did you name your first car?', 'You have your own late night talk show, who do you invite as your first guest?', 'What was your least favorite food as a child? Do you still hate it or do you love it now?', 'If you had to eat one meal everyday for the rest of your life what would it be?', 'If aliens landed on earth tomorrow and offered to take you home with them, would you go?', '60s, 70s, 80s, 90s: Which decade do you love the most?', 'What’s your favorite sandwich and why?', 'What is your favorite item you’ve bought this year?', 'Say you’re independently wealthy and don’t have to work, what would you do with your time?', 'If you had to delete all but 3 apps from your smartphone, which ones would you keep?', 'What would your dream house be like?', 'You’re going sail around the world, what’s the name of your boat?', 'Which band / artist – dead or alive would play at your funeral?', 'As a child, what did you want to be when you grew up?', 'What’s your favorite tradition or holiday?', 'What is your favorite breakfast food?', 'What is your favorite time of the day and why?', 'Coffee or tea?', 'Teleportation or flying?', 'What is your favorite TV show?', 'What book read recently you would recommend and why?', 'If you had a time machine, would go back in time or into the future?', 'Do you think you could live without your smartphone (or other technology item) for 24 hours?', 'What is your favorite dessert?', 'What was your favorite game to play as a child?', 'Are you a traveler or a homebody?', 'What’s your favorite place of all the places you’ve travelled?', 'Have you ever completed anything on your “bucket list”?', 'What did you have for breakfast this morning?', 'What was the country you last visited?', 'What is one thing we don’t know about you?', 'What is your favorite meal to cook and why?', 'Are you a morning person or a night person?', 'What is your favorite musical instrument and why?', 'What languages do you know how to speak?', 'What’s the weirdest food you’ve ever eaten?', 'What is your cellphone wallpaper?', 'You can have an unlimited supply of one thing for the rest of your life, what is it? ', 'What season would you be?', 'Are you a good dancer?', 'If you could live anywhere in the world for a year, where would it be?', 'If you could see one movie again for the first time, what would it be and why?', 'If you could rename yourself, what name would you pick?', 'If you could have someone follow you around all the time, like a personal assistant, what would you have them do?', 'If you had to teach a class on one thing, what would you teach?', 'If you could magically become fluent in any language, what would it be?', 'If you could eliminate one thing from your daily routine, what would it be and why?', 'If you could go to Mars, would you? Why or why not?', 'Would you rather live in the ocean or on the moon?', 'Would you rather lose all of your money or all of your pictures?', 'Would you rather have invisibility or flight?', 'Would you rather live where it only snows or the temperature never falls below 40 degrees?', 'Would you rather always be slightly late or super early?', 'Would you rather give up your smartphone or your computer?', 'Would you rather live without AC or live without social media?', 'Would you rather be the funniest or smartest person in the room?', 'What are your favorite songs from your teenage years that you still rock out to when nobody else is listening?', 'What’s your most embarrassing moment from your teen years?', 'What’s the worst thing you ever did as a kid — and got away with?', 'What did you get into the most trouble for with your parents as a kid?', 'What was the first concert you ever went to?', 'Do you have any crazy housemate stories?', 'What was your first record, tape or CD that you ever owned', 'What were words you couldn’t pronounce as a child, so you made up your own?', 'Have you ever gotten super lost?', 'What was your first job?', 'Who was the worst school teacher you ever had?', 'What’s the best prank you’ve ever played on someone?', 'What’s your strangest talent?', 'What show on Netflix did you binge watch embarrassingly fast?', 'What is your favorite smell and why?', 'What food could you not live without?', 'What commercial jingle gets stuck in your head all the time?', 'What sport did you try as a child and fail at?', 'What do you never leave the house without (can’t be your phone, keys or wallet)?', 'What’s a nickname people actually call you?', 'If you could only eat at one restaurant forever, what restaurant would it be?', 'If you could only wear one type of shoes for the rest of your life, what type of shoes would it be?', 'If all your clothes had to be one color forever, what color would you pick?', 'If you could eliminate one food so that no one would eat it ever again, what would you pick to destroy?', 'If you could turn the ocean into a liquid other than water, which one would you pick?', 'If you could only listen to one song for the rest of your life, which song would you pick?', 'If you had to endorse a brand, which brand would it be?', 'How much does a polar bear weigh?', 'Blow our minds with a random fact', 'In a zombie apocalypse, what would your survival strategy be?', 'Have you ever been skinnydipping?', 'What is your best quality?', 'You find a high-denomination note in a restaurant floor. Do you hand it in, or pocket it?', 'Have you ever had a recurring nightmare?', 'What is the kindest thing a stranger has done for you?', 'What is your first memory involving a computer?', 'What is the weirdest thing you have eaten?', 'You can go back in time. Which year do you choose?', 'What is one piece of advice you would give to a child?', 'Have you ever needed stitches?', 'What is your favorite website?', 'What was your least favorite subject at school?', 'Who is your dream dinner guest?', 'Would you rather publish a book or release an album?', 'Have you ever met someone famous?', 'Have you ever had a supernatural experience?', 'Who is your favorite superhero?', 'What job would you be doing if computers had not been invented?', 'What is the best holiday you have ever been on?', 'In the book of your life, what is the best chapter?', 'Can you play a musical instrument?', 'It is late, you are hungry., What shameful snack will you prepare?', 'Make the noise of your favorite animal', 'If you could only eat one type of food for the rest of your life, what would it be?', 'Day off. What do you do to relax?', 'Have you ever been in a newspaper?', 'If you could ban any word or phrase, what would it be?', 'What was your favorite TV show when growing up?', 'Which famous sporting moment would you like to have been part of?', 'Do you have superstitions?', 'Have you ever walked out of a cinema before a movie has finished?', 'What was the one thing you always wanted as a kid, but never got?', 'What was the first movie you saw at the cinema?', 'You are put in charge of the country. What is the first thing you do?', 'What do you like most about coming to work?', 'What is your favorite animal?', 'What’s the best thing that’s happened to you this week?', 'What was the worst present you’ve received?', 'Which skill would you love to learn?', 'Would you rather be clever or beautiful?', 'Would you rather be really hairy or bald?', 'Would you like to be taller or shorter?', 'What irritates you the most?', 'Have you gone out with mismatched socks or shoes on?', 'What flavor ice cream you like the most?', 'What is your favorite drink?', 'Have you ever locked yourself out of the house?', 'Have you gone in to a room and forgotten why?', 'Given the choice of anyone in the world, whom would you want as a dinner guest?', 'Would you like to be famous? In what way?', 'Before making a telephone call, do you ever rehearse what you are going to say? Why?', 'What would constitute a “perfect” day for you?', 'When did you last sing to yourself? To someone else?', 'If you were able to live to the age of 90 and retain either the mind or body of a 30-year-old for the last 60 years of your life, which would you want?', 'Name three things you and a team mate appear to have in common.', 'For what in your life do you feel most grateful?', 'If you could wake up tomorrow having gained any one quality or ability, what would it be?', 'If a crystal ball could tell you the truth about yourself, your life, the future or anything else, what would you want to know?', 'Is there something that you’ve dreamed of doing for a long time? Why haven’t you done it?', 'What is the greatest accomplishment of your life?', 'What do you value most in a friendship?', 'What is your most treasured memory?', 'What does friendship mean to you?', 'Alternate sharing something you consider a positive characteristic of each person in your team.', 'Make a true “we” statements. For instance, “We are both in this room feeling ... “', 'Share an embarrassing moment in your life.', 'What, if anything, is too serious to be joked about?', 'Your house, containing everything you own, catches fire. After saving your loved ones and pets, you have time to safely make a final dash to save any one item. What would it be? Why?', 'Texting or talking?', 'Favorite day of the week?', 'Nickname your parents used to call you?', 'Last song you listened to?', 'Would you rather be able to speak every language in the world or be able to talk to animals?', 'Favorite holiday?', 'How long does it take you to get ready?', 'Scale of 1-10, how good of a driver are you?', 'At what age do you want to retire?', 'Invisibility or super strength?', 'Is it wrong for a vegetarian to eat animal shaped crackers?', 'Scale of 1-10, how good are you at keeping secrets?', 'Dawn or dusk?', 'Do you snore?', 'Place you most want to travel?', 'Favorite junk food?', 'Favorite season?', 'Last Halloween or Carnival costume?', 'Cake or pie?', 'Do you ever post inspirational quotes on social media?', 'Favorite ice cream flavor?', 'Say a word in Spanish.', 'Favorite number?', 'Have you ever worn socks with sandals?', 'Try to tickle yourself. Can you?', 'What’s the best age?', 'If Voldemort offered you a hug, would you accept?', 'Would you rather cuddle with a baby panda or a baby penguin?', 'Would you want to live forever?', 'What will you have for dinner tonight?', 'How many pull-ups can you do in a row?', 'Favorite type of tea?', 'Say something in an Asian language.', 'What is the fastest speed you have ever driven in a car?', 'Star Trek or Star Wars?', 'How many times did you sneeze in the last 7 days?', 'Big dogs or small dogs?', 'How many hours of sleep do you need?', 'Say "Gday mate" in an Australian accent.', 'What is your favorite carb: bread, pasta, rice, or potatoes?', 'How many kids would you like to have?', 'Are rats cute?', 'What is your favorite car?', 'Do you know how to salsa dance?', 'How many cups of coffee do you drink per day?', 'What is your ideal outside temperature?', 'Favorite type of muffin?', 'Giving presents or getting presents?', 'From 1-10, how hot do you like your shower water?', 'If Kim Kardashian and Donald Trump were both drowning and you could only save one, who would it be?', 'Do you like the smell of gasoline?', 'Can you touch your toes without bending your knees?', 'Have you ever tasted soap?', 'Do you currently own any stuffed animals?', 'Tapas or pasta?', 'Ask permission or ask forgiveness?', 'How many redheads are you friends with?', 'Name a word in English that starts with the letter Q', 'Climb a mountain or jump from a plane?', 'If you were really hungry, would you eat a bug?', 'How long can you hold your breath for?', 'Have you ever seen a kangaroo in person?', 'When people stand up for a standing ovation, are you usually one of the earlier people to stand up or one of the later?', 'What type of milk do you put in your cereal?', 'Did you ever believe in Santa Claus?', 'Have you ever been to Africa?', 'What is the most number of hours you have watched TV in a single day?', 'Do you Instagram your food?', 'What sound does a seal make?', 'Would you rather lose all your hair or gain 50% more hair?', 'If there is a spider in your house, do you kill it or set it free?', 'What is something you could eat for a week straight?', 'Would you rather wake up to an air horn blowing in your ear every day, or wake up and have to run 4 miles every day?', 'Dark Chocolate or Milk Chocolate?', 'Would you go to a cinema alone?', 'What is a country you would be okay never visiting in your life?', 'Would you rather eat some smoky gnocchi or some delish fish?', 'If you were given the opportunity to fly into space given current technology, would you take it?', 'When was the last time you stayed up past 4 in the morning?', 'When you fly on a plane, do you wear a neck pillow?', 'Do you like Disneyland?', 'How would you rate your karaoke skills on a scale of 1 to Mariah Carey?', 'Are tomatoes a fruit or a vegetable?', 'Have you ever stolen anything?', 'Do you think anyone considers you a hipster?', 'What’s the sound you would make if you were freezing cold?', 'What’s your favorite martial art?', 'Los Angeles or New York?', 'Super Mario Brothers or Zelda?', 'What temperature do you like your thermostat at?', 'Do you own a bicycle?', 'Do you find moustaches to be handsome?', 'Which animal adds more joy to the world, squirrels or llamas?', 'On a scale of 1-10 how much do you enjoy garlic?', 'Who inspires you?', 'If there was a hair in your soup at a restaurant, would you return it?', 'What is the most boring thing ever?', 'What bed size do you prefer?', 'What’s your middle name?', 'What’s your current state of mind?', 'What’s one thing that most people don’t know about you?', 'What would other people say you’re exceptionally good at? Why?', 'Name 3 things that you and your team have in common.', 'What is one thing in your life that feels stressful right now?', 'What’s one embarrassing thing that’s happened to you since working here?', 'When was the last time you asked a teammate for help? What happened?', 'What’s one thing you’ve learned from your team? What does it mean to you?', 'How might we learn from each other more often?', 'What professional skills would you like to develop next?', 'Who in the company would you like to learn from? What would you like to learn?', 'Where do you imagine yourself 5 years from now?', 'Think about yourself one year ago. What’s one thing that’s changed since then?', 'What’s working particularly well on your team right now?', 'What are some things we could do to celebrate success more often?', 'How would teammates describe your communication style?', 'How do you feel about small talk?', 'What’s one time where a team took a risk, and it paid off?', 'When in your career have you felt the most purpose in your work?', 'What’s your favorite charitable or non-profit organization? Why?', 'What does leadership mean to you?', 'Who inspired you this week? Why?', 'How do you recognize when you’re stressed?', 'What’s one thing you you’ve learned from reading lately?', 'What book would benefit your team if you read it together?', 'How would you describe how work felt this month, using only phrases from a weather forecast?', 'How do you tend to see the world? Always sunny? Always stormy? Something else?', 'Who has helped make your job easier recently? What did they do?', 'What fun topic could you give a short presentation about with no preparation?', 'How do you feel about public speaking? Love it? Hate it? Both?', 'Where, outside of work, do you get your best ideas?', 'Have you ever had a helpful deadline? What made it helpful?', 'Do you have any routines you use to improve your energy and focus?', 'What’s one thing you’ve learned in the past month?', 'Who is a good listener on your team? What makes them good at it?', 'When does it feel easy for you to be a good listener?', 'What would you rather hear first, good news or bad news?', 'How do you get feedback on your own work? What questions do you ask?', 'What’s a piece of useful feedback you’ve received from a teammate?', 'Think of a time when feedback felt like a gift. Why did it feel that way?', 'When you give feedback, how do you make sure it’s received as helpful?', 'Who was your favorite teacher? What made them special?', 'What’s a part of your job that you particularly enjoy?', 'Who has made a positive difference in your life recently?', 'What’s the funniest thing that’s ever happened to you while working here?', 'What did you get into the most trouble for as a kid?', 'What’s a healthy fear that drives you and makes you more effective?', 'When looking back at your youth, what was your silliest fear?', 'What’s your meeting load like recently? Too many? Too few? Just right?', 'What meeting do you benefit the most from attending?', 'If you had an extra day to focus uninterrupted on any project, what would you work on?', 'How should teammates know when it’s a bad time to interrupt you?', 'Who has been an influential mentor to you?', 'What’s a mobile app that you love, but that few people know about?', 'Do you find it easier to say yes to projects, or no to projects? Why’s that?', 'When you need to say “no” to a project, what are some techniques you use?', 'What’s one thing you don’t like doing, but manage to do anyway?', 'When you find that part of a project is unpleasant, how do you manage to keep going?', 'If you could complete one work-related task with a wave of your hand, what task would you choose?', 'What’s one TV show you think your whole team should watch? Why?', 'What part of your job are you most passionate about?', 'What’s one thing you’re grateful for at work?', 'What character trait are you thankful that you possess?', 'When times are tough, who or what reminds you that life is good?', 'What’s one strange thing you used to believe as a child?', 'What’s one rule your parents or guardians enforced when you were a kid?', 'How do you mentally step away from work at the end of the day?', 'When do you find it hardest to stop thinking about work?', 'Do you tend to think out loud, or wait till you know just what to say?', 'How would you rather start a meeting: Get to business, or get to know each other?', 'What does “communication style” mean to you?', 'Do you tend to stay calm and cool, or get easily excited?', 'How long does it take you to warm up to a new group of people?', 'What’s one internet meme or cultural phenomenon that baffles you?', 'What would be helpful for your teammates to know about the way you communicate?', 'Has there been a day when your daily routine was thrown off recently? How did you adapt?', 'Is there any part of your daily routine that you’d like to change? Why?', 'What have you read or watched recently and enjoyed?', 'For those that might not know, what’s your role here?', 'What were you doing before working here?', 'What do you like to do for fun?', 'What are some hobbies or activities you do outside of work?', 'What’s your morning routine like?', 'If you could travel anywhere in the world, where would you go? Why?', 'Who are your heroes in real life?', 'What was your favorite cartoon as a kid?', 'Which comedian, actor, or author really makes you laugh?', 'What is your favorite holiday? Why?', 'What was the best thing that happened to you in the last week?', 'If you could invent a new flavor of ice cream, what would it be?', 'What’s the last dream that you remember?', 'What’s one strange thing that’s happened to you since working here?', 'What’s the worst haircut you’ve ever had?', 'How did you find your way to your current career? What was your journey?', 'If you had to sum up your entire career in 12 words or less, what would you say?', 'Do you like to get up early, or stay up late? Has this ever been challenging?', 'What’s one fun thing you’ve learned outside of work recently?', 'When you were younger, what did you want to be when you grew up?', 'What’s one skill that you’ve improved in the last year? How did you do it?', 'If you took a 4-week paid sabbatical from work, what would you do with the time?', 'Who do you admire? What do you admire about them?', 'If you had to move to a different country, where would you go? What would you miss?', 'If this team had a mascot, what would it be?', 'What conversations are you most looking forward to this week?', 'What’s your favorite meeting at work? Why?', 'If you could get a meeting with anyone in the world, who would it be? Why?', 'What’s one moment of success you experienced recently?', 'What recent team accomplishment brings you the most joy? Why?', 'How do you celebrate? What are some things you do to treat yourself?', 'What’s your email style? Brief or detailed? Emotive or serious?', 'Do you consider yourself an introvert, an extrovert or both? Why?', 'What’s your superpower? How do you use it at work?', 'Imagine an ideal day at work. How do you spend it? What happens?', 'What’s one thrilling thing you’ve done?', 'What’s the most beautiful place you’ve ever been?', 'What’s your favorite way to relax or unplug?', 'What excited you most when joining this team?', 'What is the best team experience of your career? What made it so great?', 'Back at school, were you on any teams or in any clubs? What was your favorite? Why?', 'What was the last thing someone thanked you for?', 'What is your favorite walk, hike, or bike ride?', 'What song or artist have you been listening to lately?', 'What books are on the top of your “want to read” list?', 'What’s your favorite children’s book? Why?', 'What’s your favorite season? Why?', 'What seemingly tiny thing are you especially grateful for?', 'If you could make a guest appearance in a TV show, which show would it be?', 'What TV or movie character would be amazing on your team? Why?', 'What talk or presentation have you enjoyed watching recently?', 'What languages do you speak? How did you learn to speak them?', 'When was the last time you were so into your work that time flew by?', 'Outside of work, what activity makes you lose track of time?', 'When you set a morning alarm, do you snooze for a while, or wake up right away?', 'When during the day do you have the most energy and focus?', 'What’s the perfect notebook for you? (Lines or grids? Big or small? Etc.)', 'What’s a favorite item that you’ve had on your desk at some point?', 'If you had an extra day a week to volunteer your time, what would you do?', 'What business jargon would you like to banish from the workplace?', 'What was the last podcast or audiobook you listened to?', 'If you could magically improve at one skill, what would it be?', 'What categories of trivia are you the best at?', 'What should be M&M’s next new color or flavor?', 'What’s one thing you enjoy about your home or neighborhood?', 'What’s a simple pleasure you enjoyed this week?', 'What’s your favorite story to tell about company history?', 'What work decision or policy would you most like to know the backstory for?', 'If you could add any snack to the kitchen at work, what would it be?', 'What helps you wake up: coffee, tea, or something else?', 'What food do you hate the most?', 'What was the last scary movie that you’ve seen?', 'What musical instruments have you played, either now or in the past?', 'If you could have any car for free, what would you drive? (Assuming free parking, gas, etc.)', 'In your kitchen, what’s your favorite tool or gadget?', 'What’s your favorite sport to play or watch?', 'Where’s your favorite place for lunch on a workday?', 'What’s your favorite Olympic event to watch? What do you like about it?', 'What fictional character would you most like to have as a mentor?', 'What’s the furthest away from home you’ve ever been?', 'Where would you like to go on your next vacation?', 'When you read books for fun, do you feel the need to finish them completely? Why?', 'What’s your least favorite chore?', 'What small activities help you re-energize?', 'You’ve been tasked with creating a real superhero. What would their superpower be?', 'What was your favorite television series as a teenager?', 'What movie will you never grow tired of watching?', 'What’s a movie that should have had a sequel, or a sequel that shouldn’t have been made?', 'What are two things you’re passionate about outside of work?', 'What’s one great thing that happened to you this week?', 'How do you approach traveling on vacation? Do you make an itinerary or just explore?', 'Have you ever dealt with a series of unfortunate events on a vacation? How did you overcome it?', 'If you could spend a season working abroad, where would you go?', 'Kids today will never understand the struggle of what?', 'When do you find it easiest to stop thinking about work?', 'How do you power down at the end of the week to make sure you enjoy your weekend?', 'How do you like to work: deep focused time, or quickly switching contexts?', 'What’s the perfect temperature setting for the office thermostat?', 'What’s your favorite figure of speech?', 'Which do you prefer: hot weather or cold weather? Why is that?', 'When looking for something at the store, do you ask someone or try to find it yourself?', 'What’s your favorite food these days? How often do you get to enjoy it?', 'How does your daily routine change from weekday to weekend?', 'What is the best piece of advice you’ve received? Why was it helpful?', 'What’s one thing that could work better on your team?', 'What’s one pet peeve you have about the way other people communicate with you?', 'What are a few ways in which you express your gratitude?', 'Think about the last mistake you made at work. What happened? What did you learn?', 'What would you do at work if you knew you couldn’t fail?', 'Think of the biggest professional risk you’ve taken. What helped you take that risk?', 'What would make you feel safer when taking calculated risks at work?', 'What things make it harder or easier for a group to feel like a team?', 'How could we make this team feel like more like a team?', 'What kind of leader do you want to be? What’s your personal leadership style?', 'When you’re feeling stressed, how do you deal with it?', 'Describe a real-life situation where you stood up for someone or something.', 'When people have different opinions on the team, what happens?', 'What was the last team decision that felt like it took too long? Why did it take so long?', 'How does your outlook on the world affect your approach to work?', 'Think of the last meaningful “thank you” that you received. What was it?', 'How do you like be thanked at work? In public or private?', 'What distractions prevent you from doing your best work?', 'What’s one deadline that you almost missed?', 'When do deadlines create more problems than they solve?', 'Are there any productivity habits that you wish you could get into?', 'When is it difficult for you to listen to others?', 'If you could give your younger self a piece of advice, what would you say?', 'Think of a time when feedback was NOT helpful to you. What went wrong?', 'What’s a fear that sometimes gets in your way?', 'If you had to skip one recurring meeting, which meeting would you skip? Why?', 'What could you change to give yourself more uninterrupted time to focus?', 'How has mentorship affected you throughout your career?', 'Is there any topic lately that you would like to be mentored on?', 'What’s one project that you could stop doing to give yourself more focus?', 'What’s the hardest thing you’ve ever done? How did you make it through?', 'How do you overcome frustration at work?', 'Imagine you’ve just had a difficult interaction with a colleague. How do you regain focus?', 'What is a passion of yours you’ve yet to act on?', 'What 3 words would you use to describe yourself to a stranger?', 'Which of your character traits do you think adds the most value to the world?', 'What’s something about you that would surprise most people who know you?', 'What’s a trip that changed you? How were you changed?', 'Looking back, what do you admire most about your childhood self?', 'When there’s disagreement, do you tend to lean into it, or away from it?', 'When was the last time you had a small misunderstanding? What happened?', 'What’s one misunderstanding that’s happened on your team recently? How was it resolved?', 'Imagine that communication totally breaks down between you and someone else. How is it likely to happen?', 'How would you describe your communication style in 3 words?', 'How does your particular communication style affect the people around you?', 'Are there times when you find it difficult to ask for help with your own work?', 'What’s a time when you should have asked for help sooner but waited? Is there anything that might have made it easier for you to ask?', 'Where does career growth rank in your list of priorities?', 'What gives you peace of mind?', 'Has social media made the world a better place?', "What's the best meal you've ever had?", 'What impact has family had on your idea of success?', 'How has your taste in music changed over time?', "What's more important: the individual or the collective good?", 'Are you artistic?', 'Share a positive characteristic of each person in this group', 'Are there any funny stories your family tells about you that come to mind?', "What's one new and interesting thing you've been thinking about lately?", "What's one thing that brings you energy and joy?", 'What kind of day have you had so far today?', 'Name a weather status that matches your mood', 'If you could invite someone to sit next to you today, who would it be?', 'Describe where your head and your heart are right now', 'What important skill do you believe everyone should have?', 'Which technological innovation made the most impact on your life?', 'How would you spend one million dollars? And five million?', 'Imagine you had a tattoo. What would it be and where would you have it?', 'Which dish would you like to learn to cook next?', 'What Disney character are you?', 'What event in the past or future would you like to witness in person?', 'What kind of party would you throw if you had unlimited budget?', 'Who would you like to trade places with for a month?', 'What are the best and worst things about being an adult?', 'What new name would you choose for yourself?', 'What’s the most embarrassing fashion trend you used to rock?', 'What would the title of your autobiography be?', 'What does your favorite shirt look like?', 'What fictional family would you be a member of?', 'What sport would you compete in if you were in the Olympics?', 'Do you have a favorite plant?', 'What fictional world or place would you like to visit?', 'Popcorn or M&Ms?', 'Would you rather be an Olympic gold medallist or an astronaut?', 'What are your favorite pizza topings?', 'Do you have any Christmas traditions?', 'Do you have any siblings?', 'Have you ever broken a bone?', 'Did you make your bed this morning?', 'Where did you grow up?', 'Do you know any good jokes? (Dad jokes are allowed)', 'What is the farthest distance you have driven?', 'How many pairs of shoes do you own?', 'How many books did you read last year?', 'Do you have any pets?', 'Where were you born?', 'Wine or Beer?', 'What would you add to your coffee: Baileys, Amaretto, Whisky or Milk?', 'What do you enjoy most about the holidays?', 'What is the best concert you have ever been to?', 'If you created a photo calendar, what photo would you put on November?', 'What board game are you unbeatable at?', 'Do you have any short term goals?', 'Favorite Christmas movie?', 'What is your favourite fast food restaurant?', 'Which is typically better, the book or the movie?', 'What is your favourite app?', 'Who is your least favourite actor?', 'When and how did you learn the truth about Santa?', 'Favourite snack to eat while watching a movie?', 'Is a hotdog a sandwich?', 'What food can you not stand?', 'Dancing in the rain or saying cozy inside?', 'Luxury beach vacations or backpacking?', 'What was the best team building you ever participated?', "What is something you do that you don't like to do?", 'Imagine you were given a kitten, what would you name her/him?', 'If you could add anything to your desk, what would it be?', 'If you could collect anything, what would it be?', 'What is your favourite scent?', 'Do you enjoy rollercoasters?', 'Do you have a favourite childhood videogame?', 'What is your cocktail of choice?', 'What is something that frustrates you at work?', 'Do you have a guilty pleasure?', 'Are you a clean or a messy person?', 'Conflicts: avoid or confront?', 'What is your favourite photograph?', 'Do you have any tattoos?', 'Best way to get over a breakup?', 'Use one word to describe your childhood bedroom', 'Do you have any hidden talents?', 'Is there any habit you would like to change?', "Tell us one of the most important lessons you've learned in life", "Is there something about your team members that you've always wanted to ask but never did?", 'Favourite memory of your team?', 'What is your most valuable travel advice?', 'Of all your possessions, what would be the hardest to give up?'] return icebreakers[randrange(0, len(icebreakers) - 1, 1)]
35f1a4243a2a56315eee8070401ee4f8dc38bf9c
JordanJLopez/cs373-tkinter
/hello_world_bigger.py
888
4.3125
4
#!/usr/bin/python3 from tkinter import * # Create the main tkinter window window = Tk() ### NEW ### # Set window size with X px by Y px window.geometry("500x500") ### NEW ### # Create a var that will contain the display text text = StringVar() # Create a Message object within our Window window_message = Message(window, textvariable = text) # Set the display text text.set("HELLO WORLD") # Compile the message with the display text ### NEW ### ## Notable .config Attributes: # anchor: Orientation of text # bg: Background color # font: Font of text # width: Width of text frame # padx: Padding on left and right # pady: Padding on top and bottom # and more! window_message.config(width=500, pady=250, font=("Consolas", 60), bg = 'light blue') ### NEW ### window_message.pack() # Start the window loop window.mainloop() exit()
d0ad9ee4882356daa2c6a413dc6b827cd7671a6a
Ricky-001/encryptor_decryptor
/algos/affine.py
15,763
3.703125
4
#!/usr/bin/python3 import argparse from utilities.tools import clear from utilities.colors import color keys = [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25] def encrypt(plain,key,step): if key not in keys: raise ValueError() plainASCII = [ord(char) for char in plain] cipherASCII = [] for i in range(len(plain)): if plain[i].isalpha(): if plainASCII[i] in range(65,91): cipherASCII.append((((plainASCII[i]-65)*key)+step)%26+65) else: cipherASCII.append((((plainASCII[i]-97)*key)+step)%26+97) else: cipherASCII.append(plainASCII[i]) cipher = ''.join(map(chr,cipherASCII)) return cipher def inverse(key): return [x for x in range(27) if (x*key)%26==1][0] def decrypt(cipher,key=None,step=None): cipherASCII = [ord(char) for char in cipher] plainASCII = [] # bruteforce decryption if not key: for key in keys: print('\n{}[!] {}Key = {}{}'.format(color.BLUE,color.ORANGE,key,color.END)) print('===============\n') for step in range(26): plainASCII = [] for i in range(len(cipher)): if cipher[i].isalpha(): if cipherASCII[i] in range(65,91): plainASCII.append(((cipherASCII[i]-65-step)*inverse(key))%26+65) else: plainASCII.append(((cipherASCII[i]-97-step)*inverse(key))%26+97) else: plainASCII.append(cipherASCII[i]) plain = ''.join(map(chr,plainASCII)) print('{}[+]{} {}Step={}{}\t:\t{}{}{}'.format(color.GREEN,color.END,color.YELLOW,step,color.END,color.RED,plain,color.END)) return None # normal decryption if key in keys: for i in range(len(cipher)): if cipher[i].isalpha(): if cipherASCII[i] in range(65,91): plainASCII.append(((cipherASCII[i]-65-step)*inverse(key))%26+65) else: plainASCII.append(((cipherASCII[i]-97-step)*inverse(key))%26+97) else: plainASCII.append(cipherASCII[i]) else: #print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}'.format(color.RED,color.END,color.YELLOW,keys,color.END)) raise ValueError() plain = ''.join(map(chr,plainASCII)) return plain def parsefile(filename): message = '' try: with open(filename) as f: for line in f: message+=line except FileNotFoundError: print('{}[-] File not found{}\n{}[!] Please make sure the file with the filename exists in the current working directory{}'.format(color.RED,color.END,color.YELLOW,color.END)) quit() return message def run(): key=None try: clear() choice = input('{}[?]{} Encrypt or Decrypt? [e/d] : '.format(color.BLUE,color.END)) if choice == 'e' or choice == 'E': # whether to load a file for the plaintext or type it from the console filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower() if filechoice != 'y': pt = input('{}[?]{} Enter the Plaintext message to encrypt: '.format(color.BLUE,color.END)) else: filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END)) pt = parsefile(filename) try: key = int(input('{}[?]{} Enter the Key to encrypt the message: '.format(color.BLUE,color.END))) step = int(input('{}[?]{} Enter the shift step of the message: '.format(color.BLUE,color.END))) ciphertext = encrypt(pt, key, step) print('{}[+] The Ciphertext with Key = {}{}{} and a Shift of {}{}{} is: {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,ciphertext,color.END)) except ValueError: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) elif choice == 'd' or choice == 'D': # whether to load a file for the plaintext or type it from the console filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower() if filechoice != 'y': ct = input('{}[?]{} Enter the Ciphertext message to decrypt: '.format(color.BLUE,color.END)) else: filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END)) ct = parsefile(filename) try: key = int(input('{}[?]{} Enter the Key used to encrypt the message (leave blank to attempt Bruteforce): '.format(color.BLUE,color.END))) if key: step = int(input('{}[?]{} Enter the shift step of the message: '.format(color.BLUE,color.END))) plaintext = decrypt(ct, key, step) print('{}[+] The Plaintext with Key = {}{}{} and a Shift of {}{}{} is : {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,plaintext,color.END)) except ValueError: if not key: decrypt(ct,None) print('\n{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END)) else: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) else: print('{}[-] Please provide a valid coice of action{}'.format(color.RED,color.END)) quit() except KeyboardInterrupt: print('\n{}[!] Exiting...{}'.format(color.RED,color.END)) def main(): key=None try: clear() # script description parser = argparse.ArgumentParser(description='Multiplicative (Affine) Cipher Encryption & Decryption') # encryption group option (single option --encrypt) enc_group = parser.add_argument_group('Encryption Options') enc_group.add_argument('-e','--encrypt', help='Encrypt a given Plaintext', default=False, action='store_true') # decryption group options (--decrypt and --brute) dec_group = parser.add_argument_group('Decryption Options') dec_group.add_argument('-d','--decrypt', help='Decrypt a given Ciphertext', default=False, action='store_true') dec_group.add_argument('-B','--brute', help='Bruteforce decryption (to be used only with -d, --decrypt)', default=False, action='store_true') # file option - whether to load from a file parser.add_argument('-f','--file', help='Load the Plaintext/ Ciphertext from a file', default=False, action='store_true') # message (either plain or cipher) - handled later on based on options parser.add_argument('TEXT', help='Plaintext or Ciphertext (based on mode)') parser.add_argument('-k','--key', default=None, type=int, help='Key used for encryption/ decryption') parser.add_argument('-s','--step', default=0, type=int, help='Shift step (default=0)') try: args = parser.parse_args() except: choice = input('{}[?]{} Encrypt or Decrypt? [e/d] : '.format(color.BLUE,color.END)) if choice == 'e' or choice == 'E': # whether to load a file for the plaintext or type it from the console filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower() if filechoice != 'y': pt = input('{}[?]{} Enter the Plaintext message to encrypt: '.format(color.BLUE,color.END)) else: filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END)) pt = parsefile(filename) try: key = int(input('{}[?]{} Enter the Key to encrypt the message: '.format(color.BLUE,color.END))) step = int(input('{}[?]{} Enter the shift step of the message: '.format(color.BLUE,color.END))) ciphertext = encrypt(pt, key, step) print('{}[+] The Ciphertext with Key = {}{}{} and a Shift of {}{}{} is: {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,ciphertext,color.END)) except ValueError: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) elif choice == 'd' or choice == 'D': # whether to load a file for the plaintext or type it from the console filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower() if filechoice != 'y': ct = input('{}[?]{} Enter the Ciphertext message to decrypt: '.format(color.BLUE,color.END)) else: filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END)) ct = parsefile(filename) try: key = int(input('{}[?]{} Enter the Key used to encrypt the message (leave blank to attempt Bruteforce): '.format(color.BLUE,color.END))) if key: step = int(input('{}[?]{} Enter the shift step of the message: '.format(color.BLUE,color.END))) plaintext = decrypt(ct, key, step) print('{}[+] The Plaintext with Key = {}{}{} and a Shift of {}{}{} is : {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,plaintext,color.END)) except ValueError: if not key: decrypt(ct,None) print('\n{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END)) else: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) else: print('{}[-] Please provide a valid coice of action{}'.format(color.RED,color.END)) quit() # parsing command line argumets (provided the necvessary ones are given) if args.encrypt: # if encrypt flag is on if args.decrypt: # decrypt flag should be off print('{}[-] Please select only one option among Encrypt or Decrypt at a time{}'.format(color.RED,color.END)) quit() if args.brute: # bruteforce flag should be off print('{}[-] Bruteforce can only be used during Decryption{}'.format(color.RED,color.END)) quit() else: # good to go - call enc() function and display result if args.file: pt = parsefile(args.TEXT) else: pt = args.TEXT try: key = int(args.key) if args.step: step = int(args.step) else: step=0 ciphertext = encrypt(pt, key, step) print('{}[+] The Ciphertext with Key = {}{}{} and a Shift of {}{}{} is: {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,ciphertext,color.END)) except ValueError: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) elif args.decrypt: # if decrypt flag is on if args.brute: # if bruteforce option is also on if args.file: ct = parsefile(args.TEXT) decrypt(ct,None) else: decrypt(args.TEXT,None) # call decrypt function directly - steps not required print('\n{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END)) else: # no bruteforce - steps known if args.file: ct = parsefile(args.TEXT) else: ct = args.TEXT try: key = int(args.key) if args.step: step = args.step else: step=0 plaintext = decrypt(ct, key, step) print('{}[+] The Plaintext with Key = {}{}{} and a Shift of {}{}{} is : {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,plaintext,color.END)) except ValueError: if not key: decrypt(pt,None) print('\n{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END)) else: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) except TypeError: try: key = int(input('{}[?]{} Enter the Key used to encrypt the message (leave blank to attempt Bruteforce): '.format(color.BLUE,color.END))) if key: step = int(input('{}[?]{} Enter the shift step of the message: '.format(color.BLUE,color.END))) else: step=None plaintext = decrypt(ct, key, step) print('{}[+] The Plaintext with Key = {}{}{} and a Shift of {}{}{} is : {}{}{}'.format(color.GREEN,color.YELLOW,key,color.END,color.ORANGE,step,color.END,color.RED,plaintext,color.END)) except ValueError: if not key: decrypt(ct,None) print('\n{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END)) else: print('{}[-] Please enter a valid key{} (one of the following):-\n{}{}{}\n{}[-] Please ensure to provide a numeric value for steps (0 for no shift){}'.format(color.RED,color.END,color.YELLOW,keys,color.END,color.RED,color.END)) # if no arguments are provided except for positional (TEXT) else: print('{}[-] At least one of Encryption or Decryption action is required{}'.format(color.RED,color.END)) except KeyboardInterrupt: print('\n{}[!] Exiting...{}'.format(color.RED,color.END)) quit() if __name__ =='__main__': main()
4df8eadf0fe84ff3b194ac562f24a94b778a2588
Zioq/Algorithms-and-Data-Structures-With-Python
/7.Classes and objects/lecture_3.py
2,395
4.46875
4
# Special methods and what they are # Diffrence between __str__ & __repr__ """ str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. if __repr__ is defined, and __str__ is not, the object will behave as though __str__=__repr__. This means, in simple terms: almost every object you implement should have a functional __repr__ that’s usable for understanding the object. Implementing __str__ is optional """ class Student: def __init__(self, first, last, courses=None ): self.first_name = first self.last_name = last if courses == None: self.courses = [] else: self.courses = courses def add_course(self, new_course): if new_course not in self.courses: self.courses.append(new_course) else: print(f"{self.first_name} is already enrolled in the {new_course} course") def remove_course(self, remove_course): if remove_course in self.courses: self.courses.remove(remove_course) else: print(f"{remove_course} not found") def __len__(self): return len(self.courses) def __repr__(self): return f"Sturdent('{self.first_name}', '{self.last_name}', '{self.courses}')" def __str__(self): return f"First name: {self.first_name.capitalize()}\nLast name: {self.last_name.capitalize()}\nCourses: {', '.join(map(str.capitalize, self.courses))}" courses_1 = ['python', 'go', 'javascript'] courses_2 = ['java', 'go', 'c'] # Create new object of class robert = Student("Robert", "Han") john = Student("John", "Smith",courses_2) print(robert.first_name, robert.last_name, robert.courses) print(john.first_name, john.last_name, john.courses) # Add new course using a method john.add_course("java") robert.add_course("PHP") print(robert.first_name, robert.last_name, robert.courses) # Remove course using a method john.remove_course("c") john.remove_course("c") john.remove_course("python") print(john.first_name, john.last_name, john.courses) # use __str__ method print(robert) print(john) # use __dict__ method print(robert.__dict__) # use repre method print(repr(robert)) print(repr(john)) # use len functionality print(len(robert)) # return how many courses robert enrolled.
835fff2341216766489b87ac7682ef49a47fb713
Zioq/Algorithms-and-Data-Structures-With-Python
/1.Strings,variables/lecture_2.py
702
4.125
4
# concatenation, indexing, slicing, python console # concatenation: Add strings each other message = "The price of the stock is:" price = "$1110" print(id(message)) #print(message + " " +price) message = message + " " +price print(id(message)) # Indexing name = "interstella" print(name[0]) #print i # Slicing # [0:5] first num is start point, second num is stop point +1, so it means 0~4 characters print(name[0:5]) # print `inter` #[A:B:C] -> A: Start point, B: Stop +1, C: Step size nums ="0123456789" print(nums[2:6]) # output: 2345 print(nums[0:6:2]) # output: 024 print(nums[::2]) # output : 02468 print(nums[::-1]) # -1 mena backward step so, it will reverse the array. output: 9876543210
f975fe681f3a7bb265f6cf378571cd833cbc49b6
Zioq/Algorithms-and-Data-Structures-With-Python
/7.Classes and objects/lecture_1.py
768
3.96875
4
# Build Student class # Make a first word of class name as capitalize letter class Student: # `self` means a instance of class itself # To allow the no course case and fix the error, assign `None` to a relevent parameter def __init__(self, first, last, courses=None ): self.first_name = first self.last_name = last if courses == None: self.courses = [] else: self.courses = courses pass courses_1 = ['python', 'go', 'javascript'] courses_2 = ['java', 'go', 'c'] # Create new object of class robert = Student("Robert", "Han") john = Student("John", "Smith",courses_2) print(robert.first_name, robert.last_name, robert.courses) print(john.first_name, john.last_name, john.courses)
9123640f03d71649f31c4a6740ba9d1d3eca5caf
Zioq/Algorithms-and-Data-Structures-With-Python
/17.Hashmap/Mini Project/project_script_generator.py
1,946
4.3125
4
# Application usage ''' - In application you will have to load data from persistent memory to working memory as objects. - Once loaded, you can work with data in these objects and perform operations as necessary Exmaple) 1. In Database or other data source 2. Load data 3. Save it in data structure like `Dictionary` 4. Get the data from the data structure and work with process data as necessary 5. Produce output like presentation or update data and upload to the Database etc In this project we follow those steps like this 1. Text file - email address and quotes 2. Load data 3. Populate the AlgoHashTable 4. Search for quotes from specific users 5. Present the data to the console output ''' # Eamil address and quotes key-value data generator from random import choice from string import ascii_lowercase as letters list_of_domains = ['yaexample.com','goexample.com','example.com'] quotes = [ 'Luck is what happens when preparation meets opportunity', 'All cruelty springs from weakness', 'Begin at once to live, and count each separate day as a separate life', 'Throw me to the wolves and I will return leading the pack'] def generate_name(lenght_of_name): return ''.join(choice(letters) for i in range(lenght_of_name)) def get_domain(list_of_domains): return choice(list_of_domains) def get_quotes(list_of_quotes): return choice(list_of_quotes) def generate_records(length_of_name, list_of_domains, total_records, list_of_quotes): with open("data.txt", "w") as to_write: for num in range(total_records): key = generate_name(length_of_name)+"@"+get_domain(list_of_domains) value = get_quotes(quotes) to_write.write(key + ":" + value + "\n") to_write.write("mashrur@example.com:Don't let me leave Murph\n") to_write.write("evgeny@example.com:All I do is win win win no matter what!\n") generate_records(10, list_of_domains, 100000, quotes)
be2ba4efc175bc81f37fb99d56383ad9a69604e2
Zioq/Algorithms-and-Data-Structures-With-Python
/1.Strings,variables/lecture_1.py
529
3.890625
4
# Strings print('Hello World using single quotes') print("Hello World using double quotes") ''' print("""Hello world using triple quotes, also known as multi-line strings""") ''' print("Hello world I'm using single quotes") print('Hello world "using quotes here" double quotes') print('Hello World I\'m using single quotes') print("Hello World \"using quotes here\" double quotes") # Variables my_message = "Hello World from my message" other_message = "Second Hello World from other message" print(my_message,other_message)
517611d9663ae87acdf5fed32099ec8dcf26ee76
Zioq/Algorithms-and-Data-Structures-With-Python
/20.Stacks and Queues/stack.py
2,544
4.25
4
import time class Node: def __init__(self, data = None): ''' Initialize node with data and next pointer ''' self.data = data self.next = None class Stack: def __init__(self): ''' Initialize stack with stack pointer ''' print("Stack created") # Only add stack pointer which is Head self.stack_pointer = None # Push - can only push (add) an item on top of the stack (aka head or stack pointer) def push(self,x): ''' Add x to the top of stack ''' if not isinstance(x, Node): x = Node(x) print (f"Adding {x.data} to the top of stack") # If the Stack is empty, set the stack point as x, which is just added. if self.is_empty(): self.stack_pointer = x # If the Stack has some Node else: x.next = self.stack_pointer self.stack_pointer = x # Pop - can only remove an item on top of the stack (aka head or stack pointer) def pop(self): if not self.is_empty(): print("Removing node on top of stack") curr = self.stack_pointer self.stack_pointer = self.stack_pointer.next curr.next = None return curr.data else: return "Stack is empty" def is_empty(self): '''return True if stack is empty, else return false''' return self.stack_pointer == None # peek - view value on top of the stack (aka head or stack pointer) def peek(self): '''look at the node on top of the stack''' if not self.is_empty(): return self.stack_pointer.data def __str__(self): print("Printing Stack state...") to_print = "" curr = self.stack_pointer while curr is not None: to_print += str(curr.data) + "->" curr = curr.next if to_print: print("Stack Pointer") print(" |") print(" V") return "[" + to_print[:-2] + "]" return "[]" my_stack = Stack() print("Checking if stack is empty:", my_stack.is_empty()) my_stack.push(1) time.sleep(2) my_stack.push(2) print(my_stack) time.sleep(2) my_stack.push(3) time.sleep(2) my_stack.push(4) time.sleep(2) print("Checking item on top of stack:", my_stack.peek()) time.sleep(2) my_stack.push(5) print(my_stack) time.sleep(2) print(my_stack.pop()) time.sleep(2) print(my_stack.pop()) print(my_stack) time.sleep(2) my_stack.push(4) print(my_stack) time.sleep(2)
6aff153c967e821b61c8e5a29facee8663794522
Zioq/Algorithms-and-Data-Structures-With-Python
/15.Binary Search/binarySearch_recursive.py
715
3.828125
4
# Bisection search - recursive implementation def bisection_recur(n, arr, start, stop): # Set the base case first if start > stop: return (f"{n} not found in list") else: mid = (start + stop) // 2 if n == arr[mid]: return (f"{n} found at index: {mid}") elif n > arr[mid]: start = mid + 1 return bisection_recur(n, arr, start, stop) else: stop = mid - 1 return bisection_recur(n, arr, start, stop) l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # #ind 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 n = 8 print(bisection_recur(8, l, 0, len(l)-1)) print("\n") for num in range(16): print(bisection_recur(num, l, 0, len(l)-1))
0be4e99dbd9d44d1e06064a98e038fae55dec91f
oilbeater/projecteuler
/Multiples_of_3_and_5.py
1,058
4.125
4
''' Created on 2013-10-24 @author: oilbeater Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' import timeit def sol1(): return sum((i for i in range(1000) if i % 3 == 0 or i % 5 == 0)) def sol2(): threes = sum((i * 3 for i in range(1000 / 3 + 1))) fives = sum((i * 5 for i in range(1000 / 5))) fifteens = sum((i * 15 for i in range(1000 / 15 + 1))) return threes + fives - fifteens def sol3(): threes = (1 + 1000 / 3) * 3 * (1000 / 3) / 2 fives = (1 + 1000 / 5 - 1) * 5 / 2 * (1000 / 5 - 1) fifteens = (1 + 1000 / 15) * 15 * (1000 / 15) / 2 return threes + fives - fifteens print str(sol1()) print str(sol2()) print str(sol3()) print timeit.timeit('sol1()', "from __main__ import sol1", number=100000) print timeit.timeit('sol2()', "from __main__ import sol2", number=100000) print timeit.timeit('sol3()', "from __main__ import sol3", number=100000)
8460e81be8576efe5f66b4953cc4efd243dac762
jakeseaton/romance_slavic_diachronic_change
/Conjugation Project--Jake/italian/verble_vocab.py
1,941
4.03125
4
import vocab import random """from threading import Timer import time import timer""" # Verbal? print "Welcome to Verble!" # Mode ask_for = "Italian" # fill a dictionary with the words to be practiced words = {} for x in vocab.all_vocab: words.update(x) # account for English mode if (ask_for == "English"): print "true" words = dict (zip(words.values(), words.keys())) # calculate the objective, the number of words to be learned objective = len(words) print "Enter the correct %s. There are %s vocab words to learn." % (ask_for, objective) # initialize the score score = 0 scale = 1 num_right = 0 # initialize funny business funny_business = 1 # initialize the words that have been seen seen = {} # create a timer """def end(): print "Game over" # raise SystemExit t = Timer(5, end) t.start()""" # main while(True): # if there are words if words: # get the next word word = random.choice(words.keys()) right_answer = words.get(word) print "Next: %s" % word # get input user_answer = raw_input() # insert into seen, remove from words seen[word] = right_answer del words[word] # if they got it right if user_answer == right_answer: del seen[word] num_right += 1 score += 1 * (scale ** 2) scale += 1 print "~~Correct! Score: %s. Words left: %s~~" % (score, (objective-num_right)) else: if user_answer == "non lo so": print "Ha. Clever. Here, have 10 points" score += 10 scale = 1 print "The correct answer is:" print right_answer correction = raw_input() correction = raw_input("One more time. per *%s* se dice " % word) while not(correction == right_answer): print "Keep trying!" correction = raw_input() # check if they won elif not(seen): print "You win! Final score: %s" % score raise SystemExit # cycle the missed ones through else: # score - 10? print "--------Starting over-------" score -= 25 words = seen seen = {}
5bf9aaf7ee509a9d986888c8498627a6c66e7309
jakeseaton/romance_slavic_diachronic_change
/Conjugation Project--Jake/italian/iverbs.py
3,471
3.53125
4
# write a function that takes the third form and makes it the third, fourth, and fifth. pronouns = ["io", "tu", "lei", "lui", "Lei", "noi", "voi", "loro"] imperfect_endings = ["vo", "vi","va","vamo","vate","vano"] essere = { "indicative":["sono","sai","e","e","e", "siamo", "siete","sono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["ero","eri","era","era","era", "eravamo", "eravate", "erano"] } avere = { "indicative":["ho","hai","ha","ha","ha", "abbiamo", "avete","hanno"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["e" + x for x in imperfect_endings] } stare = { "indicative":["sto","stai","sta","sta","sta", "stiamo", "state","stanno"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["a" + x for x in imperfect_endings] } fare = { "indicative":["faccio","fai","fa","fa","fa", "facciamo", "fate","fanno"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["a" + x for x in imperfect_endings] } andare = { "indicative":["vade","vai","va","va","va", "andiamo","andate","vanno"], "past participle": ("ato" for x in xrange(len(pronouns))), "imperfect" : ["a" + x for x in imperfect_endings] } uscire = { "indicative":["esco","esci","esce","esce","esce", "usciamo", "uscite","escono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["i" + x for x in imperfect_endings] } dare = { "indicative":["do","dai","da","da","da", "diamo", "date","danno"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["a" + x for x in imperfect_endings] } sapere = { "indicative":["so","sai","sa","sa","sa", "sappiamo", "sapete","sanno"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["e" + x for x in imperfect_endings] } bere = { "indicative":["bevo","bevi","beve","beve","beve", "beviamo", "bevete","bevono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["derpe" + x for x in imperfect_endings] } dire = { "indicative":["dico","dici","dice","dice","dice", "diciamo", "dite","dicono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["i" + x for x in imperfect_endings] } tenere = { "indicative":["tengo","tieni","tiene","tiene","tiene", "teniamo", "tenete","tengono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["e" + x for x in imperfect_endings] } volere = { "indicative":["voglio","vuoi","vuole","vuole","vuole", "vogliamo", "volete","vogliono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["e" + x for x in imperfect_endings] } potere = { "indicative":["posso","puoi","puo","puo","puo", "possiamo", "potete","possono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["e" + x for x in imperfect_endings] } #fix dovere = { "indicative":["devo","devi","deve","deve","deve", "dobbiamo", "dovete","devono"], "past participle": ("derp" for x in xrange(len(pronouns))), "imperfect" : ["e" + x for x in imperfect_endings] } verbs = { "be":essere, "have":avere, "be":stare, "do":fare, "go":andare, "go out":uscire, "give":dire, "know":sapere, "drink":bere, "say":dire, "keep":tenere, "desire":volere, "able to":potere, "need":dovere } def conjugate(verb, tense): return (dict(zip(pronouns, (verb.get(tense))))) """ Irregulars in past participle are on pg 151 """
daf2b57affee09d5157670e35a5a267d5f2c3cac
jemoore/tabula-recta
/tabula.py
457
3.609375
4
#!/usr/bin/env python from random import randint from random import seed from string import ascii_uppercase seed(73) for r in range(27): if r == 0: print " ", for s in ascii_uppercase: print s,# " ", print print '-' * 55 continue for c in range(27): if c == 0: print ascii_uppercase[r-1] + '|', #" ", else: print chr(randint(33,126)), #" ", print
0d624fefe156321ad52de0d0c4ae42e9cf04d781
XZZMemory/xpk
/Question13.py
1,007
4.15625
4
'''输入2个正整数lower和upper(lower≤upper≤100),请输出一张取值范围为[lower,upper]、且每次增加2华氏度的华氏-摄氏温度转换表。 温度转换的计算公式:C=5×(F−32)/9,其中:C表示摄氏温度,F表示华氏温度。 输入格式: 在一行中输入2个整数,分别表示lower和upper的值,中间用空格分开。 输出格式: 第一行输出:"fahr celsius" 接着每行输出一个华氏温度fahr(整型)与一个摄氏温度celsius(占据6个字符宽度,靠右对齐,保留1位小数)。只有摄氏温度输出占据6个字符, 若输入的范围不合法,则输出"Invalid."。 ''' lower, upper = input().split() lower, upper = int(lower), int(upper) if lower <= upper and upper <= 100: print("fahr celsius") while lower <= upper: result = 5 * (lower - 32) / 9.0 print("{:d}{:>6.1f}".format(lower, result)) # 只有摄氏温度输出占6个字符 lower += 2 else: print("Invalid.")
76a3faf2f22c74922f3a9a00b3f2380ad878b633
XZZMemory/xpk
/Question12.py
593
4.15625
4
'''本题要求将输入的任意3个整数从小到大输出。 输入格式: 输入在一行中给出3个整数,其间以空格分隔。 输出格式: 在一行中将3个整数从小到大输出,其间以“->”相连。''' a, b, c = input().split() a, b, c = int(a), int(b), int(c) # 小的赋值给变量a,大的赋值给变量b if a > b: temp = a a = b b = temp if c < a: print(str(c) + "->" + str(a) + "->" + str(b)) else: # c<a if c < b: print(str(a) + "->" + str(c) + "->" + str(b)) else: print(str(a) + "->" + str(b) + "->" + str(c))
16155fdabc0d8d70124d4e1b76040b5dd5189de4
Bahram3110/d16_w4_t1
/task4.py
233
3.75
4
name = input('Введите имя: ') name1 = name.lower() name2 = name[::-1] name2 = name2.lower() def cheking_name (name_revers): if name1 == name2: print("True") else: print('False') cheking_name(name)
47f9ed21fa7988e2b6bf1fe96d88d8774e83dcae
PaulSayantan/problem-solving
/HACKERRANK/Problem Solving/Implementation/Viral Advertising/viraladv.py
143
3.734375
4
#!/usr/bin/python3 shares, likes = 5, 2 for _ in range(int(input())-1): shares = (shares // 2) * 3 likes += shares // 2 print(likes)
002c584b14e9af36fe9db5858c64711ec0421533
PaulSayantan/problem-solving
/CODEWARS/sum_of_digits.py
889
4.25
4
''' Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. ''' import unittest def digitalRoot(n:int): if n < 10 and n > 0: return n add = 0 while n != 0: add += n % 10 n = n // 10 if add > 9: return digitalRoot(int(add)) else: return int(add) class digitRootTest(unittest.TestCase): def test1(self): self.assertEqual(digitalRoot(16), 7) def test2(self): self.assertEqual(digitalRoot(942), 6) def test3(self): self.assertEqual(digitalRoot(132189), 6) def test4(self): self.assertEqual(digitalRoot(493193), 2) if __name__ == "__main__": unittest.main()
7be21e3ee7c231c8d112a2d0b6788a1f26a0d15c
PaulSayantan/problem-solving
/LEETCODE/Easy/Merge Two Sorted Lists/mergeTwoLists.py
839
3.875
4
from typing import List def mergeTwoLists(l1: List[int], l2: List[int]) -> List[int]: return sorted(l1 + l2) if __name__ == "__main__": list1 = [int(x) for x in input().split()] list2 = [int(x) for x in input().split()] print(mergeTwoLists(list1, list2)) # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # class MergeTwoLists: # def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # if not l1: # return l2 # if not l2: # return l1 # if l1.val < l2.val: # head = l1 # tail = self.mergeTwoLists(l1.next, l2) # else: # head = l2 # tail = self.mergeTwoLists(l1, l2.next) # head.next = tail # return head
1661fa969a32c86a1b03683c6f841bf63a8d1293
PaulSayantan/problem-solving
/HACKERRANK/Problem Solving/Algorithms/Implementation/Sherlock and Squares/sherlocksquares.py
214
3.5625
4
from math import ceil, sqrt for _ in range(int(input())): a, b = (int(x) for x in input().split()) i = ceil(sqrt(a)) cnt = 0 while i <= sqrt(b): i += 1 cnt += 1 print(cnt)
bec67b41cc9eed65b949b86703c5f169be9e0e46
PaulSayantan/problem-solving
/HACKEREARTH/Data Structures/Arrays/1-D/microArrayUpdate.py
355
3.5625
4
def arrayUpdate(nums: list, target: int) -> int: if nums[0] >= target: return 0 return target - min(nums) if __name__ == "__main__": res = list() array_len, tar = (int(x) for x in input().split()) for _ in range(int(input())): res.append(arrayUpdate([int(x) for x in input().split()], tar)) [print(r) for r in res]
701089394efdb6d31a2266c1dc2b415b17ae3d84
PaulSayantan/problem-solving
/LEETCODE/Medium/Longest Substring Without Repeating Characters/longestsubstring.py
756
3.65625
4
def lengthOfLongestSubstring(s: str) -> int: left = length = 0 visited = dict() for pos, char in enumerate(s): if char in visited and visited[char] >= left: left = visited[char] + 1 else: length = max(length, pos - left + 1) visited[char] = pos return length # def lengthOfLongestSubstring(s: str) -> int: # left = pos = length = 0 # visited = dict() # while pos < len(s): # if visited.__contains__(s[pos]): # left = max(visited.get(s[pos]), left) # length = max(length, pos - left + 1) # visited[s[pos]] = pos + 1 # pos += 1 # return length if __name__ == "__main__": print(lengthOfLongestSubstring(input()))
28dbc9321520a7c8d083a6ce05b655f530fbdf6b
PaulSayantan/problem-solving
/HACKERRANK/Python/Collections/namedtuple.py
586
3.921875
4
from collections import namedtuple ''' Simplified Solution ''' total_students, Student = int(input()), namedtuple('Student', list(str(input()).split('\t'))) print('{:.2f}'.format(sum([int(Student(*input().split()).MARKS) for _ in range(total_students)]) / total_students)) ''' Descriptive Solution ''' # total_students = int(input()) # cols = list(input().split('\t')) # Student = namedtuple('Student', cols) # marks = 0 # for _ in range(total_students): # marks += int(Student(*input().split('\t')).MARKS) # print('{:.2f}'.format(marks / total_students))
0050ecdb924f57520cbcb2d0507e4fe18f370dc5
PaulSayantan/problem-solving
/CODEWARS/is_divide_by.py
1,028
3.78125
4
import unittest def is_divide_by(number, a, b): return (number % a) == 0 and (number % b) == 0 class is_divide_by_Test(unittest.TestCase): def test_case1(self): self.assertEqual(is_divide_by(-12, 2, -6), True) def test_case2(self): self.assertEqual(is_divide_by(-12, 2, -5), False) def test_case3(self): self.assertEqual(is_divide_by(45, 1, 6), False) def test_case4(self): self.assertEqual(is_divide_by(45, 5, 15), True) def test_case5(self): self.assertEqual(is_divide_by(4, 1, 4), True) def test_case6(self): self.assertEqual(is_divide_by(15, -5, 3), True) def test_case7(self): self.assertEqual(is_divide_by(3459, 2, 5), False) def test_case8(self): self.assertEqual(is_divide_by(3665, 1, 1), True) def test_case9(self): self.assertEqual(is_divide_by(5944, 2, 6), False) def test_case10(self): self.assertEqual(is_divide_by(8893, 3, 3), False) if __name__ == "__main__": unittest.main()
55951c1717bad99076d718197c1db303a517fce7
PaulSayantan/problem-solving
/CODEWARS/swapcase_n.py
1,194
3.9375
4
''' Your job is to change the string s using a non-negative integer n. Each bit in n will specify whether or not to swap the case for each alphabetic character in s. When you get to the last bit of n, circle back to the first bit. If the bit is 1, swap the case. If its 0, don't swap the case. You should skip the checking of bit when a non-alphabetic character is encountered, but they should be preserved in their original positions. ''' '''Simplified Solution''' from itertools import cycle def swap(s,n): b = cycle(bin(n)[2:]) return "".join(c.swapcase() if c.isalpha() and next(b) == '1' else c for c in s) '''Descriptive Solution''' def swap(s: str, n: int)-> str: string = list() binary = bin(n).replace('0b', '') pos = 0 for i in s: if i.isalpha(): if binary[pos] == '1': string.append(i.swapcase()) pos += 1 else: string.append(i) pos += 1 else: string.append(i) if pos == len(binary): pos = 0 return ''.join(string) if __name__ == "__main__": res = swap('the lord of the rings', 0) print(res)
85a5e091af32344e43fc344dc4a4bd483dca75a1
PaulSayantan/problem-solving
/HACKERRANK/Problem Solving/Algorithms/Implementation/Minimum Distances/minDist.py
867
3.75
4
import unittest from typing import List from collections import defaultdict def minimumDistances(arr: List[int], size: int) -> int: minDist = 10**5 position_map = dict() position_map = defaultdict(list) for pos, item in enumerate(arr): position_map[item].append(pos) for i in position_map: if type(position_map.get(i)) == list and len(position_map.get(i)) > 1: dist = position_map.get(i)[1] - position_map.get(i)[0] if dist < minDist: minDist = dist return minDist if minDist != 10**5 else -1 class TestMinDist(unittest.TestCase): def test_min_dist_1(self): self.assertEqual(minimumDistances([3, 2, 1, 2, 3], 5), 2) def test_min_dist_2(self): self.assertEqual(minimumDistances([7, 1, 3, 4, 1, 7], 6), 3) if __name__ == '__main__': unittest.main()
bf1738dc857220dc5abafc6e02d28be43b938d30
2kwattz/Guess-The-Number-Game
/numbergame2.py
774
3.90625
4
import pyfiglet import random number = random.randint(0,100) no_of_guesses = 0 banner = pyfiglet.figlet_format("Guess The Number") print(banner) print("Game by 2kwattz \nTries Left:10") while (no_of_guesses<10): no_of_guesses = no_of_guesses + 1 guess = int(input("Enter the number\n")) if guess>number: print(f"Enter a smaller number , {no_of_guesses} tries done") elif guess<number: print(f"enter a bigger number number , {no_of_guesses} tries done") elif guess == number: print(f"Congratulations! You guessed the number correct! \n The number is {number} \n") break else: print("Enter a valid number\n") break if no_of_guesses>9: print("GAME OVER\n")
cccfb6f481416b650f8bf04d0bfdff9a5e172a54
yosifbostandzhiev/problem_solving
/loops/prob1.py
221
4.0625
4
# 1. Write a program that inputs a positive integer N and outputs the factorial of 2N n = int(("Input your positive integer: ")) n = 2 * n n_fact = 1 for i in range(1, n): n_fact = n_fact + n_fact*i print(n_fact)
704201b4dc10807811036f9d879941ec2e34129f
Kyrixty/lol
/app/utilities.py
1,116
3.734375
4
import hashlib import random import string import os #test class Utility: ''' Provides useful general functions--such as generating a random string--of which can be useful to multiple programs in the application. ''' def genRandomString(size=10, chars=string.ascii_letters + string.digits): ''' Returns a random string with a default size of 10, using the string module. Usage: genRandomString() --> Will return a random string with a size of (size, default is 10). ''' return ''.join(random.choices(chars, k=size)) def hash_pass(password): #Hashes password with a randomly generated salt. salt = self.genRandomString(size=64) return hashlib.sha384(str(salt+password).encode()).hexdigest() def hash_pass_with_salt(password, salt): #Hashes password with a salt provided. return hashlib.sha384(str(salt+password).encode()).hexdigest() def get_site_news(): basedir = os.path.dirname(__file__) with open(basedir+"\\Site News.txt", mode="r") as f: return f.read()
6806bab64048c57dde3c6e19b46ac15252453fab
SeesawLiu/py
/radar-ted.py
1,070
3.515625
4
import matplotlib.pyplot as plt from math import pi # Abilities data ted_abilities = { 'COMPUTER': 62, 'ENGLISH': 55, 'LONGBOARD': 40, 'UKULELE': 35, 'DRIVING': 50, } # number of variable # categories=list(df)[1:] categories = ted_abilities.keys() N = len(categories) # But we need to repeat the first value to close the circular graph: values=list(ted_abilities.values()) values += values[:1] # What will be the angle of each axis in the plot? (we divide the plot / number of variable) angles = [n / float(N) * 2 * pi for n in range(N)] angles += angles[:1] # Initialise the spider plot ax = plt.subplot(111, polar=True) # Draw one axe per variable + add labels labels yet plt.xticks(angles[:-1], categories, color='#0047BD', size=10) # Draw ylabels ax.set_rlabel_position(0) plt.yticks([0,20,40,60,80], ["0","20","40","60","80"], color="#000000", size=8) plt.ylim(0,100) # Plot data ax.plot(angles, values, linewidth=1.5, linestyle='solid', color='#009543') # Fill area ax.fill(angles, values, 'b', color='#00AB38', alpha=0.6) plt.show()
96487cf3863ed2216c6ad83109b16e98c8955b3c
SeesawLiu/py
/abc/func/first_class_functions.py
2,150
4.34375
4
# Functions Are Objects # ===================== def yell(text): return text.upper() + '!' print(yell('hello')) bark = yell print(bark('woof')) # >>> del yell # >>> yell('hello?') # NameError: name 'yell' is not defined # >>> bark('hey') # HEY print(bark.__name__) # Functions Can Be Stored In Data Structures # ========================================== funcs = [bark, str.lower, str.capitalize] print(funcs) for f in funcs: print(f, f("hi there")) print(funcs[0]("yo man")) # Functions Can Be Passed To Other Functions # ========================================== def greet(func): greeting = func("Hi, I'm Python") print(greeting) greet(yell) def whisper(text): return text.lower() + '...' greet(whisper) print(map(yell, ['Hi', 'Hey', 'hi'])) # Functions Can Be Nested # ======================= def speak(text): def whisper(t): return t.lower() + '...' return whisper(text) print(speak("hi man")) # >>> whisper('Yo') # NameError: "name 'whisper' is not defined" # # >>> speak.whisper # AttributeError: "'function' object has no attribute 'whisper'" def get_speak_func(volume): def whisper(text): return text.lower() + '...' def yell(text): return text.upper() + '!' if volume > 0.5: return yell else: return whisper print(get_speak_func(0.3)) print(get_speak_func(0.6)) speak_func = get_speak_func(0.8) print(speak_func("oooooooooh")) # Functions Can Capture Local State # ================================= def get_speak_func2(text, volume): def whisper(): return text.lower() + '...' def yell(): return text.upper() + '!' if volume > 0.5: return yell else: return whisper print(get_speak_func2("bitch", 0.9)()) def make_adder(n): def add(x): return x + n return add plus_3 = make_adder(3) plus_5 = make_adder(5) print(plus_3(4)) print(plus_5(4)) # Objects Can Behave Like Functions # ================================= class Adder: def __init__(self, n): self.n = n def __call__(self, x): return self.n + x plus_3 = Adder(3) print(plus_3(7))
24d2adffcd84acfb126a3d618de6a9a4822876d2
KrishnaGupta72/Pandas
/3_different_ways_of_creating_dataframe/pandas_different_ways_of_creating_dataframe.py
1,109
3.765625
4
import pandas as pd #Read from a CSV file df = pd.read_csv("weather_data_1.csv") print(df) #Read from an Excel file df=pd.read_excel("weather_data_1.xlsx","Sheet1") print(df) #Creating a dataframe in JSON format weather_data = { 'day': ['1/1/2017','1/2/2017','1/3/2017'], 'temperature': [32,35,28], 'windspeed': [6,7,2], 'event': ['Rain', 'Sunny', 'Snow'] } df = pd.DataFrame(weather_data) print(df) #Creating a dataframe in List of Tuple format weather_data = [ ('1/1/2017',32,6,'Rain'), ('1/2/2017',35,7,'Sunny'), ('1/3/2017',28,2,'Snow') ] df = pd.DataFrame(data=weather_data, columns=['day','temperature','windspeed','event']) print(df) #Creating a dataframe in List of Tuple format weather_data = [ {'day': '1/1/2017', 'temperature': 32, 'windspeed': 6, 'event': 'Rain'}, {'day': '1/2/2017', 'temperature': 35, 'windspeed': 7, 'event': 'Sunny'}, {'day': '1/3/2017', 'temperature': 28, 'windspeed': 2, 'event': 'Snow'}, ] df = pd.DataFrame(data=weather_data, columns=['day', 'temperature', 'windspeed', 'event']) print(df)
f99bcedd6bed96991fb8fdf06eba27708ef867b1
dks1018/CoffeeShopCoding
/2021/Code/Python/DataStructures/dictionary_practice1.py
1,148
4.25
4
myList = ["a", "b", "c", "d"] letters = "abcdefghijklmnopqrstuvwxyz" numbers = "123456789" newString = " Mississippi ".join(numbers) print(newString) fruit = { "Orange":"Orange juicy citrus fruit", "Apple":"Red juicy friend", "Lemon":"Sour citrus fruit", "Lime":"Green sour fruit" } veggies = { "Spinach":"Katia does not like it", "Brussel Sprouts":"No one likes them", "Brocolli":"Makes people gassy" } veggies.update(fruit) print(veggies) superDictionary = fruit.copy() superDictionary.update(veggies) print(superDictionary) while True: user_input = str(input("Enter Fruit or Veggie: ")) if user_input == "quit": break if user_input in superDictionary or fruit or veggies: print(superDictionary.get(user_input)) if user_input not in superDictionary and fruit and veggies: print("Hey that item is not in the list, but let me add it for you!!") fruit_veggie = str(input("Enter your Fruit or Veggie: ")) desc = str(input("Enter the taste: ")) superDictionary[fruit_veggie] = desc print(superDictionary[fruit_veggie])
1c4e7bf09af67655c22846ecfc1312db04c3bfe1
dks1018/CoffeeShopCoding
/2021/Code/Python/Tutoring/Challenge/main.py
967
4.125
4
import time # You can edit this code and run it right here in the browser! # First we'll import some turtles and shapes: from turtle import * from shapes import * # Create a turtle named Tommy: tommy = Turtle() tommy.shape("turtle") tommy.speed(10) # Draw three circles: draw_circle(tommy, "green", 50, 0, 100) draw_circle(tommy, "green", 50, 0, 200) draw_circle(tommy, "blue", 50, 75, 25) draw_circle(tommy, "red", 50, -75, 25) # Draw three Squares draw_square(tommy, "green", 50, -50, -200) draw_square(tommy, "green", 50, -50, -300) draw_square(tommy, "blue", 50, 50, -200) draw_square(tommy, "red", 50, -150, -200) # Write a little message: tommy.penup() tommy.goto(0,-50) tommy.color("black") tommy.write("Darius's New Python Challenge", None, "center", "16pt 20") tommy.goto(0,-80) # Try changing draw_circle to draw_square, draw_triangle, or draw_star #The turtle program is finished turtle.done() #Dont close out GUI for (x) seconds #time.sleep(10)
45a6d829ada04a90c64a5bdd99822a5a7d8981c6
dks1018/CoffeeShopCoding
/2021/Code/Python/etc/test.py
1,335
3.96875
4
# Administrator accounts list def getCreds(): # Prompt the user for their username and store it in a variable called username username = input("What's your username? ") # Prompt the user for their password and store it in a variable called password password = input("what's your password?") return {"username": username, "password": password} # Create a dictionary that will store username and password combinations. user_info = [ { "username": username, "password": password }, { "username": username, "password": password } ] # Return the above list (called user_info) adminList = [ { "username": "DaBigBoss", "password": "DaBest" }, { "username": "root", "password": "toor" } ] getCreds() # Build your login functions below def checkLogin(user_info, adminList): for admin in adminList: if(admin["username"] == user_info["username"] and admin["password"] == user_info["password"]): return True return False LoggedIn = False while(LoggedIn == False): user = getCreds() LoggedIn = checkLogin(user, adminList) print("--------------") print("YOU HAVE LOGGED IN!")
894d15b0dc03ad3f22b07860143ab48363b71997
dks1018/CoffeeShopCoding
/2021/Code/Python/Tutoring/chrisName.py
114
4.09375
4
name = str(input("Please enter your name: ")) age = input("How old are you {0} ".format(name)) print(age) print()
760537b38c1899088736d0f4a3ba3d27fe3a29c5
dks1018/CoffeeShopCoding
/2021/Code/Python/Searches/BinarySearch/BinarySearch.py
1,779
4.15625
4
low = 1 high = 1000 print("Please think of a number between {} and {}".format(low, high)) input("Press ENTER to start") guesses = 1 while low != high: print("\tGuessing in the range of {} and {}".format(low, high)) # Calculate midpoint between low adn high values guess = low + (high - low) // 2 high_low = input("My guess is {}. Should I guess Higher or Lower?" "Enter h or l or c if my guess was correct " .format(guess)).casefold() if high_low == "h": # Guess higher.The low end of the range becomes 1 greater than the guess. low = guess + 1 elif high_low == "l": # Guess lower.The high end of the range becomes one less than the guess high = guess - 1 elif high_low == "c": print("I got it in {} guesses!".format(guesses)) break else: print("Please enter h,l, or c") guesses += 1 else: print("You thought of the number {}".format(low)) print("I got it in {} guesses".format(guesses)) #I am choosing 129 # with 1000 number what I want to do is be able to guess the users number within 10 guesses # to do this i need to continue to devide in half the high form the low # then establish a new high and low # if the number is 22 and the high is 100 and low is 0 first computer says # 1 is you number 50? higher or lower # lower, so high is 100-1 / 2 equals 49.5 rounded down high now equals 49 low now equals 0 # 2 is the number 25 or higher or lower # lower so high is 49-1 / 2 is 24 # 3 is you number 12, # it is higher so lower = guess + 1 # lower is 13 high is 24 # 4 is you number 18, # no high # 5 lower is 19, is your number 21 # no high lower equals 22 high equals 24 # 6 is your number 23, no lower # 7 your number is 22
7cc8eac1063d0b9c60f6e4ddfd1c504ed1b0fd83
dks1018/CoffeeShopCoding
/2021/Code/Python/PiProjects/CardGame/players.py
529
3.71875
4
class Gamers: def __init__(self, players, playerCount): self._players = players self._playerCount = playerCount def __playerInfo__(self): return "There are " + self.playerCount + " players, they are:\n" + self.players def __players__(self, count): self._playerCount = (int(input("How many people are playing: "))) def __playerNames__(self, players): for i in range(self._playerCount): self._players = (str(input("Input player names: ")))
a5b5097cfd81bf9b82e4ffd6b2e58001e71a8037
dks1018/CoffeeShopCoding
/2021/Code/Python/PythonCrypto/Module_3/openImage.py
534
3.5625
4
# Imports PIL module from PIL import Image def open_image(): # open method used to open different extension image file im = Image.open(r"C:\Users\dks10\OneDrive\Desktop\Projects\Code\Python\PythonCrypto\Module_3\eye.png") file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb') # file = open('eye.png', 'rb') open_f = file.read() # print(file) print(open_f) # This method will show image in any image viewer im.show() open_image()
960cf574b67f07b2b108e3ae01f2146ea6481777
dks1018/CoffeeShopCoding
/2021/Code/Python/DataStructures/class_practice1.py
363
3.96875
4
class Person(): def __init__(self,name,DOB,height,weight): self.name = name self.DOB = DOB self.height = height self.weight = weight Darius = Person("Darius", "10/18/1995","6 foot", 185) print(Darius.name) print(Darius.DOB) print(Darius.weight) print(Darius.height) Darius.name = "Darius Smith" print(Darius.name)
6ebdc47b984d3f9b7b65663b2ba01f9b54fc7edf
dks1018/CoffeeShopCoding
/2021/Code/Python/Exercises/Calculator2.py
1,480
4.1875
4
# Variable statements Number1 = input("Enter your first number: ") Number2 = input("Enter your second number: ") NumberAsk = input("Would you like to add a third number? Y or N: ") if NumberAsk == str("Y"): Number3 = input("Please enter your third number: ") Operation = input("What operation would you like to perform on these numbers? +, -, *, or /? ") # Operations Sum = (int(Number1) + int(Number2)) # noinspection PyUnboundLocalVariable Sum2 = (int(Number1) + int(Number2) + int(Number3)) Difference = (int(Number1) - int(Number2)) Difference2 = (int(Number1) - int(Number2) - int(Number3)) Product = (int(Number1) * int(Number2)) Product2 = (int(Number1) * int(Number2) * int(Number3)) Quotient = (int(Number1) / int(Number2)) Quotient2 = (int(Number1) / int(Number2) / int(Number3)) # Variable operations Addition = "+" Subtraction = "-" Multiplication = "*" Division = "/" # Conditionals if Operation == str("+") and NumberAsk == str("N"): print(Sum) if Operation == str("+") and NumberAsk == str("Y"): print(Sum2) if Operation == str("-") and NumberAsk == str("N"): print(Difference) if Operation == str("-") and NumberAsk == str("Y"): print(Difference2) if Operation == str("*") and NumberAsk == str("N"): print(Product) if Operation == str("*") and NumberAsk == str("Y"): print(Product2) if Operation == str("/") and NumberAsk == str("N"): print(Quotient) if Operation == str("/") and NumberAsk == str("Y"): print(Quotient2)
8295142ec306661b5435ca646424501b72209109
nikashamova/nsuPython
/part3/B/taskB.py
944
3.828125
4
import csv def is_anagram(str1, str2): return sorted(list(str1)) == sorted(list(str2)) file = open("input.txt", "r", encoding="utf-8") count = int(file.readline()) prepared_words = (([w.lower().strip() for w in file.readlines()])) total = [] added = [] for i in range((len(prepared_words) - 1)): if i in added: continue indexes = [i] word1 = prepared_words[i] result = [word1] for j in range(i + 1, len(prepared_words)): word2 = prepared_words[j] if j not in added and sorted(list(word1)) == sorted(list(word2)): added.append(j) indexes.append(j) result.append(word2) result = sorted(result) if len(result) > 1 and result not in total: total.append(result) added.append(i) total.sort() with open("output.txt", "w", encoding='utf-8', newline="", ) as f: writer = csv.writer(f, delimiter=' ') writer.writerows(total)
b926d7089ecc5e06fa191e30be164c4e10e2586e
nikashamova/nsuPython
/part3/A/task1.py
396
3.59375
4
import re file = open("input.txt", "r", encoding="utf-8") output = open("output.txt", "w", encoding="utf-8") count = int(file.readline()) regex = re.compile('[^а-я]') for i in range(count): s = file.readline() s = s.lower() s = s.replace('ё', 'е') s = regex.sub('', s) #print(s) if s == s[::-1]: output.write('yes\n') else: output.write('no\n')
b0bf2e4453a661cf855f33341dee690cb2478e0c
naivenlp/naivenlp-legacy
/naivenlp/structures/trie_test.py
1,677
3.65625
4
import unittest from .trie import Trie class TrieTest(unittest.TestCase): def testTrie(self): t = Trie() t.put("上海市 浦东新区".split()) t.put("上海市浦东新区") print() t.show() self.assertEqual('市', t.get('上海市').val) self.assertEqual('浦东新区', t.get('上海市 浦东新区'.split()).val) self.assertEqual('市', t.get('上海市').val) self.assertEqual('区', t.get('上海市浦东新区').val) self.assertEqual(None, t.get('上海市浦东区')) self.assertEqual(None, t.get('上海市浦东新区哈哈哈')) self.assertEqual(2, t.size()) self.assertEqual(True, t.contains('上海市 浦东新区'.split())) self.assertEqual(True, t.contains('上海市浦东新区')) self.assertEqual(True, t.contains('上海市浦东')) self.assertEqual('上海市浦东新区', t.longest_prefix_of('上海市浦东新区')) self.assertEqual('上海市浦东新', t.longest_prefix_of('上海市浦东新')) self.assertEqual(['上海市', '浦东新区'], t.longest_prefix_of('上海市 浦东新区'.split())) t.put('上海市黄浦区') for r in t.keys_with_prefix('上海市'): print(r) print('=' * 80) self.assertEqual(3, t.size()) t.delete('上海市浦东') t.show() self.assertEqual(False, t.is_empty()) print('=' * 80) t.delete('上') t.show() t.delete('上海市'.split()) t.show() self.assertEqual(True, t.is_empty()) if __name__ == "__main__": unittest.main()
dd6608fa6ec0b67c2bb03cb72a1c8e6286930a0f
MarceloMoraesTech/Calculadora
/calculadora.py
2,504
3.953125
4
menu=''' MENU ==== 1- Somar. 2- Subtrair. 3- Multiplicar. 4- Dividir. Escolha: ''' def leiaInt(msg): ok = False valor = 0 while True: soma_x = 0 soma_y = 0 subtrair_x = 0 subtrair_y = 0 multiplicar_x = 0 multiplicar_y = 0 dividir_x = 0 dividir_y = 0 god = soma_x + soma_y + subtrair_x + subtrair_y + multiplicar_x + multiplicar_y + dividir_x + dividir_y god = str(input(msg)) if god.isnumeric(): valor = int(god) ok = True else: print("ERRO. POR FAVOR DIGITE UM NÚMERO!") if ok: break return valor ######################################## #1 - SOMAR def somar(): soma_x= leiaInt("Digite um número:") soma_y= leiaInt("Digite outro número:") print("A soma dos numeros", soma_x, "e", soma_y, "é igual a:", soma_x+soma_y) ######################################## #2 - SUBTRAIR def subtrair(): subtrair_x= leiaInt("Digite um número:") subtrair_y= leiaInt("Digite outro número:") print("A subtração dos numeros", subtrair_x, "e", subtrair_y, "é igual a:", subtrair_x-subtrair_y) ######################################## #3 - MULTIPLICAR def multiplicar(): multiplicar_x= leiaInt("Digite um número:") multiplicar_y= leiaInt("Digite outro número:") print("A multiplicação dos numeros", multiplicar_x, "e", multiplicar_y, "é igual a:", multiplicar_x*multiplicar_y) ######################################## #4 - DIVIDIR def dividir(): try: dividir_x = leiaInt("Digite um número:") if dividir_x == 0: print("Não é possível dividir zero! Por favor digite outro número.") return dividir() dividir_y = leiaInt("Digite outro número:") print("O numero", dividir_x , "dividido por", dividir_y , "é igual a:", dividir_x/dividir_y) except ZeroDivisionError: print("Não é possível dividir um número por zero.") return dividir() ###PROGRAMA PRINCIPAL####### ############################ while True: escolha = input(menu) if escolha == '1': somar() if escolha == '2': subtrair() if escolha == '3': multiplicar() if escolha == '4': dividir() somar() subtrair() multiplicar() dividir()
9820a6e2fd5ffe8e532618197922cfa761367568
ajanzadeh/python_interview
/json/footbal_chalange.py
1,873
3.796875
4
# We want to be able to see how many goals a specific football team in the Premier League scored in total during the 2014/2015 season. All the information you need is contained in this JSON file https://raw.githubusercontent.com/openfootball/football.json/master/2014-15/en.1.json # # INPUT string teamKey ^^ the football team key name (is a parameter of the JSON) # # OUTPUT int goals ^^ an integer with the total number of goals scored by that team during the session # # EXAMPLE Input "arsenal" Output "X" ^^ number of goals scored by Arsenal in that JSON # # HTTP Libraries PHP: curl JavaScript: XMLHttpRequest - Example NodeJS: https - Example Python: urllib.request Ruby: net/http C#: System.Net.Http - Example Java: java.net - Example C++: curl/curl.h - Example Scala: scala.io.Source - Example Clojure: clj-http "3.8.0" # # JSON Libraries PHP: json_decode JavaScript: JSON.parse NodeJS: JSON.parse Python: import json Ruby: require 'json' C#: json.net 11.0.1 - Example Java: gson 2.8.2 - Example C++: jsoncpp 1.8.4 (json/json.h) - Example Scala: play.api.libs.json 2.6.x - Example Clojure: org.clojure/data.json 0.2.6 import urllib.request import json class Solution: def run(self, teamKey): goals = 0 # Write your code below; return type and arguments should be according to the problem's requirements # def get_json(url): with urllib.request.urlopen(url) as data: data = data.read() return json.loads(data.decode()) json_string = get_json("https://raw.githubusercontent.com/openfootball/football.json/master/2014-15/en.1.json") for item in json_string["rounds"]: #matches = item[counter]["matches"] for i in item["matches"]: if i["team1"]["key"] == teamKey : print(teamKey) goals += i["score1"] if i["team2"]["key"] == teamKey : goals += i["score2"] return goals sl = Solution() print(sl.run("arsenal"))
7b98a668260b8d5c0b729c6687e6c0a878574c9d
ajanzadeh/python_interview
/games/towers_of_hanoi.py
1,100
4.15625
4
# Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: # 1) Only one disk can be moved at a time. # 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. # 3) No disk may be placed on top of a smaller disk. # Take an example for 2 disks : # Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'. # # Step 1 : Shift first disk from 'A' to 'B'. # Step 2 : Shift second disk from 'A' to 'C'. # Step 3 : Shift first disk from 'B' to 'C'. # # The pattern here is : # Shift 'n-1' disks from 'A' to 'B'. # Shift last disk from 'A' to 'C'. # Shift 'n-1' disks from 'B' to 'C'. def tower(n,source,helper,dest): if n == 1: print("move disk",n, "from", source,"to",dest) return else: tower(n-1,source,dest,helper) print("move disk",n,"from",source,"to", dest) tower(n-1,helper,source,dest) tower(5,"a","b","c")
9d2e20a001b959ae8ec1e3d497245abc28b1eeec
ajanzadeh/python_interview
/algorithms/repated_word_in_a_file.py
619
3.921875
4
# how many times each word in a file has been repated from collections import defaultdict def repeate(path): dic = {} sort_dic = {} with open(path,"r") as f: lines = f.read().splitlines() for lin in range(0,len(lines)): words = lines[lin].split() for word in range(0,len(words)): if words[word] in dic: dic[words[word]] +=1 else: dic.setdefault(words[word],0) sort_dic = {k: v for k, v in sorted(dic.items(), reverse=True, key=lambda x: x[1])} print(sort_dic) repeate("algorithms/word_frequencies_text.txt")
ad5ffac1ad276520d141b2c270ebc461b06d3770
EddieGarciaDevOps/Dojo
/Python/fundamentals/ComparingLists/ComparingLists.py
971
3.890625
4
def compareLists(list_one, list_two): if len(list_one) == len(list_two): for i in range (0,len(list_one)): if type(list_one[i] == type(list_two[i])): if list_one[i] == list_two[i]: pass else: print "The lists are not the same." return else: print "The lists are not the same." return else: print "The lists are not the same." return print "The lists are the same." list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] list_three = [1,2,5,6,5] list_four = [1,2,5,6,5,3] list_five = [1,2,5,6,5,16] list_six = [1,2,5,6,5] list_seven = ['celery','carrots','bread','milk'] list_eight = ['celery','carrots','bread','cream'] compareLists(list_one, list_two) compareLists(list_three, list_four) compareLists(list_five, list_six) compareLists(list_seven, list_eight) compareLists(list_three, list_six)
14e2bc48c90948afbe1ed92b65d95ceabc56de1f
EddieGarciaDevOps/Dojo
/Python/fundamentals/FindingCharacters/FindingCharacters.py
256
4.03125
4
word_list = ['hello','world','my','name','is','Anna'] char = 'o' def findWords(letter, wordList): newList = [] for word in wordList: if letter in word: newList.append(word) return newList print findWords(char, word_list)
a1b6118e177e6ac1451863e5ae7943fe8fcfc126
mark-jay/machine-learning
/supervised/tree.py
10,418
3.65625
4
''' decision tree ''' from math import log import operator, sys #entropy is about the information of target value. def calEntropy(dataSet): numEntries = len(dataSet) labelCount = {} for featVec in dataSet: #get the target value curLabel = featVec[-1] if curLabel not in labelCount.keys(): labelCount[curLabel] = 0 labelCount[curLabel] +=1 entropy = 0.0 #iterate each key of labelCount #print 'dict: ', labelCount #both iterations work #for k, v in labelCount.iteritems(): #prob = float(v)/numEntries for key in labelCount: prob = float(labelCount[key])/numEntries # log2(prob) entropy -= prob * log(prob, 2) return entropy def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] # two features. labels = ['no suffacing', 'flippers'] return dataSet, labels ''' dataset splitting on a given feature. axis: the feature col, value: the col divided by two groups, equal to value, or not equal to value. The feature col is removed after being used to split. return the dataset equals to value. ''' def splitDataSet(dataSet, axis, value): # create a new list to keep origin dataSet intact. resultDataSet = [] for featureVec in dataSet: if featureVec[axis] == value: # keep the data in front of the feature col resultVec = featureVec[:axis] # keep the data behind the feature col resultVec.extend(featureVec[axis+1:]) resultDataSet.append(resultVec) return resultDataSet ''' Split the dataset across every feature to see which split gives the highest information gains. calculate entropy, split the dataset, measure the entropy on the split sets, and see if splitting it was the right thing to do. apply this for all features to determine the best feature to split on. split on the best feature, best organize the data. assumption: 1. dataset is a list of lists, all the lists are of equal size. 2. the last col of dataset is the class labels. ''' def chooseFeatureToSplit(dataSet): numFeatures = len(dataSet[0]) - 1 baseEntropy = calEntropy(dataSet) bestInfoGain = 0.0 bestFeature = numFeatures-1 for i in range(numFeatures): # get the feature col featureCol = [example[i] for example in dataSet] uniqueVals = set(featureCol) newEntropy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) prob = float(len(subDataSet))/len(featureCol) newEntropy = prob * calEntropy(subDataSet) # the higher the entropy, the more mixed up the data. # large infoGain -> lower newEntropy # infoGain is the reduction in entropy or the reduction in messiness infoGain = baseEntropy - newEntropy if (infoGain > bestInfoGain): bestInfoGain = infoGain bestFeature = i return bestFeature ''' split the tree to more than two-way branches. terminate: run out of features to split or all instances in a branch are the same class. if run out of features but the class labels are not all the same, a majority vote is used to decide the class of leaf node. If all instances have the same class, create a leaf node. Any data that reaches the leaf node is deemed to belong to the class of that leaf node. ''' def majorityCount(classList): classCount = {} for classVal in classList: if classVal not in classCount.keys(): classCount[classVal] = 0 classCount[classVal] += 1 #sort by the value. sortedClassCount = sorted(classCount.items(), \ key=operator.itemgetter(1), reverse=True) #return the first element's value. return sortedClassCount[0][0] ''' build a decision tree by recursively choosing the best splitting. a decision tree is represented by a dict, tree = {bestFeature: {instances}} labels: the list of features. ''' def createDecisionTree(dataSet, labels): classList = [example[-1] for example in dataSet] #terminate cond1: all instances in the same class if classList.count(classList[0]) == len(classList): return classList[0] #terminate cond2: no more features, apply majorityCount if len(dataSet[0]) == 1: return majorityCount(classList) #bestFeature is the index of featureList bestFeature = chooseFeatureToSplit(dataSet) bestFeatureLabel = labels[bestFeature] decisionTree = {bestFeatureLabel: {}} #remaining features #del(labels[bestFeature]) #similar to splitDataSet() featureCol = [example[bestFeature] for example in dataSet] uniqueFeatureVals = set(featureCol) #bestFeature is marked in node, each value is an outgoing tran. #tree = {bestFeature: {outgoing trans}} #an outgoing tran = {value: subtree} for value in uniqueFeatureVals: #subLables is a copy of lables. keep the original list intact for #each call of createDecisionTree(). subLabels = labels[:bestFeature] subLabels.extend(labels[bestFeature+1:]) #iterate all unique values from chosen feature and recursively #call createDecisionTree() for each split of dataset. dt = createDecisionTree(\ splitDataSet(dataSet, bestFeature, value), subLabels) decisionTree[bestFeatureLabel][value] = dt return decisionTree #traverse the tree and count the leaf nodes. #compare two strings use cmp(), not == def getNumLeafs(dTree): numLeaf = 0 firstKey = dTree.keys()[0] secondDict = dTree[firstKey] #return for the leaf nodes. #if cmp(type(secondDict).__name__ ,'dict') != 0: #return 0 for key in secondDict.keys(): #if cmp(type(secondDict[key]).__name__,'dict') == 0: if isinstance(secondDict[key], dict): numLeaf += getNumLeafs(secondDict[key]) else: numLeaf += 1 return numLeaf ''' traverse the tree and count the time hitting the decision nodes. the elements in dict are randomly {k: v}. passed dTree in recursive might be {k1:a, k2: {a, b, c}}. But getTreeDepth() assume dTree is {k2: {a, b, c} It is weird that getTreeDepth() works without checking dict before for loop and using == to compare two strings. ''' def getTreeDepth(dTree): depth = 0 firstStr = dTree.keys()[0] secondDict = dTree[firstStr] for key in secondDict.keys(): #if type(secondDict[key]).__name__ == 'dict': if isinstance(secondDict[key], dict): thisDepth = 1 + getTreeDepth(secondDict[key]) else: thisDepth = 1 #depth is the deepest branch. if thisDepth > depth: depth = thisDepth return depth #artificial decision tree for testing. def testTree(i): listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers':\ {0: 'no', 1: 'yes'}}}}, {'no surfacing': {0: 'no', 1: {'flippers': \ {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}} ] return listOfTrees[i] ''' Given decision tree and featureLabels, take the unknown data to compare it against the values in the decision tree recursively until it hits a leaf node. ''' def classify(decisionTree, featureList, testVec): if not(isinstance(decisionTree, dict)): return descisionTree firstFeature = decisionTree.keys()[0] featureIndex = featureList.index(firstFeature) secondDict = decisionTree[firstFeature] testValue = testVec[featureIndex] valueOfDict = secondDict[testValue] if isinstance(valueOfDict, dict): classLabel = classify(valueOfDict, featureList, testVec) else: classLabel = valueOfDict return classLabel #store the decision tree using pickle. def storeTree(dTree, filename): import pickle fw = open(filename, 'w') pickle.dump(dTree, fw) fw.close() #retrieve the object from pickle def readTree(filename): import pickle fr = open(filename) return pickle.load(fr) def contactLenTree(filename): fr = open(filename) lenses = [inst.strip().split('\t') for inst in fr.readlines()] features = ['age', 'prescript', 'astigmatic', 'tearRate'] lenseTree = createDecisionTree(lenses, features) return lenseTree def orangeDatasetToDecisionTree(dataset): import orange # features as string featLabels = map(lambda f : f.name, dataset.domain.features) # normalizing data to fit createDecisionTree. So the class value always wiil be last def f(row): r = map(lambda featName : str(row[featName]), featLabels) + [str(row[row.domain.classVar.name])] return r normalizedData = map(f, dataset) return createDecisionTree(normalizedData, featLabels) # reads orange suitable file, converts and returns decision tree, example: # d = tree.orangeAdapter("../dataset/lenses.tab") def orangeAdapter(filename): import orange return orangeDatasetToDecisionTree(orange.ExampleTable(filename)) # prints a decision tree to a string, example: # print tree.treeToStr(tree.orangeAdapter("../dataset/lenses.tab")) def treeToStr(decisionTree, indent = 0, indentBy = 1): def indentToStr(indent): return " "*indent # tree is just a class value if type(decisionTree) != dict: return indentToStr(indent) + decisionTree+"\n" # otherwise it is a dict def f( (featName, aDict) ): featStr = indentToStr(indent+indentBy) + featName + ":\n" dictStr = treeToStr(aDict, indent+(indentBy*2), indentBy) return featStr + dictStr return ''.join(map(f, decisionTree.items())) def getStats(decisionTree, testingOrangeDataset): def isGoodClassified(row): fs = map(lambda f: f.name, row.domain.features) vs = map(lambda f: str(row[f]), fs) realValue = str(row[row.domain.classVar]) return classify(decisionTree, map(str, fs), vs) == realValue goodClassified = filter(isGoodClassified, testingOrangeDataset) return (len(goodClassified), len(testingOrangeDataset)) def testOnDataID3(trainingSet, testingSet): return getStats(orangeDatasetToDecisionTree(trainingSet), testingSet)
e4d99bb5a2f1a22c90c89aae263a6e4222ca54db
mas-kon/Python_Learn
/find_mutiples.py
959
4.03125
4
def find_multipex(x, y): z = 0 lst = [] # if not isinstance(x, int): # print("Число должно быть INT!") # return 0 # elif not isinstance(y, int): # print("Лимит должен быть INT!") # return 0 if y < x: # print("Лимит должен быть больше числа!") print(lst) return 0 else: for i in range (1,y): i = i * x lst.insert(z, i) z = z + 1 if i > y: lst.pop() # Костыль :( print(lst) return # print(i) yes_or_no = "y" while (yes_or_no == "y" or yes_or_no == "Y"): num_int = int (input ("Введите число: ")) lim_int = int (input ("Введите лимит: ")) find_multipex (num_int, lim_int) yes_or_no = input ("Для продолжения нажмите y или Y: ")
ca091bae52a3e79cece2324fe946bc6a52ca6c2f
mrmuli/.bin
/scripts/python_datastructures.py
2,019
4.15625
4
# I have decided to version these are functions and operations I have used in various places from mentorship sessions # articles and random examples, makes it easier for me to track on GitHub. # Feel free to use what you want, I'll try to document as much as I can :) def sample(): """ Loop through number range 1 though 11 and multiply by 2 """ total = 0 # to be explicit about even numbers, you can add a step to range as: range(2,11,2) for number in range(2, 101, 2): # If the number is 4, skip and continue if number == 4: continue total += number # Calculate the product of number and 2 product = number * 2 # Print out the product in a friendly way print(number, '* 2 = ', product) # sample() def password_authenticate(): """ A very simple way to validate or authenticate """ # set random value and Boolean check. (This is subject to change, on preference.) user_pass = "potato" valid = False while not valid: password = input("Please enter your password: ") if password == user_pass: print("welcome back user!") valid = True else: print("Wrong password, please try again.") print("bye!") # password_authenticate() # use of pass, continue and break def statements_demo(): for number in range(0, 200): if number == 0: continue elif number % 3 != 0: continue elif type(number) != int: break else: pass print(number) # statements_demo() def nested_example(): for even in range(2, 11, 2): for odd in range(1, 11, 2): val = even + odd print(even, "+", odd, "=", val) print(val) # nested_example() def randome_args(*args): for value in args: if type(value) == int: continue print(value) # randome_args(1,2,3,4,"five","six","seven",8,"nine",10)
356122c10a2bb46ca7078e78e991a08781c46254
KingHammer883/21.Testing-for-a-Substring-with-the-in-operator.py
/21.Testing-for-Substring-With-the-in-operator.py
752
4.40625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 18, 2019 File: Testing for a Substring with the in operator @author: Byen23 Another problem involves picking out strings that contains known substrings. FOr example you might wnat to pick out filenames with a .txt extension. A slice would work for this but using Python's in operator is the right operand is the string to be searched. The operator in returns True if the target string is somewhere in teh search string, or False otherwise. The next code segment traverses a list of filenames and prints just the filenames taht have a .txt extension: """ filelist = ["myfile.txt", "myprogram.exe", "yourfile.txt"] for fileName in filelist: if ".txt" in fileName: print(fileName)
aafdb81d8579da905c67eab9210eaf86eab191cc
ChuckyNTG/PythonProgramming
/main_game.py
3,785
3.9375
4
import random as rand ######## # Command Line Game designed by my 7 year-old sister. Programming done by ChuckyNTG. # # ####### #Add points for correctanswers, powerups for hard questions if you have enough points #Dress up person with hats incomplete_sentences = ['The dog ___ outside','I swam ___ dad','My dad ___ leaves outside','I went trick-or-treating with ___ ___ ___','Dad and I put up the ___ on the tree','At midnight, we opened all our ___'] solutions = ['ran','with','raked','Mom and Dad','star'] word_choices = [['ran','played','flew','fell'],['outside','away','with','above'],['used','hugged','smacked','raked'],['Ghost and Mummy','Devil and God','Neighbors','Mom and Dad'],['Strawberry','Eyeball','Cat','Star'],['Beers','rifles','wallets','presents']] sentences = zip(incomplete_sentences, solutions, word_choices) powerups_choose_word = [('Skip Level',9),('Give Hints',2),('Remove all but two',6)] def check_spelling(word): user_written = raw_input("Enter the spelling for the word:") if user_written.lower() == word.lower(): return True else: return False def play_again(): while True: play_again = raw_input("Would you like to play again(Y/N)?") if play_again.lower() in ['y','yes']: return True elif play_again.lower() in ['n','no']: print 'Goodbye, {0}'.format(name) return False else: print 'Your choice is invalid! Please choose again!' continue def spelling_game(): hand_coins = 10 #Voice reading while True: if len(sentences) != 0: sentence = rand.choice(sentences) sentences.remove(sentence) word_list = sentence[2] else: print 'No more sentences!' break print 'Please finish this sentence by entering a number!:\n' print '{0}\n'.format(sentence[0]) print '1. {0}\t\t2.{1}\n3. {2}\t\t4.{3}\n'.format(word_list[0], word_list[1], word_list[2], word_list[3]) print 'Choose powerups:' for index, powerup in enumerate(powerups_choose_word): print '{0}{0}. {1}'.format(index+1,powerup[0]) print '\n' while True: try: choice = int(raw_input("Enter Your Choice:")) print 'You chose {0}'.format(word_list[choice-1]) break #input validation on choice except ValueError: print 'Please enter a number for your choice' continue except IndexError: print 'Your choice {0} is invalid'.format(choice) continue #check if the word is the right word if sentence[1] == word_list[choice-1]: print 'You chose right! Have 10 coins!' hand_coins += 10 #Ask the user to spell the word while True: print 'Please spell the word: {0}'.format(word_list[choice-1]) if check_spelling(word_list[choice-1]): print 'Nice Job! You spelled the word right!' hand_coins += 20 break else: print 'You spelled it wrong, please try again! You have lost 3 coins.' hand_coins -= 3 continue else: print 'You chose wrong! You have lost 2 coins. Please try again.' hand_coins -= 2 continue print 'You have {0} coins'.format(hand_coins) if play_again(): continue else: break if __name__ == '__main__': name = raw_input("Enter Your Name:") print 'Hello, {0}'.format(name) spelling_game() exit()
ce8efceb3e7f107d5f62dd29ad37966b711de7d2
ChuckyNTG/PythonProgramming
/AlgoDataStruc/Sort/MergeSort.py
869
3.921875
4
def start(array): sort(array, 0, len(array)) def sort(array, lo, hi): #Keep splitting array in half until it is at its base if lo>=hi: return mid = (lo+hi)/2 sort(array,lo, mid) sort(array,mid+1, hi) merge(array,lo,hi) print array def merge(array, lo, high): #array to take values from aux = [] for k in array: aux.append(k) #left array index i = lo #right array start index mid = (lo+high)/2 j = mid print i,j #we want to merge lo to high for k in range(lo,high): if aux[i]>aux[j]: array[k] = aux[j] j+=1 elif aux[j]>aux[i]: array[k] = aux[i] i+=1 elif i>mid: array[k] = aux[j] j+=1 elif j>high: array[k] = aux[i] i+=1 start(range(20,0,-1))
69e8422f3960744a76812f8981e9a9aaf8b5e41a
ChuckyNTG/PythonProgramming
/Problems/Kattis/Line_Them_Up.py
428
3.625
4
from itertools import izip, tee team = [] for _ in range(0,int(raw_input())): team.append(raw_input()) t = iter(team) prev, cur = tee(t, 2) cur.next() paired = list(izip(prev,cur)) state = 0 for pair in paired: if pair[0] > pair[1]: state += -1 else: state += 1 if state == len(team)-1: print 'INCREASING' elif state == -len(team)+1: print 'DECREASING' else: print 'NEITHER'
d0a8d768edb0e216948c41c53592d2fadb2241db
Jalbanese1441/Waterloo-CS-Circles-Solutions
/7B Geometric Mean.py
83
3.53125
4
a = float(input()) b = float(input()) import math test = a*b print(math.sqrt(test))
5826f0021893bd43bd0bb7ef913184f78dad2942
Jalbanese1441/Waterloo-CS-Circles-Solutions
/15A Smart Simulation.py
483
3.53125
4
def findLine(prog, target): for i in range(len(prog)): splited=prog[i].split() if splited[0]==str(target): return i def execute(prog): location = 0 i=10 visited=[False]*len(prog) for i in range(len(prog)): if location==len(prog)-1: return "success" temp=(prog[location].split()) T=temp[2] if visited[location]==True: return "infinite loop" visited[location]=True location = findLine(prog, T) location = findLine(prog, T)
5e5806c33987009c9f599df3eb73b04d2cd84a67
Jalbanese1441/Waterloo-CS-Circles-Solutions
/11A Lower-case Characters.py
152
3.765625
4
def lowerChar(char): if ord(char) >= ord('A') and ord(char) <= ord('Z'): char = chr(ord(char)+32) return char else: return char
775ae5471b1d90a1dd88ac4ffb9cad75ac315934
antdke/Basketball-Simulator-in-Python
/Basketball3.py
5,422
3.9375
4
## Anthony Dike started: 3/8/18 ## ## This is VERSION 3 of a program that ## will simulate basketball games like NBA 2k. ## ## In this version I will add ## 1) More Overtime and Sportcasting (announcers and stuff) ## 2) Notifier that says when team is blown out or a close game ## 3) Win Counter ## ## abbreviations: ## ffv: for future versions """ NOTES FOR PRE PUblISHING REFERENCES - should probs make 1 game score print (ie if OT played, oly print OT) """ import random ''' Steps: 1) add more emotive print statement - for ots, for close games - make a random function that causes events based on random ints (snow, rain, winter, summer, celebrities, etc) and make sportscasters react to that news while talking. DONE 2) 3) make function that counts how many ots occur and if one doesnt happen after a certain number of times (maybe make that counter # random 1-10) then an ot game is played 4) 5) ''' # EVENT SPEECH TRIGGER FUNCTIONS #def RandomizeEventTriggers(): # use dictionary or list to store event functions # randomize selection from the container def WeatherTrigger(): # weather list weather = ['rain', 'snow', 'sunny'] #randommize index int weatherToday = weather[random.randint(0,(len(weather) - 1))] #choose random weather return weatherToday def RainTalk(): # commentary list on rain rainTalk = [ "I hope you all have your umbrellas tonight, sports fans, 'cuz it'll be raining all night!", "It's raining cats and dogs outside tonight, sports fans!", "It's been so hot lately, glad we got some rain to cool things down!" ] # randomize index int rainTalkChoice = rainTalk[random.randint(0,(len(rainTalk) - 1))] # choose random commentary choice return rainTalkChoice def SnowTalk(): # commentary list on rain snowTalk = [ "Stay warm sports fans, it's freezing outside today!", "It is absolutely frigid outside today in the city, hope y'all are warm!", "Lets all enjoy this game, while the temperatures drop outside!" ] # randomize index int snowTalkChoice = snowTalk[random.randint(0,(len(snowTalk) - 1))] # choose random commentary choice return snowTalkChoice def SunnyTalk(): # commentary list on rain sunnyTalk = [ "It's a beautiful sunny day out today, sports fans!", "Wouldn't it be great if this game was played outside in the nice weather, sports fans? If only!", "Such a lovely sunny day for sports!" ] # randomize index int sunnyTalkChoice = sunnyTalk[random.randint(0,(len(sunnyTalk) - 1))] # choose random commentary choice return sunnyTalkChoice def OvertimeTeam1(): overtimeAdder = random.randint(0,30) global Team1 Team1 += overtimeAdder global team1OT team1OT = Team1 return team1OT def OvertimeTeam2(): overtimeAdder = random.randint(0,30) global Team2 Team2 += overtimeAdder global team2OT team2OT = Team2 return team2OT def SportscastingIntro(): # intro print("\nWelcome back sports fans! Time for another day of basketball!\n") #ffv: create team name variables # weather commentary weatherToday = WeatherTrigger() if weatherToday == 'rain': print(RainTalk()) print() elif weatherToday == 'snow': print(SnowTalk()) print() elif weatherToday == 'sunny': print(SunnyTalk()) print() # where the team points calc takes place def Game(): # create max and min scores maxScore = 122 minScore = 98 # initialize team variables global Team1 Team1 = random.randint(minScore, maxScore) global Team2 Team2 = random.randint(minScore, maxScore) # if tie trigger overtime if Team1 == Team2: otScore1 = OvertimeTeam1() otScore2 = OvertimeTeam2() print("There was an overtime!") # prints overtime print("OVERTIME: Team 1 - " + str(otScore1) + " Team 2 - " + str(otScore2)) print() if otScore1 == otScore2: Team1 = otScore1 Team2 = otScore2 dotScore1 = OvertimeTeam1() dotScore2 = OvertimeTeam2() print("After a well fought regulation and a grueling two overtimes, Team 1 finished with " + str(dotScore1) + " and Team 2 ended up with " + str(dotScore2)) else: print("\nREGULATION: Team1 - " + str(Team1) + " Team 2 - " + str(Team2)) # welcome message print() print("----------------------------------------------") print("| HELLO, WELCOME TO THE BASKETBALL SIMULATOR |") print("----------------------------------------------") print() proceed = False while proceed == False: print("\t Would you like to start a game?") print() answer = input("(YES or NO): ") print() if answer.lower() == "yes": print() SportscastingIntro() Game() print() elif answer.lower() == "no": proceed = True break else: print("INVALID INPUT. Try Again.") print() # closing message print() print("----------------------------------------------") print("| GOODBYE, THANK YOU FOR PLAYING! |") print("----------------------------------------------") print()
d73a4b41708799494b39b64071ca0a48ba8c5a74
swaroski/AIDeepDive
/deepdiveday1.py
645
4.09375
4
#1) function that converts the argument into a string def convert_to_string(string): return str(string) #2) function that takes two lists as arguments, # checks whether the two lists have overlapping elements # and either returns the duplicated elements or provides a nice message a = [] b = [] def two_lists(a,b): #a = [] #b = [] if a == b: return a, b else: print("Go to hell") # Create a function that tries to replace index 0 of the argument passed # with the word "pancakes" def pancakes(mylist): mylist[0] = "pancakes" return mylist pancakes([1,2,3])
9c0a683edece6cbd45bc96e33340374ec2962674
jlgm/vd-scraping
/src/elem_handler.py
1,350
3.65625
4
"""this module will deal with the parts of github urls""" class Elem(object): """Class that provides utility for github urls""" def __init__(self, url): self.url = url def is_blob(self): """returns true if this elem is a file and false if it is a folder""" parts = self.url.split('/') if len(parts) < 4: return False return parts[3] == "blob" def name(self): """returns the name of the file or folder""" parts = self.url.split('/') return parts[-1] def blob_to_raw(self): """replaces 'blob' with 'raw' in this elem url, allowing the scraper to fetch only the file instead of the html""" if not self.is_blob(): raise NameError("not a blob!") parts = self.url.split('/') raw = parts[0] for part in parts[1:]: if part != "blob": raw += ("/"+part) else: raw += "/raw" return raw def extension(self): """returns the extension of this file if it has one""" if not self.is_blob(): raise NameError("not a blob!") name = self.name() if name[0] == '.': return "<other>" elif '.' not in name: return "<other>" else: return name.split('.')[-1]
0606ac38799bfe01af2feda28a40d7b863867569
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/12. Downloading data from input/downloading-data.py
260
4.15625
4
print("Program that adds two numbers to each other") a = int(input("First number: ")) b = int(input("Second number: ")) #CASTING allows you to change ONE type of variable to another type of variable print("Sum of a =", a, "+", "b =", b, "is equal to", a + b)
1d863dd58506bb382ce3850784b38e60813fa385
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/24. List 'in', 'not in'/listain.py
305
4.03125
4
# in # not in # operations on list names = ["Arkadiusz", "Claire", "Peter", "Jacob"] numbers = [3, 12, 24, 7, -8] if ("John" not in names): print("Hello John, welcome!") if (4 in numbers): print("Number 4 is inside the list called numbers") else: print("Number 4 is not inside the list")
7702aca0ec88345ab7697aa1f98a136dea291bf0
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/66. reading content from file/openingfiles.py
803
3.796875
4
""" FILE - name of location that stores pernamently data RAM - temporary data storage Operations you can do on a file: 1) opening 2) writing/reading 3) closing basic modes(ways) of opening files: r - R ead - default w - W rite - if the file existed (will be removed), if not will be created a - A ppend (adding new content at the end) extension is simply saying TEXT that is there only to make sure other programs know what is inside the type of file for example txt suggest there is text inside EXCEPTION - an exceptional (unusal) situation in program that makes your program suddenly stop working read readline readlines splitlines """ with open("namesurnames.txt", "r", encoding="UTF-8") as file: for line in file: print(line, end='')
ec03b7eaf28bf5ce9f37534754278e630471f494
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/45. Measuring performance of code/arithmeticsequence.py
924
3.875
4
""" Measuring the performance of code """ import time def sum_up_to(end): sum = 0 for number in range(1, end+1): sum = sum + number return sum def sum_up_to2(end): return sum([number for number in range(1, end+1)]) def sum_up_to3(end): return sum({number for number in range(1, end+1)}) def sum_up_to4(end): return sum((number for number in range(1, end+1))) def sum_up_to5(end): return (1 + end) / 2 * end start = time.perf_counter() print(sum_up_to(325)) end = time.perf_counter() print(end-start) start = time.perf_counter() print(sum_up_to2(325)) end = time.perf_counter() print(end-start) start = time.perf_counter() print(sum_up_to3(325)) end = time.perf_counter() print(end-start) start = time.perf_counter() print(sum_up_to4(325)) end = time.perf_counter() print(end-start) start = time.perf_counter() print(sum_up_to5(325)) end = time.perf_counter() print(end-start)
cafe85ae01b5271bd86dd82c797fdbcfddb06be5
rosnikv/OpenCV2-Python
/Official_Tutorial_Python_Codes/2_core/fiter2d.py
867
3.59375
4
''' file name : filter2d.py Description : This sample shows how to filter/convolve an image with a kernel This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/core/mat-mask-operations/mat-mask-operations.html#the-filter2d-function Level : Beginner Benefits : Learn to convolve with cv2.filter2D function Usage : python filter2d.py Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' import cv2 import numpy as np img = cv2.imread('lena.jpg') kernel = np.array([ [0,-1,0], [-1,5,-1], [0,-1,0] ],np.float32) # kernel should be floating point type. new_img = cv2.filter2D(img,-1,kernel) # ddepth = -1, means destination image has depth same as input image. cv2.imshow('img',img) cv2.imshow('new',new_img) cv2.waitKey(0) cv2.destroyAllWindows()
ba212ce447ccd81cede48f43906bd3590a6381cd
rosnikv/OpenCV2-Python
/Official_Tutorial_Python_Codes/3_imgproc/remap.py
1,821
3.9375
4
''' file name : remap.py Description : This sample shows how to remap images This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/remap/remap.html#remap Level : Beginner Benefits : Learn to use remap function Usage : python remap.py Written by : Abid K. (abidrahman2@gmail.com) , Visit opencvpython.blogspot.com for more tutorials ''' import cv2 import numpy as np def update(): global ind ind = ind%4 for j in xrange(rows): for i in xrange(cols): if ind == 0: # Resize and center the image if 0.25*cols< i <0.75*cols and 0.25*rows< j <0.75*rows: map_x.itemset((j,i),2*( i - cols*0.25 ) + 0.5) map_y.itemset((j,i),2*( j - rows*0.25 ) + 0.5) else: # Other pixel values set to zero map_x.itemset((j,i),0) map_y.itemset((j,i),0) elif ind == 1: # Flip image in vertical direction, alternatively you can use np.flipud or cv2.flip map_x.itemset((j,i),i) map_y.itemset((j,i),rows-j) elif ind == 2: # Flip image in horizontal direction, you can use np.fliplr or cv2.flip map_x.itemset((j,i),cols-i) map_y.itemset((j,i),j) elif ind == 3: # Flip image in both the directions, you can use cv2.flip(flag = -1) map_x.itemset((j,i),cols-i) map_y.itemset((j,i),rows-j) ind = ind+1 img = cv2.imread('messi5.jpg') ind = 0 map_x = np.zeros(img.shape[:2],np.float32) map_y = np.zeros(img.shape[:2],np.float32) rows,cols = img.shape[:2] while(True): update() dst = cv2.remap(img,map_x,map_y,cv2.INTER_LINEAR) cv2.imshow('dst',dst) if cv2.waitKey(1000)==27: break cv2.destroyAllWindows()
6ea202990b68777ed61d70b06f5eb9ee7f0acf2a
Anteru/luna
/luna/geo.py
4,096
3.53125
4
from numbers import Number import copy class Vector2: def __init__ (self, *args): if len (args) == 1: assert (hasattr (args [0], '__len__') and len (args[0]) == 2) self.x = args [0][0] self.y = args [0][1] else: assert (len (args) == 2) assert (isinstance (args [0], Number)) assert (isinstance (args [1], Number)) self.x = args [0] self.y = args [1] def __repr__ (self): return 'Vector2 ({}, {})'.format (self.x, self.y) def __eq__ (self, other): if isinstance (other, Vector2): return self.x == other.x and self.y == other.y else: return self.x == other [0] and self.y == other [1] def __ne__ (self, other): return not self.__eq__ (other) def __len__(self): return 2 def __getitem__ (self, key): if key == 0: return self.x elif key == 1: return self.y def __setitem__ (self, key, value): if key == 0: self.x = value elif key == 1: self.y = value def __iter__ (self): return iter([self.x, self.y]) def __add__ (self, other): if isinstance (other, Vector2): return Vector2 (self.x + other.x, self.y + other.y) else: assert (hasattr (other, '__len__') and len (other) == 2) return (self.x + other [0], self.y + other [1]) def __sub__ (self, other): if isinstance (other, Vector2): return Vector2 (self.x - other.x, self.y - other.y) else: assert (hasattr (other, '__len__') and len (other) == 2) return (self.x - other [0], self.y - other [1]) def __imul__ (self, other): assert (isinstance (other, Number)) self.x *= other self.y *= other return self def __mul__ (self, other): c = Vector2 (self.x, self.y) c *= other return c def __itruediv__ (self, other): assert (isinstance (other, Number)) self.x /= other self.y /= other return self def __truediv__ (self, other): c = Vector2 (self.x, self.y) c /= other return c class BoundingBox: def __init__ (self, minCorner = None, maxCorner = None): if minCorner is not None: self._min = Vector2 (minCorner) else: self._min = Vector2 (float ('inf'), float ('inf')) if maxCorner is not None: self._max = Vector2 (maxCorner) else: self._max = Vector2 (-float ('inf'), -float ('inf')) @staticmethod def FromPoints (points): result = BoundingBox () result.MergePoints (points) return result def Merge (self, other): if isinstance (other, BoundingBox): return self.MergePoints (other) elif isinstance (other, Vector2) or isinstance (other, tuple): return self.MergePoint (other) def MergePoint (self, point): self._min.x = min (point [0], self._min.x) self._min.y = min (point [1], self._min.y) self._max.x = max (point [0], self._max.x) self._max.y = max (point [1], self._max.y) return self def MergePoints (self, points): for p in points: self.MergePoint (p) return self def Expand (self, amount): v = Vector2 (amount, amount) self._min -= v self._max += v def __len__ (self): return 2 def __getitem__ (self, key): if key == 0: return self._min elif key == 1: return self._max def __iter__ (self): return iter([self._min, self._max]) def GetMinimum (self): return self._min def GetMaximum (self): return self._max def GetWidth (self): return self._max.x - self._min.x def GetHeight (self): return self._max.y - self._min.y def GetSize (self): return Vector2 (self.GetWidth (), self.GetHeight ())
14f05e95c5c6e04b2f0b9c7c2c8f71041c168a6a
Salvatore83/txt_to_py
/classes/prog.py
4,027
3.640625
4
import os class Programme(): def __init__(self): try: self.fichier_python = open("fichiers/fichier_python.py", "w") except: quit() self.content = "" self.avant = "\t" self.ligne = "" self.fin_ligne = "" self.nombre_indentation = [1] self.dictionnaire_fonction = {"AFFICHER":"print( "} self.dictionnaire_conditions = {"SINON_SI":"elif ", "DEBUT_SI":"if "} self.dictionnaire_boucle = {"DEBUT_TANT_QUE":"while ", "DEBUT_POUR":"for "} self.dictionnaire_symboles = {'+':"+ ", "-":"- ", "/":"/ ", ",":", ", "<":"<", ">":"> ", "=":"== ", "!=":"!= ", "<=":"<= ", ">=":">= ", "%":"% "} def _ouvrir_fichier(self): try: self.fichier_txt = open("fichiers/fichier_txt.txt", "r") except: quit() def _savoir_si_MAJ(self, chaine): return chaine == chaine.upper() def _creer_liste(self, chaine): self.liste = chaine.split(" ") def _ecrire_fichier_py(self, chaine): self.fichier_python.write(chaine + "\n") def _ecrire_debut_fichier_python(self): self._ecrire_fichier_py("# Ce fichier python a ete ecrit pas un convertisseur .txt to .py_" + "\n") self._ecrire_fichier_py("def main():") self.avant = "\t" def _ecrire_fin_fichier_python(self): self._ecrire_fichier_py("\n" + "if __name__ == '__main__':") self._ecrire_fichier_py("\tmain()") def _fonction_definir(self, mot): if mot in self.dictionnaire_fonction: self.fin_ligne = ")" self.ligne = self.ligne + self.dictionnaire_fonction[mot] elif mot in self.dictionnaire_boucle: pass else: pass def _definir_ligne(self, mot): try: mot = int(mot) except: pass if mot == "<-": self.ligne = self.ligne + "= " elif mot in self.dictionnaire_symboles: self.ligne = self.ligne + self.dictionnaire_symboles[mot] elif type(mot) == int: self.ligne = self.ligne + str(mot) + " " elif "FIN" in mot: self.nombre_indentation.remove(1) i = 0 while i < len(self.nombre_indentation) - 1: self.avant = self.avant + "\t" i += 1 elif mot in self.dictionnaire_conditions: self.nombre_indentation.append(1) self.fin_ligne = ":" self.ligne = self.ligne + self.dictionnaire_conditions[mot] self.avant = self.avant + "\t" elif mot in self.dictionnaire_boucle: self.nombre_indentation.append(1) self.fin_ligne = ":" self.ligne = self.ligne + self.dictionnaire_boucle[mot] self.avant = self.avant + "\t" else: if self._savoir_si_MAJ(mot) == True: self._fonction_definir(mot) else: mot = mot.replace("\n", "") self.ligne = self.ligne + mot + " " def _traitement(self): self._ecrire_debut_fichier_python() self.debut = self.avant if os.stat("fichiers/fichier_txt.txt").st_size != 0: for ligne in self.fichier_txt: self.content = ligne # print(ligne) self._creer_liste(self.content) for mot in self.liste: self._definir_ligne(mot) self._ecrire_fichier_py(self.debut + self.ligne + self.fin_ligne) self.ligne = "" self.fin_ligne = "" self.debut = self.avant print(self.nombre_indentation) else: self._ecrire_fichier_py(self.avant + "pass") self._ecrire_fin_fichier_python() def _fermer_fichiers(self): self.fichier_python.close() self.fichier_txt.close() def _main(self): self._ouvrir_fichier() self._traitement() self._fermer_fichiers()
9dbcec24d2b156aa7f69a8bf1e65ade631e0eea3
sdelpercio/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,202
4.1875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [None] * elements # Your code here while None in merged_arr: if not arrA: popped = arrB.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif not arrB: popped = arrA.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif arrA[0] < arrB[0]: popped = arrA.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif arrB[0] < arrA[0]: popped = arrB.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped else: continue return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # base case if len(arr) == 0 or len(arr) == 1: return arr # recursive case elif len(arr) == 2: return merge([arr[0]], [arr[1]]) else: middle = (len(arr) - 1) // 2 left = arr[:middle] right = arr[middle:] return merge(merge_sort(left), merge_sort(right)) return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): swapped = False while True: swapped = False for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True if swapped == False: break return arr def merge_sort_in_place(arr, l, r): # base case if l < r: middle = l + (r - l) // 2 merge_sort_in_place(arr, l, middle) merge_sort_in_place(arr, middle + 1, r) merge_in_place(arr, l, middle, r) return arr
77d79a10d558f871153a02d7386db26c5a37da9d
patelp456/Project-Euler
/lattice_points.py
571
3.84375
4
#!/usr/bin/env python # ========= Import required modules ===================== # question is not clear # for using system commands import sys # for using os commands like list directeries etc import os # for mathematical functions specially matriices import numpy as np # for general maths from math import * m,n = input("enter comman separated - number of rows and columns in the grid : ") arr = np.zeros((m+1,n+1),dtype=int) arr[0,:] = 1 arr[:,0] = 1 for i in range(1,m+1): for j in range(1,n+1): arr[i,j] = arr[i-1,j] + arr[i,j-1] print arr[m,n]
1bbfdce49e5fd9502618f6261b9ff40b0c91ecdc
patelp456/Project-Euler
/even_fiboncacci.py
484
3.546875
4
#!/usr/bin/env python # ========= Import required modules ===================== # for using system commands import sys # for using os commands like list directeries etc import os # for mathematical functions specially matriices import numpy as np # for general maths from math import * limit = int(sys.argv[1]) a = 1 b = 2 total_even = b # print a , b , while(b < limit): temp = b b = b + a a = temp if b%2 == 0 and b < limit: total_even += b # print b, print total_even
d63827477f880920dbbd73a19befdd5ffb118b02
ITA-ftuyama/GerenciadorCache
/ProjetoCacheL3.py
9,587
3.75
4
# !/usr/bin/env python # -*- coding: utf-8 -*- u"""Simulador de Sistema de Memória.""" # Professor: Paulo André (PA) # Disciplina: CES-25 # Autor: Felipe Tuyama class Cache (object): u"""Classe Cache.""" def __init__(self, size, block_size, associativity): u"""Inicialização da Cache.""" self.size = size self.block_size = block_size self.associativity = associativity self.groups = size / associativity self.cache = [-1] * size self.cacheM = [False] * size self.FIFO = [0] * self.groups self.LRU = [0] * size def hash(self, address): u"""Cálculo do hash do conjunto do bloco de Cache.""" if self.hash_type == 'simple': return address % self.groups elif self.hash_type == 'address': hash = address % (self.block_size * self.size) hash = hash / self.block_size hash = hash / self.associativity return hash elif self.hash_type == 'complex': hash = i = 1 while address > 0: hash = hash + (address % 10) * i + i address = address / 10 i = i + 1 return hash % self.groups elif self.hash_type == 'bigcomplex': hash = i = 1 while address > 0: hash = (hash + (address % 10) * i) * i address = address / 10 i = i + 1 return hash % self.groups def search(self, address): u"""Procura endereço na cache.""" stats.stats[self.stattries] += 1 # Setting the searching range group = self.hash(address) start = group * self.associativity stop = (group + 1) * self.associativity for i in range(start, stop): if address == self.cache[i]: return i return -1 def substitute(self, address, write): u"""Substituição de conjunto de blocos na Cache.""" group = self.hash(address) if self.substitution == 'FIFO': slot = group * self.associativity + self.FIFO[group] self.FIFO[group] = (self.FIFO[group] + 1) % self.associativity elif self.substitution == 'LRU': start = group * self.associativity stop = (group + 1) * self.associativity slot = start for i in range(start, stop): if self.LRU[slot] < self.LRU[i]: slot = i self.LRU[i] = self.LRU[i] + 1 self.LRU[slot] = 0 # Verfica se o bloco está sujo if self.cacheM[slot] and self.write_policy == 'WB': # Penalidade: Tempo extra para gravação stats.stats['memtime'] += max(times) del times[:] # O Bloco deve ser gravado no nível inferior self.lower_level.write(address) # Substituição do bloco sem traumas self.cache[slot] = address self.cacheM[slot] = write def read(self, address): u"""Operação de leitura na Cache.""" # Busca endereço na Cache index = self.search(address) if index > 0: # Realização da leitura na Cache stats.stats[self.stathits] += 1 times.append(self.tag_time + self.access_time) else: # Continua a busca no nível inferior times.append(self.tag_time) self.lower_level.read(address) # Traz o bloco para a Cache self.substitute(address, False) def write(self, address): u"""Operação de escrita na Cache.""" # Busca endereço na Cache index = self.search(address) if index > 0: stats.stats[self.stathits] += 1 # Política de Gravação Write Through if self.write_policy == 'WT': # Realização da escrita na Cache times.append(self.tag_time + self.access_time) self.cacheM[index] = True # Realiza escrita no nível inferior também self.lower_level.write(address) # Política de Gravação Write Back elif self.write_policy == 'WB': # Realização da escrita na Cache times.append(self.tag_time + self.access_time) self.cacheM[index] = True else: # Política de Gravação Write Allocate if self.write_fail_policy == 'WA': # Grava bloco no nível inferior times.append(self.tag_time) self.lower_level.write(address) # Traz o bloco para a Cache self.substitute(address, True) # Política de Gravação Write Not Allocate elif self.write_fail_policy == 'WNA': # Não traz o bloco do nível inferior times.append(self.tag_time) self.lower_level.write(address) class Memory (object): u"""Memória RAM principal.""" def __init__(self): u"""Inicialização da memória.""" def search(self, address): u"""Procura endereço na memória.""" times.append(self.access_time) stats.stats['memhits'] += 1 def read(self, address): u"""Operação de leitura na memória.""" # Busca endereço na memória self.search(address) def write(self, address): u"""Operação de escrita na memória.""" # Busca endereço na memória self.search(address) class Statistics (object): u"""Estatísticas do programa para a sua execução.""" stats = { 'l1hits': 0, 'l2hits': 0, 'l3hits': 0, 'l1tries': 0, 'l2tries': 0, 'l3tries': 0, 'memhits': 0, 'memtime': 0, 'total': 0 } def print_stats(self): u"""Exibe as estatísticas da execução do benchmark.""" print "" print "Estatísticas: " + str(stats.stats) l1_hit_rate = 1.0 * self.stats['l1hits'] / self.stats['total'] l2_hit_rate = 1.0 * self.stats['l2hits'] / self.stats['total'] l3_hit_rate = 1.0 * self.stats['l3hits'] / self.stats['total'] mem_hit_rate = 1.0 * self.stats['memhits'] / self.stats['total'] print "L1 hit rate: " + str(l1_hit_rate) print "L2 hit rate: " + str(l2_hit_rate) print "L3 hit rate: " + str(l3_hit_rate) print "Mem hit rate: " + str(mem_hit_rate) l1_success_rate = 1.0 * self.stats['l1hits'] / self.stats['l1tries'] l2_success_rate = 1.0 * self.stats['l2hits'] / self.stats['l2tries'] l3_success_rate = 1.0 * self.stats['l3hits'] / self.stats['l3tries'] mem_success_rate = 1.0 print "L1 success rate: " + str(l1_success_rate) print "L2 success rate: " + str(l2_success_rate) print "L3 success rate: " + str(l3_success_rate) print "Mem success rate: " + str(mem_success_rate) l1time = (l1.tag_time + l1.access_time) l2time = (l2.tag_time + l2.access_time) l3time = (l3.tag_time + l3.access_time) effective_time = ( l1_success_rate * l1time + (1.0 - l1_success_rate) * ( l2_success_rate * l2time + (1.0 - l2_success_rate) * ( l3_success_rate * l3time + (1.0 - l3_success_rate) * ( mem.access_time)))) print "Effective Time: " + str(effective_time) print "Mem Total Time: " + str(self.stats['memtime'] / 1000.0) def main(): u"""Rotina main do Simulador de Memória.""" print "*************************************" print "* *" print "* Simulador de Sistema de Memória *" print "* *" print "*************************************" total = 0 # Para cada linha do arquivo de entrada: with open('../gcc.trace') as infile: for line in infile: # Barra de progresso if total % 50000 == 0: print "#", total += 1 # Interpreta endereço e operação address = int(line[:8], 16) operation = line[9] # Realiza operação selecionada del times[:] if operation == 'R': l1.read(address) elif operation == 'W': l1.write(address) # Operações realizads em paralelo stats.stats['memtime'] += max(times) # Imprime estatísticas stats.stats['total'] = total stats.print_stats() u"""Escopo global para chamada da main.""" # Auxiliar times vector times = [] # Creating Statistics stats = Statistics() # Creating Memory mem = Memory() mem.access_time = 60 # Creating Cache L3 l3 = Cache(98304, 512, 32) l3.write_policy = 'WB' l3.write_fail_policy = 'WNA' l3.substitution = 'FIFO' l3.hash_type = 'simple' l3.stathits = 'l3hits' l3.stattries = 'l3tries' l3.access_time = 10 l3.tag_time = 5 l3.lower_level = mem # Creating Cache L2 l2 = Cache(65536, 512, 16) l2.write_policy = 'WB' l2.write_fail_policy = 'WA' l2.substitution = 'FIFO' l2.hash_type = 'bigcomplex' l2.stathits = 'l2hits' l2.stattries = 'l2tries' l2.access_time = 4 l2.tag_time = 2 l2.lower_level = l3 # Creating Cache L1 l1 = Cache(1024, 512, 8) l1.write_policy = 'WT' l1.write_fail_policy = 'WA' l1.substitution = 'FIFO' l1.hash_type = 'complex' l1.stathits = 'l1hits' l1.stattries = 'l1tries' l1.access_time = 2 l1.tag_time = 1 l1.lower_level = l2 main()
52cf0e8469ba0dbaecfd617bdbcbf00947addb24
Techsrijan/diplomaiieit
/vendingmachine.py
272
3.953125
4
num=int(input("how many toffe u want")) av=10 i=1 while i<=num: if i<=av: print("Plese collect toffee=",i) else: print("out of stock") break i=i+1 else: # this else will run when loop properly runs print("Thanks Please Visit again")
dfdce15d468daed6d81882ff74db866803720d4f
harshit-dot/python-programs
/array1.py
125
3.578125
4
string=input() substring=input() s=string.strip() sb=substring.strip() b=s.find(sb) print(b) c=s[b:3] k=s.remove(c) print(k)
2c9093f3321d2ab4226bc1bd44ffe47046261f10
harshit-dot/python-programs
/happy.py
448
3.984375
4
class rectangle: def __init__(self,l,b,r): self.length=l self.bredth=b self.radius=r def area_rectangle(self): a=self.length*self.bredth print(a) def area_circle(self): p=self.radius*3.14 print(p) a=int(input('enter the value of length')) b=int(input('enter the value of breadth')) c=int(input('enter the value of radius')) p1=rectangle(a,b,c) p1.area_rectangle()
efb0bd28717c73a45d63a9de5646f1832f0579b7
JuneTse/MyCoding
/2/数组中重复的数字.py
1,031
3.78125
4
# -*- coding: utf-8 -*- """ 数组中重复的数字 1. 题目 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 2. 思路 (1) 使用辅助数组存放每个数字的次数: C[i]存放数组i的次数 """ class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # write code here C=[0]*len(numbers) for d in numbers: C[d]+=1 for i in range(len(numbers)): if C[i]>1: duplication[0]=i return True return False a=[2,1,3,0,4] s=Solution() s.duplicate(a,[-1])
94139a93fc64d104d325b54be4b881bc045fc49c
JuneTse/MyCoding
/1.排序/计数排序.py
868
3.578125
4
# -*- coding: utf-8 -*- """ 计数排序 1. 前提条件: 假设数组A中的元素都是0到k之间的数,k=O(n) 2. 思想: * 统计数组A中小于元素A[i]的个数,这样就可以得到A[i]排序后的位置 3. 过程 * 统计元素A[i]出现的个数C[A[i]] * 累加得到小于等于A[i]的元素个数:C[A[i]]=C[A[i]]+C[A[i]-1] """ def count_sort(A,k): l=len(A) B=[-1]*l C=[0 for i in range(k)] # 1. 统计A[i]的元素出现的次数 for a in A: C[a]+=1 # 2. 累加得到小于等于A[i]的元素个数 for i in range(1,k): C[i]=C[i]+C[i-1] # 3. 遍历A,输出有序数组到B for a in A: #a的位置为C[a] B[C[a]-1]=a #a的位置减1 C[a]-=1 return B A=[1,2,5,9,6,4,3,2,8,2,1,7,6,4] B=count_sort(A,10) print(B)
d4d05a4ef6d267e776e1fa169b49c79830ab9772
JuneTse/MyCoding
/2/字符串排序.py
980
3.734375
4
# -*- coding: utf-8 -*- """ 字符串排序 1. 题目 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 2. 思路 (1)递归: 分解成子问题求解 * 如果len(s)==1: 输出 * 否则,分解为s[i], s[0:i]+s[i+1:n] """ class Solution: def Permutation(self, ss): if ss is None: return None res=[] # write code here def printStr(pre,s): if len(s)==1: #print(pre+s[0]) res.append(pre+s[0]) s=sorted(s) for i in range(len(s)): if i>0 and s[i]==s[i-1]: continue printStr(pre+s[i],s[0:i]+s[i+1:]) printStr('',ss) return res ss="aab" solu=Solution() res=solu.Permutation(ss) print(res)
b204be17032ba6122a4d3fecdab5be80a5528a50
Sonnaly/Exercicio-Revis-o-
/questão 8.py
1,183
3.9375
4
notas = 0 lista = [] lista_reversa = [] while True: notaX= int(input("Digite uma nota: ")) if notaX == -1: break notas += 1 lista.append(notaX) lista_reversa = lista[::-1] print("") print(" A quantidade valores lidos foi: %d\n"%(notas)) print(" Os valores na ordem que foram informados:") for i in range(len(lista)): print(lista[i], end = " ") print("") print("") print(" Os valores na ordem inversa que foram informados um abaixo do outro:") for j in range(len(lista_reversa)): print(lista_reversa[j], end = " ",) print("") print("") somaVetor = 0 for k in range(len(lista)): somaVetor += lista[k] print(" A soma dos valores dos elementos do vetor é: %d\n" %(somaVetor)) print(" A media dos valores do elementos do vetor é: %d\n"%(somaVetor/len(lista))) acimaMedia = 0 for l in range(len(lista)): if lista[l] > somaVetor/len(lista): acimaMedia +=1 print(" A quantidade de valores acima da media é: %d\n"%(acimaMedia)) abaixoSete = 0 for m in range(len(lista)): if lista[m] < 7: abaixoSete+=1 print(" A quantidade de valores abaixo de sete é: %d\n"%(abaixoSete)) print(" FIM!")
eb4b625458c39c548b8ff405192a9fc952f5b0f3
cspoon/DataStructures-in-Python
/Sort/MergeSort.py
2,177
3.75
4
import DoublyLinkedList import Vector class MergeSort(object): def listMergeSort(self, list, p, n): "sort n elements at the beginning of node p" if n < 2: return p mid = n / 2 q = list.getNodeAfterNIndex(p, mid) p = self.listMergeSort(list, p, mid) q = self.listMergeSort(list, q, n - mid) return self.listMerge(list, p, mid, q, n-mid) def listMerge(self, list, p, n, q, m): pp = p.pred while m > 0: if n > 0 and p.data <= q.data: p = p.succ if p == q: break n -= 1 else: q = q.succ list.insertNodeBeforeP(p, list.remove(q.pred)) m -= 1 return pp.succ def arrayMergeSort(self, arr, lo, hi): if hi - lo < 2: return mid = (lo + hi) / 2 self.arrayMergeSort(arr, lo, mid) self.arrayMergeSort(arr, mid, hi) self.arrayMerge(arr, lo, mid, hi) def arrayMerge(self, arr, lo, mid, hi): 'merge [lo, mi) and [mi, hi)' b = arr[lo:mid] lb, lc = mid - lo, hi - mid pb = pa = pc = 0 while pb < lb or pc < lc: if pb < lb and (pc >= lc or b[pb] <= arr[mid+pc]): arr[lo+pa] = b[pb] pb += 1 elif pc < lc and (pb >= lb or arr[mid+pc] < b[pb]): arr[lo+pa] = arr[mid+pc] pc += 1 pa += 1 if __name__ == '__main__': a = DoublyLinkedList.DoublyLinkedList() ms = MergeSort() ''' a.insertAsLast(4) a.insertAsLast(3) a.insertAsLast(2) a.insertAsLast(1) a.insertAsLast(6) a.insertAsLast(9) a.insertAsLast(5) a.printAll() ms.listMergeSort(a, a._header.succ, a.__len__()) a.printAll() print '*' * 20 ''' b = Vector.Vector() b.append(1) b.append(4) b.append(3) b.append(9) b.append(11) b.append(6) b.append(2) b.printAll() ms.arrayMergeSort(b, 0,b.__len__()) b.printAll()
3469a2c651f84505c0af4cf3734eec0e77f308ff
cspoon/DataStructures-in-Python
/Tree/BinTreeTest.py
1,402
3.8125
4
import BinTree import Utils def randomBinTree(bt, x, h): if h <= 0: return if Utils.randomRange(h): randomBinTree(bt, bt.insertAsRC(x, Utils.randomRange(100)), h - 1) if Utils.randomRange(h): randomBinTree(bt, bt.insertAsLC(x, Utils.randomRange(100)), h - 1) def randomBinNode(binNode): if (not binNode.hasLC()) and (not binNode.hasRC()): return binNode elif not binNode.hasLC(): return Utils.randomRange(1) and randomBinNode(binNode.RC) or binNode elif not binNode.hasRC(): return Utils.randomRange(1) and randomBinNode(binNode.LC) or binNode else: return Utils.randomRange(1) and randomBinNode(binNode.LC) or randomBinNode(binNode.RC) def randomCompleteBinTree(bt, x, h, isOrder): if h <= 0: return randomCompleteBinTree(bt, bt.insertAsLC(x, isOrder and x.data*2+1 or Utils.randomRange(100)), h - 1, isOrder) randomCompleteBinTree(bt, bt.insertAsRC(x, isOrder and x.data*2+2 or Utils.randomRange(100)), h - 1, isOrder) if __name__ == '__main__': #h = input("please input the height of the tree:") bt = BinTree.BinTree() bt.insertAsRoot(0) randomCompleteBinTree(bt, bt.root(), 3, True) bt.printAll() ''' node = randomBinNode(bt.root()) print 'node.data = '+ str(node.data) bt.remove(node) bt.printAll() '''
bb0b64472fbe2b97b79b007368eeec751f87b7d3
bmart7/School-Projects
/CSE 331/Project2/Recursion.py
5,133
4.15625
4
""" PROJECT 2 - Recursion Name: Brian Martin PID: A56350183 """ from Project2.LinkedNode import LinkedNode def insert(value, node=None): """ Adds a node with value 'value' in ascending order to a list with head 'node' or creates a new list of length 1 :param value: value to add to list :param node: head node of a list :return: head node of the list with inserted value """ if node is None: temp = LinkedNode(value, None) return temp if node.value < value: if node.next_node is None or node.next_node.value >= value: temp = LinkedNode(value, node.next_node) node.next_node = temp return node if node.next_node.value < value: insert(value, node.next_node) return node else: temp = LinkedNode(value, node) return temp def string(node): """ Returns a string representation of the list with head 'node' :param node: head node of a list :return: string representation of the list with head 'node' """ if node is None: return '' if node.next_node is None: return '%s' % node.value else: return '%s, ' % node.value + string(node.next_node) def reversed_string(node): """ Returns a string representation of the list with head 'node', in reverse order :param node: head node of a list :return: string representation of the list with head 'node', in reverse order """ if node is None: return '' if node.next_node is not None: return reversed_string(node.next_node) + ', %s' % node.value else: return '%s' % node.value def remove(value, node): """ Removes first node with value 'value' from a list with head 'node' :param value: value to remove from list :param node: head node of a list :return: head node of the list with removed value """ if node is None: return node if node.value == value: temp = node.next_node node.next_node = None return temp elif node.next_node is not None: if node.next_node.value == value: node.next_node = node.next_node.next_node return node else: remove(value, node.next_node) return node else: return node def remove_all(value, node): """ Removes all nodes with value 'value' from a list with head 'node' :param value: value to remove from list :param node: head node of a list :return: head node of the list with removed values """ if node is None: return node if node.next_node is not None: if node.value == value: temp = node.next_node node.next_node = None return remove_all(value, temp) if node.next_node.value == value: if node.next_node.next_node is not None: temp = node.next_node.next_node node.next_node = None node.next_node = temp remove_all(value, node) return node else: node.next_node = None return node remove_all(value, node.next_node) return node else: if node.value == value: return None return node def search(value, node): """ Searches for first node with value 'value' from a list with head 'node' :param value: value to find in list :param node: head node of a list :return: boolean value if value is present in list """ if node is None: return False if node.value == value: return True elif node.next_node is None: return False else: return search(value, node.next_node) def length(node): """ Calculates and returns length a list with head 'node' :param node: head node of a list :return: length of list with head 'node' """ if node is None: return 0 if node.next_node is None: return 1 else: return 1 + length(node.next_node) def sum_all(node): """ Calculates and returns sum of all node values in a list with head 'node' :param node: head node of a list :return: sum of all node values in a list with head 'node' """ if node is None: return 0 if node.next_node is None: return node.value else: return node.value + sum_all(node.next_node) def count(value, node): """ Calculates and returns amount of nodes with value 'value' from a list with head 'node' :param value: value to find in list :param node: head node of a list :return: amount of nodes with value 'value' from a list with head 'node' """ if node is None: return 0 if node.next_node is not None: if node.value == value: return 1 + count(value, node.next_node) else: return count(value, node.next_node) else: if node.value == value: return 1 else: return 0
605071feb62fca3eda314d4fa1b145999a40ffe9
softwarelikeyou/CS313E
/Assignment 4 - htmlChecker/htmlCheckerCourtney.py
2,701
3.75
4
import sys class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) #function goes through file returns a string for each tag def getTag(file): tag = '' recording = False while True: char = file.read(1) if not char: return '' if char == '<': recording = True continue if (char == '>' or char == ' ') and len(tag) != 0: return tag if recording == True: tag += char continue def main(): #intialize lists of exceptions, valid tags and tags EXCEPTIONS = ['br', 'meta', 'hr'] VALIDTAGS = [] tags = [] #open file html = open("UNTITLED.txt", "r") #create a list of get tag while True: tag = getTag(html) if len(tag) == 0: break tags.append(tag) print() #print tags print(tags) print() #declare stack m = Stack() #go through stack to find matches for tag in tags: if tag[0] == '/': if tag[1:] == m.peek(): print('Tag ', m.pop(), ' matches top of stack: stack is now ', m.items) else: print('Error: tag is ', tag[1:], ' but top of stack is ', m.pop()) #change why does it keep going through program needs to end sys.exit() else: if tag in EXCEPTIONS: print('Tag ', tag, ' does not need to match: stack is still ', m.items) #change add exceptions to validtags if tag not in VALIDTAGS: VALIDTAGS.append(tag) print('Adding', tag, ' to list of valid tags') continue m.push(tag) if tag not in VALIDTAGS and tag[0] != '/': VALIDTAGS.append(tag) print('Adding', tag, ' to list of valid tags') print('Tag ', tag, ' pushed: stack is now ', m.items) print() #end processesing if m.isEmpty(): print('Processing complete. No mismatches found.') else: print('Processing complete. Unmatched tags remain on stack: ', m.items) print() EXCEPTIONS.sort() VALIDTAGS.sort() #final contents of sorted exceptions and validtags print('Exception tags are: ', EXCEPTIONS) print() print('Valid tags are: ', VALIDTAGS) main()
04b704d9811a7d1c9db91db0cbff7d11adfa8f13
zbck/Titanic
/Feature_selection.py
2,950
3.84375
4
import csv import numpy as np from pathlib import Path class Feature_selection: '''This class is used to select only some features of the samples written in a csv file. ''' EXTENTION = '.csv' TITANIC_FEATURES = ['id', 'pclass', 'survived', 'name', 'sex', 'age', 'sibsp', 'parch', 'ticket', 'fare', 'cabin', 'embarked', 'boat', 'body', 'home.dest', 'has_cabin_number'] # Array with clean features NEW_ARRAY = [] def __init__(self, filepath, features_wanted): self.FILEPATH = filepath if self._check_file(): self.FEATURES = features_wanted self._open_read_file() def _check_file(self): '''Check if the file is a .csv ''' if Path(self.FILEPATH).suffix == self.EXTENTION: return True else: return False def _open_read_file(self): '''Open and read csv files the spamreader will be used to read the rows of the csv file ''' self.FILE = open(self.FILEPATH,"r") self.SPAMREADER = csv.reader(self.FILE) def _feature_identification(self): ''' In order to access easily to which column corespond what create two dictionnaies: (key = feature label, value = column index) - dict_old : Old array index of the selected features - dict_new : New array index of the selected features ''' columns_index_old = [(feature, index) for index, feature in enumerate(self.TITANIC_FEATURES) if feature in self.FEATURES] self.dict_old = dict(columns_index_old) columns_index_new = [(feature, index) for index, feature in enumerate(self.dict_old)] self.dict_new = dict(columns_index_new) def feature_select(self): '''Keep in a numpy array only the selected columns ''' # Take take the column number of the given # features labeles self._feature_identification() for row in self.SPAMREADER: new_row = [] for index in self.dict_old.values(): new_row.append(np.array(row[index])) self.NEW_ARRAY.append(np.array(new_row)) del self.NEW_ARRAY[-1] # Be careful row containt NA either #put a number the mean of the other value # or del self.NEW_ARRAY[1226] del self.NEW_ARRAY[0] def sex2int(self): ''' Change to male = 0 and female = 1 ''' for i in range(len(self.NEW_ARRAY)): if self.NEW_ARRAY[i][self.dict_new['sex']] == 'male': self.NEW_ARRAY[i][self.dict_new['sex']] = 0 else: self.NEW_ARRAY[i][self.dict_new['sex']] = 1 def array2file(self, output_file): ''' Write an array into a csv file ''' np.save(output_file, np.reshape(np.array(self.NEW_ARRAY), (-1,len(self.FEATURES)))) if __name__=='__main__': filepath = 'Cleaning-Titanic-Data/titanic_clean.csv' output_file = 'data/train_data_clean' #output_file = 'data/train_label_clean' features_wanted = ['pclass', 'sex', 'age', 'sibsp', 'fare'] #features_wanted = ['survived'] param_selec = Feature_selection(filepath, features_wanted) param_selec.feature_select() param_selec.sex2int() param_selec.array2file(output_file)
0684f210b036b64b9821110bdb976908deeca8ca
Guilherme758/Python
/Estrutura Básica/Exercício i.py
374
4.375
4
# Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. # C = 5 * ((F-32) / 9). fahrenheit = float(input("Informe a temperatura em graus fahrenheit: ")) celsius = 5 * (fahrenheit-32)/9 if celsius.is_integer() == True: celsius = int(celsius) print("A temperatura em celsius é:", f'{celsius}ºC')
d4393db248c28cafa20467c616da8428496550fb
Guilherme758/Python
/Estrutura Básica/Exercício j.py
332
4.25
4
# Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. celsius = float(input('Passe a temperatura em celsius: ')) fahrenheit = 9*(celsius/5)+32 if fahrenheit.is_integer() == True: fahrenheit = int(fahrenheit) print("A temperatura em fahrenheit é:", f'{fahrenheit}ºF')
2c3d68c6da066692baa0ed2843ae62abf1492f54
harmsm/linux-utilities
/split_dir.py
1,412
3.65625
4
#!/usr/bin/env python """ split_dir.py Takes a directory and splits it into some number of smaller directories. """ __usage__ = "split_dir.py dir_to_split num_to_split_into" __author__ = "Michael J. Harms" __date__ = "070622" import sys, os, shutil def splitDir(dir,split): """ Split "dir" into "split" new directories. """ # Contents of dir dir_list = os.listdir(dir) dir_list.sort() # Split interval l = len(dir_list) interval = l/split # Split dir for i in range(split - 1): new_dir = "%s_%i" % (dir,i) os.mkdir(new_dir) file_list = dir_list[i*interval:(i+1)*interval] for f in file_list: shutil.copy(os.path.join(dir,f),new_dir) # Grab last part of directory (even if not divisible by split) new_dir = "%s_%i" % (dir,i+1) os.mkdir(new_dir) file_list = dir_list[(i+1)*interval:] for f in file_list: shutil.copy(os.path.join(dir,f),new_dir) def main(): """ To be called if user runs program from command line. """ try: dir = sys.argv[1].strip(os.sep) split = int(sys.argv[2]) except IndexError: print __usage__ sys.exit() if os.path.isdir(dir): splitDir(dir,split) else: err = "%s is not a directory" % dir raise IOError(err) # If called from the command line if __name__ == "__main__": main()
e0f808f1c93b832eeb29f9133a86ce99dbbe678d
NuradinI/simpleCalculator
/calculator.py
2,097
4.40625
4
#since the code is being read from top to bottom you must import at the top import addition import subtraction import multiplication import division # i print these so that the user can see what math operation they will go with print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") #this is a while loop, different from the for loop in that it will not run 'x' amount of times, #a while loop runs as a set of code if the condition defined is true # here i create the while loop by writing while and then true so that the code statements below #only execute when true, i add the : to start it up while True: #here i define the variable Userchoice, then i put the input function which allows for user input # i give the user a choice to enter values UserChoice = input("Choose (1,2,3,4): ") #if the users choice is 1 2 3 4 run this code if UserChoice in ('1', '2', '3', '4'): #the code that is run is a input in which the first number is a variable that stores the users input num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) #if the userschoice is equal to one, print the value of num1 concatonate with a string that shows #that the content was added and concatonate with a = and then run the function that acc does the math #that is now called back so the value of x, y is now the variables num1 and num2 if UserChoice == '1': print(num1, "+", num2, "=", addition.addNum(num1, num2)) elif UserChoice == '2': print(num1, "-", num2, "=", subtraction.subtractNum(num1, num2)) elif UserChoice == '3': print(num1, "*", num2, "=", multiplication.multiplyNum(num1, num2)) elif UserChoice == '4': print(num1, "/", num2, "=", division.divideNum(num1, num2)) #we use the break to stop the code, otherwise the if the conditions remain true the code #will run up again, its basically a period i think break else: #if they dont chose any print invalid input print("pick a num 1 - 4 silly ")
b2377860b50e58e29c4dabde578ba8981e993c04
MandySuperTT/Algorithm-Practice-Python
/二分法.py
10,525
4.15625
4
‘’‘ Last Position of Target Find the last position of a target number in a sorted array. Return -1 if target does not exist. ‘’‘ class Solution: """ @param nums: An integer array sorted in ascending order @param target: An integer @return: An integer """ ''' def lastPosition(self, nums, target): # write your code here if len(nums) == 0: return -1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = (start + end) // 2 if nums[mid] > target: end = mid else: start = mid if nums[end] == target: return end if nums[start] == target: return start return -1 ''' def lastPosition(self, A, target): # Write your code here if len(A) == 0 or A == None: return -1 start = 0 end = len(A) - 1 if target < A[start] or target > A[end]: return -1 while start + 1 < end: mid = start + (end - start) / 2 if A[mid] > target: end = mid else: start = mid if target == A[end]: return end elif target == A[start]: return start else: return -1 ‘’‘ 585. Maximum Number in Mountain Sequence Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top. ‘’‘ class Solution: """ @param nums: a mountain sequence which increase firstly and then decrease @return: then mountain top """ def mountainSequence(self, nums): # write your code here start,end = 0,len(nums)-1 while start + 1 < end: mid = (end+start) // 2 if nums[start] < nums[mid]: if nums[mid-1] < nums[mid]: start = mid else: end = mid else: end = mid return max(nums[start],nums[end]) ’‘’ 460. Find K Closest Elements Given a target number, a non-negative integer k and an integer array A sorted in ascending order, find the k closest numbers to target in A, sorted in ascending order by the difference between the number and target. Otherwise, sorted in ascending order by number if the difference is same. ‘’‘ class Solution: """ @param A: an integer array @param target: An integer @param k: An integer @return: an integer array """ def kClosestNumbers(self, A, target, k): # write your code here if len(A) == 0 or k > len(A): return -1 start,end = 0, len(A)-1 while start + 1 < end: mid = start + (end-start)//2 if A[mid] < target: start = mid else: end = mid if A[end] < target: left= end if A[start] < target: left= start else: left = -1 right = left + 1 r=[] for i in range(k): if left< 0: #return A[:k-1] r.append(A[right]) right += 1 elif right >= len(A): #return A[-k:-1] r.append(A[left]) left -= 1 elif A[right]-target < target-A[left]: r.append(A[right]) right += 1 else: r.append(A[left]) left -= 1 return r ‘’‘ 447. Search in a Big Sorted Array Given a big sorted array with positive integers sorted by ascending order. The array is so big so that you can not get the length of the whole array directly, and you can only access the kth number by ArrayReader.get(k) (or ArrayReader->get(k) for C++). Find the first index of a target number. Your algorithm should be in O(log k), where k is the first index of the target number. Return -1, if the number doesn't exist in the array. ‘’‘ class Solution: """ @param: reader: An instance of ArrayReader. @param: target: An integer @return: An integer which is the first index of target. """ def searchBigSortedArray(self, reader, target): # write your code here index = 0 while reader.get(index) < target: index = index * 2 + 1 start, end = 0, index while start + 1 < end: mid = start + (end-start) // 2 if reader.get(mid) < target: start = mid else: end = mid if reader.get(start) == target: return start elif reader.get(end) == target: return end else: return -1 ‘’‘ 428. Pow(x, n) Implement pow(x, n). ‘’‘ class Solution: """ @param x: the base number @param n: the power number @return: the result """ def myPow(self, x, n): # write your code here if x == 0: return 0 if n == 0: return 1 if n < 0: x = 1 / x n = -n if n == 1: return x if n % 2 == 0: temp = self.myPow(x, n // 2) return temp * temp else: temp = self.myPow(x, n // 2) return temp * temp * x ‘’‘ 159. Find Minimum in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. ’‘’ class Solution: """ @param nums: a rotated sorted array @return: the minimum number in the array """ def findMin(self, nums): # write your code here start,end = 0, len(nums)-1 while start + 1 < end: mid = (end+start) // 2 if nums[start] < nums[mid]: start = mid else: end = mid if (nums[0] < nums[start]) and (nums[0] < nums[end]): return nums[0] elif nums[start] < nums[end]: return nums[start] else: return nums[end] ‘’‘ 140. Fast Power Calculate the an % b where a, b and n are all 32bit positive integers. ’‘’ class Solution: """ @param a: A 32bit integer @param b: A 32bit integer @param n: A 32bit integer @return: An integer """ def fastPower(self, a, b, n): # write your code here ''' ans=1 # a = a % b while n > 0: if n % 2 == 1: ans = ans * a % b a = a*a % b n = n/2 return ans % b ans = 1 while n > 0: if n % 2==1: ans = ans * a % b a = a * a % b n = n / 2 return ans % b ''' # write your code here if n == 0: return 1 % b if n % 2 == 0: tmp = self.fastPower(a, b, n / 2) return tmp * tmp % b else: tmp = self.fastPower(a, b, n / 2) return tmp * tmp * a % b ‘’‘ 75. Find Peak Element There is an integer array which has the following features: The numbers in adjacent positions are different. A[0] < A[1] && A[A.length - 2] > A[A.length - 1]. We define a position P is a peak if: A[P] > A[P-1] && A[P] > A[P+1] Find a peak element in this array. Return the index of the peak. ‘’‘ class Solution: """ @param A: An integers array. @return: return any of peek positions. """ def findPeak(self, A): # write your code here start,end = 0,len(A)-1 while start + 1 < end: mid = (start+end)//2 if A[mid+1] < A[mid]: end = mid else: start = mid if A[start] > A[end]: return start return end ‘’‘ 74. First Bad Version The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version. You can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code's annotation part. ‘’‘ #class SVNRepo: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use .SVNRepo.isBadVersion(10) to check whether version 10 is a # bad version. class Solution: """ @param n: An integer @return: An integer which is the first bad version. """ def findFirstBadVersion(self, n): # write your code here start,end = 1,n while start + 1 < end: mid = start + (end-start)//2 if SVNRepo.isBadVersion(mid): end = mid else: start = mid if SVNRepo.isBadVersion(start): return start return end ’‘’ 62. Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. ‘’‘ class Solution: """ @param A: an integer rotated sorted array @param target: an integer to be searched @return: an integer """ def search(self, A, target): # write your code here start,end = 0,len(A)-1 if len(A) == 0: return -1 while start+1<end: mid = (end+start)//2 if A[start] < A[mid]: if A[mid] > target and A[start] <= target: end = mid else: start = mid else: if (A[mid] > target) or (A[start]<target): end = mid else: start = mid if A[start] == target: return start elif A[end] == target: return end else: return -1
1944db6e10434cac6bea84dbb6a93c1031f4d43f
zhoujunjun-apple/Dynamic-Programming-for-Coding-Interviews
/chapter-01/Q-1.1/py3/main.py
126
3.5625
4
def factorialFunc(n: int)->int: if n<=0: return 0 if n==1: return 1 return n * factorialFunc(n-1)
50fb9cc69f8dacdb53071aac402fc0e806843bfe
coder-zhanglei/zhanglei.github.io
/python/test/love.py
2,131
3.625
4
from tkinter import * from tkinter import messagebox def closeWindow(): messagebox.showinfo(title="警告",message = "不许关闭,好好回答") # messagebox.showerror(title="警告",message = "") return def closeAllWindow(): window.destroy() def Love(): love = Toplevel(window) love.geometry("300x100+610+260") love.title("好巧,我也是") label = Label(love,text = "好巧我也是", font =( "楷体", 25 )) label.pack() btn = Button(love,text= "确定", width = 10, height = 2, command = closeAllWindow) btn.pack() love.protocol("WM_DELETE_WINDOW", closelove) def closelove(): messagebox.showinfo(title="爱你", message="再考虑一下嘛") def closenolove(): nolove() def nolove(): noLove = Toplevel(window) noLove.geometry("300x100") noLove.title("考虑一下嘛") label = Label(noLove, text="考虑一下嘛", font=("楷体", 25)) label.pack() btn = Button(noLove, text="好的", width=10, height=2, command=noLove.destroy) btn.pack() noLove.protocol("WM_DELETE_WINDOW", closenolove) #创建窗口 window = Tk() #设置窗口的标题 window.title("你喜欢我???") #设置窗口的大小 window.geometry("380x420+590+230") #窗口的位置 #window.geometry("+590+230") window.protocol("WM_DELETE_WINDOW", closeWindow) #标签控件 labell = Label(window,text = "hey,小姐姐!",font = ('微软雅黑',15),fg = 'red') #定位 grid网格式的布局 pack place labell.grid() label2 = Label(window,text = "喜欢我??", font = ('微软雅黑',30),fg = 'green') #sticky 对齐方式 ,N S W E label2.grid(row = 1,column = 1,sticky = E) #显示图片 photo = PhotoImage(file = './cc.png') imageLable = Label(window,image = photo) #columnspan 组件跨越的列数 imageLable.grid(row = 2,columnspan = 2) #按钮 btn1= Button(window,text = "喜欢",width = 15, height = 2,command = Love) btn1.grid(row = 3,column = 0,sticky = W) btn2= Button(window,text = "不喜欢",command = nolove) btn2.grid(row = 3,column = 1,sticky = E) #显示窗口 消息循环 window.mainloop()
b675a618e289c5d995e0368985788b6b2e636ff8
Raul-Guerra/Proyecto-Final
/Proyecto Final.py
3,877
3.90625
4
#Esta biblioteca sirve para que no se despliegue todo de golpe import time #Para que no se despliegue todo de golpe def nombrecliente(nombre): print("¡Hola"+" "+"%s!"%nombre) #Time es para que haya un tiempo de despliegue cuando se ejecuta el programa time.sleep(2) print("Este es un programa te ayudará a tener un menú de calidad") time.sleep(3) #cuandoescribe cualquier bebida del menú, sele restará lo que se pague def cambio(u1,a): #la condicion "(A<12)" porque el agua es bebida más barata y cuesta 12 pesos if (a<12): print("Lo lamentamos, no te alcanza para nada") else: #el acumulador tiene la función de manter la suma de los gastos del usuario acum=0 #se establece un limite al cual el acumulado no puede sobrepasar limite1=a-12 ref = 20 cer = 25 agua = 12 bebida=0 while acum <= limite1: if u1 == "refresco" or u1 == "Refresco" : acum=acum+ref bebida=bebida+1 #elif hace que si no se cumple la primera condición, se cumplirá la siguiente elif u1 == "cerveza" or u1 == "Cerveza" : acum=acum+cer bebida=bebida+1 elif u1 == "agua" or u1 == "Agua" : acum=acum+agua bebida=bebida+1 print("lleva acumulados:", acum, "pesos") sino=str(input("¿Quiere otra bebida? coloque (sí) o (no)")) if sino == "Sí" or sino == "Si" or sino == "sí" or sino == "si": u1= str(input("Escriba la otra bebida que guste.")) else: break cambio=a-acum print("El precio total de su compra fue: ",bebida, acum, " pesos") print("Su cambio total es de: ",cambio," pesos") def main(): print("Bienvenido") nombre = input("Escribe tu nombre: ") nombrecliente(nombre) while True: print("Elige tu bebida (nombre)") #Este es el menú que se le muestra al cliente print("Menú:") print("1. refreso 20 pesos") print("2. cerveza 25 pesos") print("3. agua 12 pesos") #El usuario nos escribirá la bebida para poder obtener su precio u1 = input() # se calcula el cambio que se le devolverá si es el caso print("Inserte la cantidad con la que usted va a pagar") a = int(input()) cambio(u1,a) #colocará la opción de repetir con el while true y con conti conti=str(input("¿Volver a realizar otra compra?, coloque (sí) (no)?")) if conti == "No" or conti == "no" or conti == "N" or conti == "n": print("Gracias por su tiempo") break main() #Se vuelve a usar la nueva biblioteca digital time.sleep(2) print ("Escribe las bebidas que deseas que salgan proximamente:") #Esta lista funciona para guardar los datos ingresados por el usuario lista= [] tamano=int(input("coloca el número de bebidas sugeridas")) for i in range(0,tamano): nobebs = str(input("Escribe el nombre de las bebidas: ")) lista.insert(i, nobebs) print("Nos daría mucho tener en el menú estas bebidas: ", lista) print ("Vuelva pronto") print ("Si resuelves las adivinanzas, en la siguiente visita tienes descuento") print ("Fui por él y nunca lo traje, ¿Qué es?") print ("Nazco sin padre y al morir nace mi madre, ¿Quién soy?") #La matriz sirve para guardar información de varias listas m=[["A","Despensa","Batman"],["B","Cigarros","Gallina"],["C","Camino","Nieve"]] print("Opciones:") for x in range(0,len(m)): #X es un contador que nos sirve para la secuencia de las listas print(m[x][0]," ) " ,m[x][1], " y " ,m[x][2]) r=str(input("\nColoca la letra de la opción correcta (MAYUSCULA)")) if r == "C" or r== "c": print("Respuesta correcta") else: print("Respuesta incorrecta, la respuesta correcta era la opción C")
bae8df0874fd25083af53ea8d5c0bcdd0fca53c8
DeepakSunwal/Daily-Interview-Pro
/solutions/find_index_at_element.py
423
3.78125
4
def find_index(numbers, low, high): if low >= high: return None mid = (low + high) // 2 if numbers[mid] == mid: return mid if numbers[mid] < mid: return find_index(numbers, mid + 1, high) return find_index(numbers, low, mid) def main(): assert find_index([-5, 1, 3, 4, 5], 0, 5) == 1 assert not find_index([1, 2, 3, 4, 5], 0, 5) if __name__ == '__main__': main()