blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b3edf8d7d5c833af3e529c30fbe679a111609346 | shahprashant030/Student-Library-Management | /Student Library Management/insertstudent.py | 1,409 | 3.640625 | 4 | import pymongo
from tkinter import *
def i_student_function():
root = Tk()
root.title("Insert Into Student")
root.geometry("700x300")
def insertstudent():
client = pymongo.MongoClient("mongodb://localhost:27017")
db = client.student_lib_DB
collection = db.student
label = Label(root, text="\nInserted data successfully\n")
label.grid(row=5,column=3)
studentId = e1.get()
studentName = e2.get()
studentAge = e3.get()
studentCountry = e4.get()
db.student.insert_one(
{
"std_id":studentId,
"name":studentName,
"age":studentAge,
"country":studentCountry
})
l1= Label(root, text="Student Id")
l2= Label(root, text="Student Name")
l3= Label(root, text="Student Age")
l4= Label(root, text="Student Country")
l1.grid(row=0, sticky=E)
l2.grid(row=1, sticky=E)
l3.grid(row=2, sticky=E)
l4.grid(row=3, sticky=E)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e4 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
b1= Button(root, text='Insert', command=insertstudent)
b1.grid(row=5, column=1, sticky=W, pady=4)
root.mainloop()
|
17dc194ec1a56cd846e727589729d22f2e45ec4f | DianaN87/Project-Diana | /biblioteki.py | 620 | 3.96875 | 4 | import calendar
print(calendar.month(2020,11, w=10, l=0)) # esli 1-9 mecjaz, to nuzno pisat prosto chslo bez 0 speredi
print(calendar.calendar(2020, w=0, l=0, c=13, m=3)) # c=3 - rastojanie mezdu stolbikami vsego kalendarakolichestvo, m- kolichestvo mesjacev v odnu strochku
print(calendar.weekday(2021, 2, 15)) # 0 pokazaivajet po indeksu denj nedeli v formate chisla
print(calendar.isleap(2020)) # will return True because 2020 is a leap year
print(calendar.isleap(2018)) # will return False because 2018 is not a leap year
print(calendar.leapdays(2000,2021)) # will return number of leap years between 2000 and 2020
|
52b59369626e4e18ee7364e897ca2443a286d199 | marufaytekin/robotics | /linear_controller.py | 6,318 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Linear Cascaded Control
#
# **NOTE** - completing this exercise without looking at the solution could take a few hours. Be prepared and good luck!
#
# <img src="Drone2.png" width="300" height="300">
#
# In this lesson we will be working with a simplified model of the 2D drone you worked with in the first lesson. We
# will be directly setting the vehicle's collective thrust through $u_1$ and the moment about the x axis,
# $M_x$ through $u_2$. We will ignore propeller rotation rates as well as the yaw-inducing moment $M_z$.
#
# The state of this 2D drone can be described by the following vector:
#
# $$X = [z , y, \phi, \dot{z}, \dot{y},\dot{\phi}]$$
#
import matplotlib.pylab as pylab
import simulate
import plotting
from controllers import LinearCascadingController
from drone import Drone2D
import trajectories
pylab.rcParams['figure.figsize'] = 10, 10
# #### TODO 1 - Review Simplified `Drone2D` class Walk through this code to refamiliarize youself with how state is
# represented, how controls are set, and what the underlying dynamics are.
# ### Linear Cascading Controller
#
# In this section, you will create the controller described in class. The schematic description of the cascading
# controller looks like this: <img src="CascadingController2.png" width="800" >
#
# The controller architecture uses three **PD** controllers to control the drone (note that, for simplification,
# you will not need an I term for the controllers used in this exercise).
#
# One PD controller is used to generate the thrust and control the altitude while two PD controllers are used to
# control the lateral motion. The first receives the desired lateral position information containing $y$ ,
# $\dot{y}$ and (optionally) $\ddot{y}$. Using this information as well as the current vehicle state, it outputs the
# commanded $\phi$ roll angle.
#
# The second PD controller is used to set a torque value $M_x$ to achieve the desired angle. In most cases,
# the inner controller responsible for roll angle operates at a higher frequency than the ones that are used to
# control the position.
# #### TODO - Implement 2D controller with LINEAR control equations.
#
# The linear equations of motion are shown below.
#
# $$\begin{align}
# \ddot{z} &= g - \frac{u_1}{m}
# \\
# \\
# \ddot{y} &= g \phi
# \\
# \\
# \ddot{\phi} &= \frac{u_2}{I_x}
# \end{align}$$
#
# These equations can be solved for $u_1$, $\phi_{\text{command}}$, and $u_2$.
#
# $$\begin{align}
# u_1 &= m(g - \bar{u_1})
# \\
# \\
# \phi_{\text{command}} &= \frac{\ddot{y}_{\text{target}}}{g}
# \\
# \\
# u_2 &= I_x \bar{u}_2
# \end{align}$$
#
# The first equation will be useful when implementing `altitude_controller`, the second when implementing
# `lateral_controller`, and the third when implementing `attitude_controller`.
#
# Note that $\ddot{y}_{\text{target}}$ is like $\bar{u}_1$ or $\bar{u}_2$. It comes from PD control on the
# controller's inputs.
#
# **Note the sequence of implementation, which should start from the INNER loop and then proceed with the OUTER loop.
# In this specific case, you should start implementing the ATTITUDE controller first, then proceed with the LATERAL
# and ALTITUDE controller.**
# The flight path we'll use to test our controller is a figure 8 described as follows:
# $$
# \begin{align}
# z & = a_z \sin{\omega_z t} \\
# y & = a_y \cos{\omega_y t}
# \end{align}
# $$
#
# where $\omega_y = \omega_z / 2$.
#
# > NOTE - you can find the code that generates this trajectory in the file called `trajectories.py`, which you can
# access by clicking on the Jupyter logo in the top left corner of this notebook.
# **NOTE on tuning:**
# <br></br>
#
# A good approach is to start with the inner loop, the ATTITUDE controller parameters (phi_k_p, phi_k_d) and the move
# forward with the LATERAL and ALTITUDE controller.
#
# 1- increase phi_K_p until the drone is able to perform a shape smilar to the final path
# <br></br>
# <img src="phi_k_p.png" width="300" height="300">
#
# 2- increase phi_k_d to align to the shape.
#
# 3- Re-adjust phi_k_p until you get something similar to this:
# <br></br>
# <img src="phi_k_p2.png" width="300" height="300">
#
# 4- At this point you can move forward with the outer loop for LATERAL postion. Increase y_k_d in order to align the
# shape in the y direction. Such as: <br></br> <img src="k_d.png" width="300" height="300">
#
# 5- Slightly increase y_k_p.
#
# 6- Now you can move on to the ALTITUDE controller and, as above, start increasing z_k_d and then slighlty increase
# z_k_p until you have a good overlap betwwen the planned and the executed path.
#
# TESTING CELL
#
# Note - this cell will only give nice output when your code
# is working AND you've tuned your parameters correctly.
# you might find it helpful to come up with a strategy
# for first testing the inner loop controller and THEN
# testing the outer loop.
#
# Run this cell when you think your controller is ready!
#
# You'll have to tune the controller gains to get good results.
#### CONTROLLER GAINS (TUNE THESE) ######
z_k_p = 0.1
z_k_d = 10.0
y_k_p = 0.3
y_k_d = 10.0
phi_k_p = 150.0
phi_k_d = 50.0
#########################################
drone = Drone2D()
# INSTANTIATE CONTROLLER
linear_controller = LinearCascadingController(
drone.m,
drone.I_x,
z_k_p=z_k_p,
z_k_d=z_k_d,
y_k_p=y_k_p,
y_k_d=y_k_d,
phi_k_p=phi_k_p,
phi_k_d=phi_k_d
)
# TRAJECTORY PARAMETERS (you don't need to change these)
total_time = 100.0
omega_z = 1.0 # angular frequency of figure 8
# GENERATE FIGURE 8
z_traj, y_traj, t = trajectories.figure_8(omega_z, total_time, dt=0.02)
z_path, z_dot_path, z_dot_dot_path = z_traj
y_path, y_dot_path, y_dot_dot_path = y_traj
# SIMULATE MOTION
linear_history = simulate.zy_flight(z_traj,
y_traj,
t,
linear_controller,
inner_loop_speed_up=10)
# PLOT RESULTS
plotting.plot_zy_flight_path(z_path, y_path, linear_history)
# If everything is working correctly you should see a blue figure 8 that (nearly) overlaps with a red figure 8.
|
cb38d9f780da3f8f4c88026d6c7665b81f4f13d3 | wseungjin/codingTest | /kakao/2021/2-fast.py | 1,764 | 3.53125 | 4 | from itertools import combinations
def getElements(orders):
elements = set()
for order in orders:
for i in range(len(order)):
elements.add(order[i])
answer=list(elements)
answer=sorted(answer)
return answer
def solution(orders, course):
elements = getElements(orders)
possibleArray = []
countArray = []
for courseNum in course:
possibleArray.append(list(map(''.join,combinations(elements,courseNum))))
countArray.append([])
for index,possibles in enumerate(possibleArray):
for possible in possibles:
count = 0
for order in orders:
flag = True
for pChar in possible:
if (pChar in order) == False:
flag = False
break
if(flag == True):
count += 1
if count > 1:
countArray[index].append((possible,count))
answer = []
for array in countArray:
if array:
newArray = sorted(array, key = lambda x:x[1] ,reverse = True)
answer.append(newArray[0][0])
maxValue = newArray[0][1]
for i in range(1,len(newArray)):
if (maxValue != newArray[i][1]):
break
answer.append(newArray[i][0])
answer = sorted(answer)
return answer
def main():
print(solution(["ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"],[2, 3, 4]))
print(solution(["ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD"],[2, 3, 5]))
print(solution(["XYZ", "XWY", "WXA"],[2, 3, 4]))
main() |
b2ee5d0b503f291796d45c807bd0fa2ddb274cb0 | EpsilonHF/Leetcode | /Python/219.py | 533 | 3.640625 | 4 | """
Given an array of integers and an integer k, find out whether
there are two distinct indices i and j in the array such that
nums[i] = nums[j] and the absolute difference between i and j
is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
"""
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
d = dict()
for i, val in enumerate(nums):
if val in d and i - d[val] <= k:
return True
d[val] = i
return False
|
0f9a520edff3825a861e623db91a22083d9a2efb | LuccaSantos/curso-em-video-python3 | /Desafios/modulo02/def66.py | 504 | 3.859375 | 4 | '''
crie um script q leia varios numeros inteiros (flag 999)
no final mostre quantos números foram digitados e qual a
soma entre eles
'''
print('= ' * 6 + 'TESTANDO O BREAK' + ' =' * 6)
soma = 0
numero_inputs = 0
while True:
numero_atual = float(input('Informe um número(999 para para!): '))
if numero_atual == 999:
break
else:
soma += numero_atual
numero_inputs += 1
print(f'A soma dos {numero_inputs} numeros digitados é {soma}')
print('= ' * 15)
|
1cf029d70860bd6015b8abe2e6d01ed46f50d777 | daniel-reich/turbo-robot | /FWh2fGH7aRWALMf3o_2.py | 1,079 | 4.40625 | 4 | """
Create a function that takes a string (without spaces) and a word list,
cleaves the string into words based on the list, and returns the correctly
spaced version of the string (a sentence). If a section of the string is
encountered that can't be found on the word list, return `"Cleaving stalled:
Word not found"`.
### Examples
word_list = ["about", "be", "hell", "if", "is", "it", "me", "other", "outer", "people", "the", "to", "up", "where"]
cleave("ifitistobeitisuptome", word_list) ➞ "if it is to be it is up to me"
cleave("hellisotherpeople", word_list) ➞ "hell is other people"
cleave("hellisotterpeople", word_list) ➞ "Cleaving stalled: Word not found"
### Notes
Words on the `word_list` can appear more than once in the string. The
`word_list` is a reference guide, kind of like a dictionary that lists which
words are allowed.
"""
def cleave(s,l):
r,l='',sorted(l)[::-1]
while s:
f=1
for w in l:
if s[:len(w)]==w:r,s,f=r+' '+w,s[len(w):],0
if f:return'Cleaving stalled: Word not found'
return r[1:]
|
7a9ec2362cb6ff94fbd54a901000317bb4dc79ac | mailinhvu912/C4T15 | /session3/minihack1/part5.py | 673 | 3.75 | 4 | from random import randint
Score = 0
while True:
a = randint(0,20)
b = randint(0,20)
c = randint(0,40)
print(a ,"+", b ,"=", c)
Answer = input("Is this correct?", )
if c == (a + b):
if Answer == "yes":
print("Well done")
Score+=1
print("Score =", Score)
else:
print("Game over")
print("Score =", Score)
break
elif c != (a + b):
if Answer == "no":
print("Well done")
Score+=1
print("Score =", Score)
else:
print("Game over")
print("Score =", Score)
break
|
36001589859d608522238ba7932f60e4e47cc6bc | srinijadharani/DataStructuresLab | /01/01_c_perfect.py | 719 | 3.828125 | 4 | # 1c. Program to check whether a given number is perfect or not.
"""Definition: A perfect number is a positive number such that
it is equal to the sum of its proper divisors."""
num = int(input("Enter a number to check whether it is a perfect number or not: "))
def perfect_number(num):
# initialize sum to zero in order to increment it later
sum1 = 0
# logic to find the sum of the divisors
for i in range(1, num):
if num%i == 0:
sum1 += i
# check if the number is equal to the sum. if yes, it is a perfect number
if sum1 == num:
print(num, "is a perfect number.")
else:
print(num, "is not a perfect number.")
perfect_number(num) |
86c94e69f58a8a9b0e6f0503c955cdafe8ee8fed | kohle/py-blackjack | /main.py | 7,730 | 3.90625 | 4 | # py-blackjack
# File description: Main class for the program
# Developed by Kohle Feeley
# Burlington, Vermont 2017
# Import Python classes
import random
# Score variable
score = 0
# Create score file if it doesn't exist with base score, otherwise get score
try :
score_file = open("score.txt", "r")
score = float(str(score_file.read()))
score_file.close()
except FileNotFoundError:
score_file = open("score.txt", "w")
score_file.write("10")
score = 100
score_file.close()
# Create the deck of cards
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4
# Method that deals 2 cards into a hand (a list), remove from deck
def deal(deck) :
hand = []
for x in range(2) :
random.shuffle(deck)
card = deck.pop()
# If we pick a JQKA, change it from a number to a string for the list
if card == 11 :
card = "J"
if card == 12 :
card = "Q"
if card == 13 :
card = "K"
if card == 14 :
card = "A"
hand.append(card)
return hand
# Method to hit, adds another card to the specified hand
def hit(hand) :
card = deck.pop()
# If we pick a JQKA, change it from a number to a string for the list
if card == 11 :
card = "J"
if card == 12 :
card = "Q"
if card == 13 :
card = "K"
if card == 14 :
card = "A"
hand.append(card)
return hand
# Method to calculate the hand's total value
def total(hand) :
total = 0
for card in hand :
if card == "J" or card == "Q" or card == "K" :
total = total + 10
elif card == "A" :
if total >= 11 :
total = total + 1
else :
total = total + 11
else :
total = total + card
return total
# Method to determime who won and print the appropriate statement
def winner() :
dealer_total = total(dealer)
player_total = total(player)
if dealer_total > 21 :
print("The dealer busted! You win!")
elif player_total > 21 :
print("You busted! Dealer wins!")
elif dealer_total > player_total :
print("Dealer wins!")
elif player_total > dealer_total :
print("Player wins!")
elif player_total == dealer_total :
print("It\'s a tie!")
# Game function that allows it to keep looping using break/while statements
def game() :
while True:
# Print main menu
print("##########[ BLACKJACK ]##########")
print("# #")
print("# MAIN MENU #")
print("# [P]LAY [S]CORE [A]BOUT #")
print("# #")
print("#################################")
# Ask for user's input
menu_choice = input(" ENTER YOUR CHOICE: ")
# About screen
while menu_choice.lower() == "a" :
print("\n############[ ABOUT ]############")
print("# #")
print("# Developed by Kohle Feeley #")
print("# (C) 2017 #")
print("# #")
print("#################################\n")
break
# High score table
while menu_choice.lower() == "s" :
print("\n############[ SCORE ]############")
print("YOUR SCORE IS: ", str(score))
print() # Break line
break
# Actually playing the game
while menu_choice.lower() == "p" :
# Re-state the deck of cards to prevent it from running out if
# the player decides to do multiple rounds
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4
# Create the two hands
dealer = deal(deck)
player = deal(deck)
# Tell the players their current total
print("\n############[ HAND ]############")
print("YOUR HAND:", str(player))
print("YOUR TOTAL:", str(total(player)))
# Betting procedure
print("\n###########[ BETTING ]##########")
print("YOU WILL RECEIVE 1.5x YOUR BET IF YOU WIN THE ROUND.")
print("YOUR SCORE IS: ", str(score))
betting = input("DO YOU WANT TO PLACE A BET? (Y/N): ")
amount = 0
if betting.lower() == "y" :
amount = input("ENTER YOUR BET: ")
amount = float(str(amount))
while amount > score :
print("YOU MUST ENTER AN AMOUNT LESS THAN YOUR SCORE.")
amount = input("ENTER YOUR BET: ")
amount = float(str(amount))
# Ask if they want to hit
hit_hand = input("\nDO YOU WANT TO HIT? (Y/N): ")
# If they want to hit
if hit_hand.lower() == "y" :
hit(player)
# Give them their new hand
print("\n############[ HAND ]############")
print("YOUR HAND:", str(player))
print("YOUR TOTAL:", str(total(player)))
# If the player didn't bust
if total(player) < 21 :
# This is the cut-off I decided for the dealer hitting
if total(dealer) < 12 :
hit(dealer)
print("\n###########[ RESULTS ]##########")
print("YOUR TOTAL:", str(total(player)))
print("DEALER TOTAL:", str(total(dealer)))
print() # Blank line
if total(dealer) > 21 :
print("The dealer busted! You win!")
if amount > 0 :
winnings = amount * 1.5
new_score = score + winnings
print("You won", str(amount * 1.5), "points!")
print("Your new score is", str(new_score))
score_file = open("score.txt", "w")
score_file.write(str(new_score))
score_file.close()
elif total(player) > 21 :
print("You busted! Dealer wins!")
if amount > 0 :
new_score = score - amount
print("You lost", str(amount), "points!")
print("Your new score is", str(new_score))
score_file = open("score.txt", "w")
score_file.write(str(new_score))
score_file.close()
elif total(dealer) > total(player) :
print("Dealer wins!")
if amount > 0 :
new_score = score - amount
print("You lost", str(amount), "points!")
print("Your new score is", str(new_score))
score_file = open("score.txt", "w")
score_file.write(str(new_score))
score_file.close()
elif total(player) > total(dealer) :
print("Player wins!")
if amount > 0 :
winnings = amount * 1.5
new_score = score + winnings
print("You won", str(amount * 1.5), "points!")
print("Your new score is", str(new_score))
score_file = open("score.txt", "w")
score_file.write(str(new_score))
score_file.close()
elif total(player) == total(dealer) :
print("It\'s a tie!")
if amount > 0 :
print("Nobody gets any points!")
print() # Blank line
break
game()
|
c770cbbc47d09745afd1e44b20392b7265a14cea | Dzhevizov/SoftUni-Python-Advanced-course | /Tuples and Sets - Exercise/04. Count Symbols.py | 218 | 3.640625 | 4 | text = input()
dictionary = {}
for el in text:
if el not in dictionary:
dictionary[el] = 0
dictionary[el] += 1
for letter, count in sorted(dictionary.items()):
print(f"{letter}: {count} time/s")
|
3ae7965d6da9d452ef1deae189ff91138d43cf98 | PuttTim/MundaneUnevenBug | /diamond/diamond half bottom.py | 463 | 3.90625 | 4 | row=int(input("Enter row number here: "))
column=0
col2=row-1
column3=row
col4=1
for i in range (row):
column=int(column+1)
# for blanks
for i in range (column):
print(" ", end='')
# for stars
for i in range (col2+1):
print("*", end="")
col2=col2-1
#bottom half
#for stars
column3=int(column3-1)
for i in range (column3):
print("*", end='')
#for blanks
for i in range (col4):
print(" ", end="")
col4=col4+1
print("")
|
fe940875d949b8c1b8d56ff777a0b9ac01a62ee2 | rtejaswi/python | /rec.py | 105 | 3.703125 | 4 | def rec():
a=input('enter the string')
#if len(a)>1:
temp=a[::-1]
print(temp)
rec()
|
9a2d0596d60feff1d0993ac86a4509bcbf478728 | Nazarik86/Second_Lesson_Python | /Fifth_Lesson_Python/Mikhail_Nazarov_HW_5_4.py | 739 | 3.9375 | 4 | # 4. Представлен список чисел. Необходимо вывести те его элементы, значения которых больше предыдущего, например:
#
# src = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
# result = [12, 44, 4, 10, 78, 123]
# ```
# Подсказка: использовать возможности python, изученные на уроке.
src = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
result = []
for i in range(len(src)-1):
if src[i] < src[i+1]:
result.append(src[i+1])
print('Вывод цикла: ', result)
result_second = [j for i, j in zip(src, src[1:]) if j > i]
print('Вывод генератора: ', result_second)
|
7008e868a5ebf045bed71e308e0dafdd77833936 | SeifMostafa/SeShat-master | /Text To Speach.py | 1,094 | 3.703125 | 4 | """def synthesize_text(text):
Synthesizes speech from the input string of text.
from google.cloud import texttospeech
client = texttospeech.TextToSpeechClient()
input_text = texttospeech.types.SynthesisInput(text="هذا صحيح")
# Note: the voice can also be specified by name.
# Names of voices can be retrieved with client.list_voices().
voice = texttospeech.types.VoiceSelectionParams(
language_code='ar-EG',
ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
response = client.synthesize_speech(input_text, voice, audio_config)
# The response's audio_content is binary.
with open('output.wav', 'wb') as out:
out.write(response.audio_content)
print('Audio content written to file "output.mp3"')
"""
from gtts import gTTS
def tts(filename,text,lang):
gTTS(text=text,lang= lang).save(filename)
print("Done")
text = "نعناعةْ"
name = "نعناعة"
lang = "ar"
tts(name,text,lang) |
d88f690ede9b352c16f22d817c2277671976682e | liliang1991/machinelearning | /src/main/python/mlib/word2vec/util/Word2VecUtils.py | 833 | 3.578125 | 4 | from pyspark.ml.feature import Word2Vec
from pyspark.shell import spark
# Input data: Each row is a bag of words from a sentence or document.
documentDF = spark.createDataFrame([
("Hi I heard about Spark".split(" "), ),
("I wish Java could use case classes".split(" "), ),
("Logistic regression models are neat".split(" "), )
], ["text"])
def Word2VecModel(input_col, output_col, vocab_size, minCount, input_data):
# mindf 必须在文档中出现的最少次数
# vocabSize 词典大小
wv = Word2Vec(inputCol=input_col, outputCol=output_col, vocabSize=vocab_size, minDF=minCount)
model = wv.fit(input_data)
result = model.transform(input_data)
return result;
# for row in result.collect():
# text, vector = row
# print("Text: [%s] => \nVector: %s\n" % (", ".join(text), str(vector))) |
ee9aa7e9974bfcbd48682885d0b8b8f858849d76 | smile0304/py_asyncio | /chapter06/set_test.py | 312 | 3.78125 | 4 | #set 集合
#fronzenset 不可变集合
# 无序,不重复
s = set("abcdee")
print(s)
s = set(["a","b","c","d","e"])
s = {'a','b','c'}
s.add('s')
print(type(s))
print(s)
# s = frozenset('abc')
# print(s)
another_set = set("def")
s.update(another_set)
print(s)
re_set = s.difference(another_set)
print(re_set) |
eb77966d1d5878ada4f95e18c4e50959275aff34 | andresalbertoramos/Master-en-Programacion-con-Python_ed2 | /silvia/05_class/reverse.py | 114 | 3.875 | 4 | def reverse(a, b):
return b, a # Lo devuelve en una tupla
a = 1
b = 2
a, b = reverse(a, b)
print(a)
print(b) |
bec8b6450cf3108276a4aab15c0750f28ef07295 | Talhaitis612/BasicofPython | /main.py | 1,364 | 3.921875 | 4 | #Python is a programming langague with a clean syntax
#Python programs can be ru on all desktop programs.
#Hello World will always be the first program that you make in any langague.
#here we did the same
#print is a built in function of android we will learn about function more in detail below
print('hello world')
#so what are variables ?
#Python Supports different type of variable such as whole numbers, floating points,and text.
f=4 #a whole number
c=3.133 #a floating point number
name="Python" # a string
#we can print them all using print function
print(c)
print(f)
print(name)
#Let's Talk about Python String in details
#A string can be called as collection of charchters or text
x="Hello"
print(x)
#String Indexing
#Indiviual Charachters can be acccessed using blockquotes,couting starts from zero
print(x[0])
print(x[2])
#String Slicing
print(x[0:3])
#Comibing String or Adding them
x="Talha"
#Combing Numbers and Text
#There are a lot of methods to do that
s="My lucky number is %d What is yours?"%7
print(s)
#Alternative method of combining
s="My lucky number is "+str(7)+" what is yours?"
print(s)
#String replace method
#Python has a built in support for String replacement .
d="Hello world"
d.replace("World","Universe",1)
print(d)
#In python and many other programming languages you can get user input
name=input("talha")
print("Hello"+name) |
b0f1bbe30323a896e926b6a3e81417102f2425ea | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/Account.py | 2,166 | 3.90625 | 4 | # Account Program
# Shehu Muhammad
# February 14, 2018
grade1 = int(input("What was the first grade? "))
grade2 = int(input("What was the second grade? "))
grade3 = int(input("What was the third grade? "))
grade4 = int(input("What was the fourth grade? "))
if(grade2 <= 50):
print("You failed Part 1.")
print("You failed Part 2.")
print("You failed Part 3.")
print("You failed Part 4.")
elif(grade1 >=75 and (grade2 <75 and grade3 <75 and grade4 <75)):
print("You failed Part 1.")
print("You failed Part 2.")
print("You failed Part 3.")
print("You failed Part 4.")
elif(grade2 >=75 and (grade1 <75 and grade3 <75 and grade4 <75)):
print("You failed Part 1.")
print("You failed Part 2.")
print("You failed Part 3.")
print("You failed Part 4.")
elif(grade3 >=75 and (grade1 <75 and grade2 <75 and grade4 <75)):
print("You failed Part 1.")
print("You failed Part 2.")
print("You failed Part 3.")
print("You failed Part 4.")
elif(grade4 >=75 and (grade1 <75 and grade2 <75 and grade3 <75)):
print("You failed Part 1.")
print("You failed Part 2.")
print("You failed Part 3.")
print("You failed Part 4.")
elif(grade1 >= 75 and grade2 >= 75 and grade3 >=75 and grade4 <75):
print("You passed Part 1.")
print("You passed Part 2.")
print("You passed Part 3.")
print("You failed Part 4.")
elif(grade1 >= 75 and grade2 >= 75 and grade3 <75 and grade4 >=75):
print("You passed Part 1.")
print("You passed Part 2.")
print("You failed Part 3.")
print("You passed Part 4.")
elif(grade1 >= 75 and grade2 < 75 and grade3 >=75 and grade4 >=75):
print("You passed Part 1.")
print("You failed Part 2.")
print("You passed Part 3.")
print("You passed Part 4.")
elif(grade1 < 75 and grade2 >= 75 and grade3 >=75 and grade4 >=75):
print("You failed Part 1.")
print("You passed Part 2.")
print("You passed Part 3.")
print("You passed Part 4.")
elif(grade1 >= 75 and grade2 >= 75 and grade3 >=75 and grade4 >=75):
print("You passed Part 1.")
print("You passed Part 2.")
print("You passed Part 3.")
print("You passed Part 4.")
|
45c4f94c95c36b37dbba3ba1255db4a7b9f8ce3f | ArshSood/Codechef_Assignment | /PEC2021H/PECEX1D.py | 503 | 3.6875 | 4 | def stairs(n,x):
global num
if x==1:
count=0
for i in range(-3,4):
#count=0
if n-i==0:
count+=1
return count
count=0
for i in range(-3,4):
if 0<=n-i<=num and x!=0:
count+=stairs(n-i,x-1)
return count
t=int(input())
for i in range(0,t):
global num
num,x=list(map(int,input().split()))
if num==0 and x==0:
print(1)
else:
Ans=stairs(num,x)
print(Ans)
|
fededea82535dba548c9dfc3e735819addefc14b | chandrakanth137/GUI-Sudoku-Solver-python | /GUI-Sudoku_Solver/Sudoku_Solver.py | 10,674 | 3.921875 | 4 | from tkinter import *
from tkinter import messagebox
import copy
# to find the empty cells in the sudoku
def find_empty_location(arr, l):
for row in range(9):
for col in range(9):
if(arr[row][col]== 0):
l[0]= row
l[1]= col
return True
return False
# to check if the input value already exists or not in that row
def used_in_row(arr, row, num):
for i in range(9):
if(arr[row][i] == num):
return True
return False
# to check if the input value already exists or not in that column
def used_in_col(arr, col, num):
for i in range(9):
if(arr[i][col] == num):
return True
return False
# to check if that value is used already exists in the 3x3 grid or not
def used_in_box(arr, row, col, num):
for i in range(3):
for j in range(3):
if(arr[i + row][j + col] == num):
return True
return False
# to check if value is fit enough to be in that cell
def check_location_is_safe(arr, row, col, num):
return not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num)
# sudoku solver driver function
def solver(arr):
l =[0, 0]
if(not find_empty_location(arr, l)):
return True
row = l[0]
col = l[1]
for num in range(1, 10):
if(check_location_is_safe(arr,
row, col, num)):
arr[row][col]= num
if(solver(arr)):
return True
arr[row][col] = 0
return False
# Global variables
win = Tk()
win.title("Sudoku")
win.geometry("700x760")
win.configure(bg="#1f1f1f")
win.resizable(False,False)
SIDE = 60
WIDTH = 540
HEIGHT = 540
border_thickness = 4
# class for creating question sudoku board and input sudoku board function
class dokuSolver(object):
def __init__(self):
self.question = []
def game_start(self):
self.input_board = []
self.answer = []
# class to create the GUI for the sudoko board
class dokuUI(Frame):
def __init__(self,main_screen,doku):
self.doku = doku
self.main_screen = main_screen
Frame.__init__(self,main_screen)
self.row = -1
self.col = -1
self.cur_x = -1
self.cur_y = -1
self.item = {}
self.choice = StringVar()
self.create_board()
# to choose the board from respective text files
def submit_board(self):
bo = ['1','2','3','4']
li1= []
if self.choice.get() in bo:
with open("%s.txt" % self.choice.get(),'r') as f:
lines = f.readlines()
for line in lines:
if line[-1] == '\n':
li1.append(list(map(int,line[:-1])))
else:
li1.append(list(map(int,line[:])))
self.doku.answer = copy.deepcopy(li1)
self.doku.question = copy.deepcopy(li1)
self.doku.input_board = copy.deepcopy(li1)
self.menu.destroy()
self.lb.destroy()
self.bt.destroy()
self.e.destroy()
solver(self.doku.answer)
self.create_num_board()
else:
self.menu.destroy()
self.lb.destroy()
self.bt.destroy()
self.e.destroy()
messagebox.showinfo('Invalid Choice','Entered value out of range')
self.board_selection()
# to create a window to choose the question
def board_selection(self):
self.menu = Canvas(win,width=300,height=130,bg="black",highlightbackground="red")
self.menu.place(x = 200 ,y =150)
self.lb = Label(win,text = "Choose Board.\nEnter number between 1 - 4",fg='white',bg='black')
self.bt = Button(win,text="Submit",width=20,height=1,command=self.submit_board,highlightbackground='black')
self.e = Entry(win,textvariable = self.choice,width=30,bg='black',fg='white')
self.lb.place(x=253,y = 155)
self.bt.place(x=240,y=240)
self.e.place(x=212,y=205)
# basic layout the gui
def create_board(self):
self.sudoku_board = Canvas(win, width= 540, height = 540, bg="white", highlightbackground="black")
for i in range(9):
if i%3 == 0 and i != 0 and i != 8:
self.sudoku_board.create_line(0, i*SIDE, WIDTH+border_thickness, i*SIDE, fill="black", width=2)
else:
self.sudoku_board.create_line(0, i*SIDE, WIDTH+border_thickness, i*SIDE, fill="black")
for i in range(9):
if i%3 == 0 and i != 0 and i != 8:
self.sudoku_board.create_line(i*SIDE, 0, i*SIDE, HEIGHT+border_thickness, fill="black", width=2)
else:
self.sudoku_board.create_line(i*SIDE, 0 , i*SIDE, HEIGHT+border_thickness ,fill="black")
self.sudoku_board.pack(padx=20,pady=20)
self.board_selection()
# to draw the layout when the sudoku puzzle is solved successfully
def draw_won(self):
x0 = y0 = border_thickness + SIDE * 2
x1 = y1 = border_thickness + SIDE * 7
self.sudoku_board.create_oval(x0, y0, x1, y1,tags="won", fill="dark orange", outline="orange")
x = y = border_thickness + 4 * SIDE + SIDE / 2
self.sudoku_board.create_text(x, y,text=" Sudoku Solved!\nPress clear to restart sudoku", tags="won",fill="white", font=("Arial", 20))
# to check if the board was solved
def is_complete(self):
if self.doku.input_board == self.doku.answer:
self.draw_won()
else:
lb = Label(win,text="Wrong Answer!",fg = "red",bg="black",font=('Arial Bold',30,))
lb.place(x=247,y=650)
self.after(2000,lb.destroy)
def solve_it(self):
self.sudoku_board.delete("temp")
for i in range(9):
for j in range(9):
value = self.doku.answer[i][j]
if value != 0 and (i,j) in self.zero_pos:
x = border_thickness + j * SIDE + SIDE/2
y = border_thickness + i * SIDE + SIDE/2
self.sudoku_board.create_text(x,y,text = value,tags="auto",fill="firebrick2",font=('Arial','30','bold'))
lb = Label(win,text="Auto Solved",fg = "Cyan2",bg="black",font= ('Arial Bold',30))
lb.place(x=255,y=650)
self.after(3000,lb.destroy)
# to create the initial question board
def create_num_board(self):
clear_bt = Button(win, text="Clear", width=8, height=2,command=self.clear_board)
clear_bt.place(x=75,y=600)
solve_bt = Button(win, text="Check", width=8, height=2,command=self.is_complete)
solve_bt.place(x=525,y=600)
solution_bt = Button(win, text ="Solve", width=8, height=2,command=self.solve_it)
solution_bt.place(x=300,y=600)
quit_bt = Button(win,text='X',fg='red',highlightbackground='black',width=1,height=1,command = lambda : win.quit())
quit_bt.place(x=640,y=10)
quit_lb = Label(win,text='Quit',fg='red',bg='black',font=('Arial',15))
quit_lb.place(x=645,y=38)
self.sudoku_board.bind("<Button-1>",self._click)
self.sudoku_board.bind("<Key>",self._keypress)
self.zero_pos = []
for i in range(9):
for j in range(9):
if self.doku.question[i][j] == 0:
self.zero_pos.append((i,j))
self.sudoku_board.delete("num")
for i in range(9):
for j in range(9):
value = self.doku.question[i][j]
if value != 0:
x = border_thickness + j * SIDE + SIDE/2
y = border_thickness + i * SIDE + SIDE/2
self.sudoku_board.create_text(x,y,text = value,tags="num",fill="black",font=('Arial','30','bold'))
# to input values in the empty cells
def fill_empty(self):
value = self.doku.input_board[self.row][self.col]
if value != 0 :
x = border_thickness + self.col * SIDE + SIDE/2
y = border_thickness + self.row * SIDE + SIDE/2
if (self.cur_x,self.cur_y) != (self.row,self.col) and (x,y) not in self.item :
self.item[(x,y)] = self.sudoku_board.create_text(x,y,text = value,tags="temp",fill= "SteelBlue1" ,font=('Arial','30','bold'))
self.cur_x,self.cur_y = self.row,self.col
else:
self.sudoku_board.delete(self.item[(x,y)])
self.item[(x,y)] = self.sudoku_board.create_text(x,y,text = value,tags="temp",fill= "SteelBlue1" ,font=('Arial','30','bold'))
# to draw the outline when a cell is clicked
def design_pointer(self):
self.sudoku_board.delete("pointer")
if(self.row >= 0 and self.col >= 0):
x1 = self.col * SIDE
x2 = (self.col + 1) * SIDE
y1 = self.row * SIDE
y2 = (self.row + 1) * SIDE
self.sudoku_board.create_rectangle(x1,y1,x2,y2,outline="red",tags="pointer",width=3)
#to clear the entered numbers in the board
def clear_board(self):
self.sudoku_board.delete("auto")
self.sudoku_board.delete("won")
self.sudoku_board.delete("temp")
self.design_pointer()
for (i,j) in self.zero_pos:
self.doku.input_board[i][j] = 0
# to update the value of the input board whenever a number is added in the cell
def _keypress(self,event):
if self.row >= 0 and self.col >= 0 and event.char in "123456789":
self.doku.input_board[self.row][self.col] = int(event.char)
self.fill_empty()
# to identify where the mouse click happended to identify the cell locations
def _click(self,event):
a, b = event.x , event.y
if(border_thickness < a < WIDTH - border_thickness and border_thickness< b < HEIGHT - border_thickness):
self.sudoku_board.focus_set()
x , y = int((b - border_thickness)/SIDE) , int((a - border_thickness)/SIDE)
if (self.row, self.col) == (x,y):
self.row, self.col = -1, -1
elif self.doku.question[x][y] == 0:
self.row, self.col = x, y
else:
self.row , self.col = -1 , -1
self.design_pointer()
# program's main driver function
if __name__ == '__main__':
game = dokuSolver()
game.game_start()
dokuUI(win,game)
win.mainloop()
|
13528f143378bcd7f952195b86c5d9a851d0a0fd | jananee009/Project_Euler | /Euler_Problem32.py | 3,028 | 4 | 4 | # Pandigital Products
# Problem 32: https://projecteuler.net/problem=32
# Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
# Approach:
# 1. We want to find a product such that multiplicand * multiplier = product and the multiplicand, multiplicant and product taken together form a pandigital number
# of 9 digits.
# 2. From the example given in the problem itself we know that a 2 digit number multplied with a 3 digit number may yield a product and they may all together form a
# pandigital number.
# 3. We need to find in what other ways can we find a pandigital product. Consider the following table.
# Multiplier
# 1-digit 2-digit 3-digit 4-digit
# 1-digit 1,2 digits 2,3 digits 3,4 digits 4,5 digits
# Multiplicand 2-digit 2,3 digits 3,4 digits 3,4,5 digits 6 digits
# 3-digit 3,4 digits 3,4,5 digits 5 or more digits 6 or more digits
# 4-digit 4,5 digits 5 or more digits 6 or more digits 8 or more digits
# From the above confusion matrix, we can see that only the following 2 types of multiplicands and multipliers suit our requirement:
# Multiplicand Multiplier
# 1-digit 4-digit
# 2-digit 3-digits
# Anything other than the above 2 types results in a multiplicand/multiplier/product identity longer than 9 digits.
import math
import time
import Common
import itertools
def fingPandigitalProdcuts():
pandigitalProducts = {0} # we are using a set because we want to avoid adding duplicate pandigital products.
# 2 digit multiplicands are multiplied with 3-digit multipliers
for multiplicand in range(12,99):
for multiplier in range(102, 988):
product = multiplicand * multiplier # compute product
multiplicand_nultiplier_product = int(str(multiplicand) + str(multiplier) + str(product)) # form a single identity using the multiplicand, multiplier and product
if (Common.isPandigital(multiplicand_nultiplier_product)): # check if the identity is pandigital
pandigitalProducts.add(product) # add product to the set of pandigital products.
# 1 digit multiplicands are multiplied with 4-digit multipliers
for multiplicand in range(1,10):
for multiplier in range(1002, 9877):
product = multiplicand * multiplier # compute product
multiplicand_nultiplier_product = int(str(multiplicand) + str(multiplier) + str(product)) # form a single identity using the multiplicand, multiplier and product
if (Common.isPandigital(multiplicand_nultiplier_product)): # check if the identity is pandigital
pandigitalProducts.add(product) # add product to the set of pandigital products.
return sum(pandigitalProducts)
def main():
start_time = time.time()
print "The sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital is:", fingPandigitalProdcuts()
print "Problem solved in %s seconds " % (time.time()-start_time)
if __name__ == "__main__":
main()
# Answer: 45228
|
b89ec87026edfef15839d29454e377f7a85791ab | flogothetis/Technical-Coding-Interviews-Algorithms-LeetCode | /Grokking-Coding-Interview-Patterns/2. Two Pointers/subarrayswithProductLesssThanATarget.py | 645 | 3.90625 | 4 | from collections import deque
# Time Complexity : O(N^3)
def subarraylessProductTarget ( array, target):
windowStart = 0
prod = 1
result = []
for windowEnd in range ( len(array)): # O(N^3)
prod *= array[windowEnd]
if ( prod >= target and windowStart <len(array)):
prod/= array[windowStart]
windowStart+=1
temp_list = deque() # O(N) space
for i in range (windowEnd, windowStart-1, -1): # O(N^2)
temp_list.appendleft(array[i])
result.append(list(temp_list.copy())) # O(N)
return result
def main():
print(subarraylessProductTarget([2, 5, 3, 10], 30))
print(subarraylessProductTarget([8, 2, 6, 5], 50))
main()
|
f3eb6edbfdfbdae64055c95766d817363a6cdc0f | Laruxx/Data_projects | /Python 101 Full Version 2-25-2019.py | 69,595 | 3.84375 | 4 | # You can use the # symbol to comment your Python code
''' Another way to comment your Python code is to use
a multiline string that is opened and closed with three single or double quotation marks
'''
"""
this is also a comment"""
####################
### INSTALLATION ###
####################
# 5 MINUTES
# Install the latest version of Python using Anaconda from https://www.anaconda.com/distribution/#download-section
# After installing, using the Start Menu open either iPython or Anaconda Prompt from the Anaconda app
# If using the Anaconda Prompt, type "ipython" and hit ENTER to launch the iPython shell
# The iPython shell will display "In [#]:" when a command is entered and "Out[#]:" when displaying the output of a command
# FULL PYTHON INSTALLATION INSTRUCTIONS CAN BE FOUND IN APPENDIX
#################
### LIBRARIES ###
#################
# 5 MINUTES
# Libraries can be imported into a Python file session using the "import" command
In [22]: import math
# To see some of the documentation associated with an imported library, use the help(library) function
# Scrolling through the output of help(math) using the Enter key, we see "ceil" is a function inside of math
# There can be a significant amount of help output; to get through it quickly use CTRL+C (this stops what is currently processing in Python; CTRL+D exits iPython shell)
# *** CTRL+C is very useful! Don't forget about it! ***
In [23]: ceil(1/2)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-864ea98b5f8d> in <module>()
----> 1 ceil(1/2)
NameError: name 'ceil' is not defined
# When calling specific functions from a library, it's necessary to preceed the function with the library's name
In [24]: math.ceil(1/2)
Out[24]: 1
# Alternatively, to avoid having to preceed every function, import the function directly from the library
In [25]: from math import ceil
In [26]: ceil(1/2)
Out[26]: 1
# Alternatively, create a shortcut by aliasing a library's name, just be careful to not use an alias you will need later on
In [27]: import math as m
In [28]: m.ceil(1/2)
Out[28]: 1
#################
### SECTION 1 ###
#################
# 80 MINUTES
# The primitive classes / data types in Python include Integers, Floats, Strings, Booleans
# It's easy to declare variables and assign values to them with the "=" operator, which will establish their Types
# Types are dynamic in Python, meaning it's possible to change a variable's type repeatedly
In [1]: x = 25
In [2]: type(x)
Out[2]: int
In [3]: x = str(25)
In [4]: type(x)
Out[4]: str
In [5]: float(x) # re-cast a string as a float
Out[5]: 25.0
In [1]: z = 1.313
In [2]: type(z)
Out[2]: float
In [3]: y = 'global insights is awesome'
In [4]: type(y)
Out[4]: str
In [42]: print(y)
global insights is awesome
# You can print multiple items using a single print statement
# You can also print new lines using the newline character "\n"
In [47]: print(y, x)
global insights is awesome 25
In [53]: print(y, '\n', 'and so are you!')
global insights is awesome
and so are you!
In [10]: y + x # you cannot add strings and integers
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-adce3e2171e0> in <module>()
----> 1 y + x
TypeError: must be str, not int
In [11]: y*x # but you can "multiply" strings by integers to create longer concatenated strings
Out[11]: 'global insights is awesomeglobal insights is awesomeglobal insights is awesomeglobal insights is awesome...' # note '...' is not actually printed
In [5]: x == y # you can perform boolean comparisons using operators such as ==, =!, >=, <=
Out[5]: False # Note Python True and False are title cased
In [45]: x != y
Out[45]: True
In [1]: x = True
In [2]: x
Out[2]: True
In [3]: x == False # notice the difference between the assignment operator "=" and the equality comparison operator "=="
Out[3]: False
In [4]: type(x)
Out[4]: bool
In [5]: print('123', x)
123 True
# Python's primitive types also include collection objects -- Lists, Tuples, Dictionaries, which can be declared in different ways
In [42]: x = list()
In [46]: type(x)
Out[46]: list
In [1]: x = [] # square brackets
In [2]: type(x)
Out[2]: list
In [43]: y = tuple()
In [47]: type(y)
Out[47]: tuple
In [3]: y = () # parentheses
In [4]: type(y)
Out[4]: tuple
In [44]: z = dict()
In [48]: type(z)
Out[48]: dict
In [5]: z = {} # curly braces
In [6]: type(z)
Out[6]: dict
# Lists and Tuples are examples of ordered collection objects, while Dictionaries are not ordered
# You can access an ordered collection object's items using an index operator, formatted as object[index]... Python index always begin with 0!
In [6]: list_x = [1, 2, 3, 4]
In [7]: list_x
Out[7]: [1, 2, 3, 4]
In [4]: list_x[0]
Out[4]: 1
In [5]: list_x[1]
Out[5]: 2
In [6]: list_x[-1] # negative indices start from the end, -1 is the last element in the List
Out[6]: 4
In [7]: list_x[0:2] # slice a list using list[index1:index2] ... IMPORTANT this will return all items UP TO BUT NOT INCLUDING the item at the end of the slice range!
Out[7]: [1, 2]
In [14]: len(list_x)
Out[14]: 4
In [13]: list_x[0:len(list_x)]
Out[13]: [1, 2, 3, 4]
In [8]: list_x[0:-1]
Out[8]: [1, 2, 3]
In [9]: list_x[:-1] # leaving the indices blank on either side of the colon means to start from the beginning or go to the end
Out[9]: [1, 2, 3]
In [11]: list_x[1:]
Out[11]: [2, 3, 4]
# List can include items of multiple types
In [74]: random_list = ['hello!', 'HELLO!', 0, [2, 3]]
In [75]: random_list
Out[75]: ['hello!', 'HELLO!', 0, [2, 3]]
# random_list is a list of strings (Sir Annoy-O says hello! HELLO!), an integer, and a List of integers
# Items in a list can be replaced; for this reason a list is called a "mutable" object (think "mutation" ... complete)
In [14]: random_list[3] = (8,9,10) # this replaces the 4th item in the list (the list [2,3]) with a tuple (8, 9, 10)
In [15]: random_list
Out[15]: ['hello!', 'HELLO!', 0, (8, 9, 10)]
# Unlike lists, however, tuples are NOT mutable (they cannot be changed after instantiation)
In [19]: tuple_x = (1,2,3)
In [20]: tuple_x[0]
Out[20]: 1
In [21]: tuple_x[0] = 11
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-622e4f267299> in <module>()
----> 1 tuple_x[0] = 11
TypeError: 'tuple' object does not support item assignment
# It's easy to change between types
In [93]: type(tuple_x)
Out[93]: tuple
In [94]: list_x = list(tuple_x)
In [96]: type(list_x)
Out[96]: list
In [21]: list_x[0] = 11
In [95]: list_x
Out[95]: [11, 2, 3]
# The values of a list or tuple can be unpacked using the "multiple assignment" shortcut
In [22]: a, b = 2+3, 10
In [23]: a
Out[23]: 5
In [24]: b
Out[24]: 10
In [15]: random_list = ['hello!', 'HELLO!', 0, (8, 9, 10)]
In [17]: a,b,c,d = random_list
In [18]: a
Out[18]: 'hello!'
In [19]: b
Out[19]: 'HELLO!'
In [20]: c
Out[20]: 0
In [21]: d
Out[21]: (8, 9, 10)
In [16]: a, b, c = random_list # make sure to unpack all the values of the list
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-8ead02d17252> in <module>()
----> 1 a, b, c = random_list
ValueError: too many values to unpack (expected 3)
# The last collection object type to mention is the Dictionary
# Dictionaries are NOT ordered but support a different type of "indexing" (similar to keys in a SQL table)
In [10]: dict_y = {'roland':'male', 'jennifer':'female'}
In [14]: dict_y['roland']
Out[14]: 'male'
In [155]: dict_y['lucky'] = 'dog'
In [156]: dict_y
Out[156]: {'roland': 'male', 'jennifer': 'female', 'lucky': 'dog'}
In [58]: dict_y[0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-58-9f03f94768f3> in <module>()
----> 1 dict_y[0]
KeyError: 0
# Each type/class has a set of functions called METHODS that operate specifically on that object type
# List methods
In [37]: list_x = [1,2,3,4]
In [18]: list_x.append(5) # concatenates an item to the end of the list
In [19]: list_x
Out[19]: [1, 2, 3, 4, 5]
In [20]: list_x.remove(5) # removes the first occurrence of an item
In [21]: list_x
Out[21]: [1, 2, 3, 4]
In [43]: list_x.append([5,6,7,8])
In [44]: list_x
Out[44]: [1, 2, 3, 4, [5, 6, 7, 8]]
In [37]: list_x = [1,2,3,4]
In [25]: list_x.extend(list_x) # extends the list with the items in another list; NOTE the difference between extend() and append()!
In [26]: list_x
Out[26]: [1, 2, 3, 4, 1, 2, 3, 4]
In [37]: list_x = [1,2,3,4]
In [23]: list_x.pop() # .pop(x) removes the item at the index passed to the method (no argument defaults to last item)
Out[23]: 4
In [24]: list_x
Out[24]: [1, 2, 3]
In [45]: list_x = [1,2,3,1,2,3]
In [27]: list_x.count(1) # counts occurrences of items in a list
Out[27]: 2
In [28]: list_x.sort()
In [29]: list_x
Out[29]: [1, 1, 2, 2, 3, 3]
In [30]: list_x.reverse()
In [31]: list_x
Out[31]: [3, 3, 2, 2, 1, 1]
In [36]: list_x.insert(1,5) # insert(x,y) inserts value y at index x, and increments all other items to the next index
In [37]: list_x
Out[37]: [3, 5, 3, 2, 2, 1, 1]
# Use the set() operator to remove duplicate items from a list
In [91]: list(set(list_x))
Out[91]: [1, 2, 3, 5]
# Lists are useful for flow control when iterating through FOR LOOPS
In [37]: list_x = [1,2,3,4]
In [8]: for item in list_x: # a list is an example of an "iterable"; aliases such as "item" can be used to track steps in the for loop
...: print(item) # Python uses an indentation scheme (4 spaces) for flow control... not indenting correctly will generate errors!
...:
1
2
3
4
In [12]: for item in list_x:
...: print(item)
File "<ipython-input-12-a8065a013cab>", line 2
print(item)
^
IndentationError: expected an indented block
# IF-THEN statements and loops can be easily nested using indentation
In [39]: list_x = [1,2,3,4]
...: for itemXXX in list_x: # this alias scheme is directly assigning elements from the list to itemXXX
...: if itemXXX >= 2 and itemXXX % 3 == 0: # % is remainder division; the only item in list_x satsifying these conditions is 3
...: for rand0 in [9,7,4]:
...: print(itemXXX+rand0)
...:
12
10
7
# Range objects created based on lists lengths can be used to assign index values to aliases, which can then be used to reference values from the list using list[alias]
In [12]: range(10)
Out[12]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [13]: range(3,6)
Out[13]: [3, 4, 5]
In [59]: for qqq in range(len(list_x)):
...: print(qqq, list_x[qqq])
...:
0 1
1 2
2 3
3 4
# String Interpolation involves passing arguments to placeholders in a string
# String Interp method 1 uses curly braces {index} indexing and the string .format() method to pass arguments to their relative placeholders
In [50]: print('Hello my name is {0}... I, {0}, have a dog named {1}.'.format('Roland', 'Lucky'))
Hello my name is Roland... I, Roland, have a dog named Lucky.
# String Interp method 2 uses %s as placeholder and % after the string instead of the .format() method
# The disadvantage of method 2 is that it does not map single arguments to multiple placeholders
# In other words, String Interp method 2 requires each placeholder to have an explicit argument passed to it
In [51]: print('Hello my name is %s... I, %s, have a dog named %s.' % ('Roland','Roland','Lucky'))
Hello my name is Roland... I, Roland, have a dog named Lucky.
# Using String Interp it's possible to modify the contents of the string within a loop and print the changing string
In [60]: for index in range(len(list_x)):
...: print('The item at index {0} is {1}'.format(index, list_x[index]))
...:
The item at index 0 is 1
The item at index 1 is 2
The item at index 2 is 3
The item at index 3 is 4
# This can be very useful when debugging and tracking steps during program execution
# CAUTION: Do not alter the iterable as you are iterating through it! Python's internal indexing scheme may get thrown off, leading to unexpected behavior!
In [9]: for item in list_x:
...: list_x.remove(item)
...: print(list_x)
...:
[2, 3, 4]
[2, 4]
# In the first iteration, Python searches for index 0 in the list [1,2,3,4], finds 1, and removes it, leaving [2,3,4]
# In the next iteration, Python searches for index 1 in the list [2,3,4], finds 3, and removes it, leaving [2,4]
# In the next iteration, Python searches for index 2 in the list [2,4], finds no such index, and exits the loop
# If you need to change a list, it's generally a better idea to work with copies or clones of the list
# CAUTION: new_list = old_list will NOT create a clone of the list!
# Instead it will just create a VIEW of the original list, and operating on the "new list" will similarly operate on the original list!
In [63]: list_x_false_clone = list_x
In [64]: list_x_false_clone
Out[64]: [1, 2, 3, 4]
In [65]: list_x_false_clone.pop()
Out[65]: 4
In [66]: list_x # list_x was affected by operating on list_x_false_clone, which is just a view of list_x
Out[66]: [1, 2, 3]
In [37]: list_x = [1,2,3,4]
In [61]: list_x_correct_clone = list_x[:] # [:] is the list clone syntax
In [62]: list_x_correct_clone
Out[62]: [1, 2, 3, 4]
In [70]: for item in list_x:
...: list_x_correct_clone.remove(item)
...: print(list_x_correct_clone)
...:
[2, 3, 4]
[3, 4]
[4]
[]
In [50]: list_x_correct_clone
Out[50]: []
In [49]: list_x # list_x_correct_clone is empty and list_x is unaffected
Out[49]: [1, 2, 3, 4]
# It is sometimes preferable to alter a list using the indexing approach instead of the item assignment approach
In [61]: list_x_correct_clone = list_x[:]
In [82]: for indexHAHA in range(len(list_x)): # South Sea Deckhand, anyone?
...: list_x_clone.remove(list_x[indexHAHA])
...: print(list_x_clone)
...:
[2, 3, 4]
[3, 4]
[4]
[]
# Loops are also useful for accumulating output into a new list
In [16]: list_x_sq = []
In [104]: for i in range(len(list_x)):
...: list_x_sq.append(list_x[i]**2) # Python uses ** for exponentiation
...: print(list_x_sq)
...:
[1]
[1, 4]
[1, 4, 9]
[1, 4, 9, 16]
In [112]: list_x_sq_strs = []
In [113]: for i in range(len(list_x)):
...: list_x_sq_strs.append('The value of {0} squared is {1}!'.format(list_x[i], list_x[i]**2))
...: print(list_x_sq_strs)
['The value of 1 squared is 1!', 'The value of 2 squared is 4!', 'The value of 3 squared is 9!', 'The value of 4 squared is 16!']
# Note the print statement above is not indented so it only prints once after the loop has finished
# Loops can be exited from after meeting a specific condition (this can help improve average program runtime)
# This can be done using the "break" keyword, which will exit out of the CURRENT loop
In [100]: counter = 0
...: for item in range(len(list_x)):
...: counter += 1 # using += is a shortcut for counter = counter + 1
...: if list_x[item] <= 2:
...: continue # the continue keyword sends you directly to the next iteration of the current loop
...: else:
...: break
...: print('Number of times passing through loop: {}'.format(counter))
Number of times passing through loop: 3
# In the example above, counter increments when item = 1, 2, 3, and then exits the loop when item = 3
In [101]: counter = 0
...: for item in range(len(list_x)):
...: if list_x[item] <= 2:
...: pass # the pass keyword exits the if-then statement and continues with the current loop iteration
...: else:
...: break
...: counter += 1
...: print('Number of times passing through loop: {}'.format(counter))
Number of times passing through loop: 2
# In the example above, counter increments when item = 1, 2, and then exits the loop when item = 3
# Although the loop iterated 3 times, counter was only incremented twice with the use of break
In [102]: counter = 0
...: for item in range(len(list_x)):
...: if list_x[item] <= 2:
...: continue
...: else:
...: break
...: counter += 1
...: print('Number of times passing through loop: {}'.format(counter))
Number of times passing through loop: 0
# In the example above, counter never increments because the loop moves to the next loop iteration when item = 1,2 and exits the loop when item = 3
# NOTE: if you break out of an inner loop within an outer loop, the outer loop will continue to the next iteration and may re-enter the inner loop!
# There are other flow control strategies you should consider, such as breaking using if-then statements while outside the current loop based on variables meeting certain conditions inside the current loop
# For more reference, see https://docs.python.org/3/tutorial/controlflow.html
In [120]: list_of_lists = [[1,2,3], [5,6,7], [8,9,10]]
...: breaker = 0
...: for x in range(len(list_of_lists)): # length 3
...: list_sum = 0 # reset the list sum when moving to a new list in list_of_lists
...: for y in range(len(list_of_lists[x])): # also length 3
...: print(list_of_lists[x][y]) # print the current item in the list within list_of_lists
...: list_sum += list_of_lists[x][y]
...: if list_sum > 10: # if the running sum in the list within list_of_lists > 10, set breaker to 1
...: breaker = 1
...: if breaker == 1: # after running through the current list within list_of_lists, test value of breaker to break or not from the outer-most for loop
...: break
...:
1
2
3
5
6
7
# In the example above, even though list_sum > 10 after 5,6 in [5,6,7], the break does not occur until after the entire inner loop finishes
# Instead of using a for loop with an iterable, WHILE loops check the truth of a CONDITION on every iteration. If true, re-enter the loop, if false, exit the loop
# Below is an example of a while loop that does NOT result in output
In [125]: for i in range(len(list_x)):
...: while list_x[i] <= 2:
...: list_x_sq_strs.append('The value of {0} squared is {1}!'.format(list_x[i], list_x[i]**2))
...: print(list_x_sq_strs)
# There is no output because the while loop never exits
# Instead it gets stuck at i=0 (when list_x[0] is 1) because i does not change inside the while loop (so list_x[i] <= 2 is ALWAYS True) and continues forever
# To break out of a while loop use a value that gets tested at each iteration and incremented or changed from inside the loop
In [143]: counter = 0
...: list_x_sq_strs = []
...: while list_x[counter] <= 2:
...: list_x_sq_strs.append('The value of {0} squared is {1}!'.format(list_x[counter], list_x[counter]**2))
...: counter += 1
...: print(list_x_sq_strs)
['The value of 1 squared is 1!', 'The value of 2 squared is 4!']
# Using a while loop with breaks can also be effective
In [69]: list_x_sq_strs = []
...: counter = 0
...:
...: while True: # this loop condition is set to always be True, and so it will continue forever until there is a break from within
...: if list_x[counter] <= 2:
...: list_x_sq_strs.append('The value of {0} squared is {1}!'.format(list_x[counter], list_x[counter]**2))
...: else:
...: break
...: counter += 1
...: print(list_x_sq_strs)
...: print('Number of times passing through loop: {}'.format(counter))
['The value of 1 squared is 1!', 'The value of 2 squared is 4!']
Number of times passing through loop: 2
In [69]: list_x_sq_strs = []
...: counter = 0
...: breaker = 0
...:
...: while breaker == 0:
...: if list_x[counter] <= 2:
...: list_x_sq_strs.append('The value of {0} squared is {1}!'.format(list_x[counter], list_x[counter]**2))
...: else:
...: breaker = 1
...: counter += 1
...: print(list_x_sq_strs)
...: print('Number of times passing through loop: {}'.format(counter))
['The value of 1 squared is 1!', 'The value of 2 squared is 4!']
Number of times passing through loop: 3
# There is a difference between the two implementations above
# The first immediately breaks out of the while loop during the if-then statement
# The second waits until the current iteration of the loop finishes (incrementing counter by 1) and then exists the loop after testing the value of breaker at the while loop
# Here's an example of a loop that will produce an error
In [154]: list_x = [1,2,3,4]
In [155]: list_y = [1,2,3,4,5]
In [157]: for index in range(len(list_y)):
...: print(list_x[index] + list_y[index])
2
4
6
8
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-157-d5a388fcd7ac> in <module>()
1 for index in range(len(list_y)):
----> 2 print(list_x[index] + list_y[index])
IndexError: list index out of range
# An error occurs because the iteration count is built using list_y's index and there was no corresponding list_x[4]
# The TRY and EXCEPT keywords can be used to tell Python what to do when an error occurs
In [158]: for index in range(len(list_y)):
...: try:
...: print(list_x[index] + list_y[index])
...: except:
...: print('Something went wrong!')
...: pass
...:
2
4
6
8
Something went wrong!
# Lists can be built with for loops using list comprehensions, which can offer readability and performance benefits
In [159]: [x**2 for x in list_x]
Out[159]: [1, 4, 9, 16]
In [160]: [x**2 for x in list_x if x <= 2]
Out[160]: [1, 4]
# List comprehensions are read left to right: "for x in list_x: if x <= 2: append x**2 to the list"
# Python Functions take input arguments and returns outputs. The "def" keyword is used to define a function
In [161]: def RolandsFunc(x,y):
...: print('Processing multiplication with values {0} and {1}'.format(x,y))
...: return x*y
# NOTE a function will finish after a return statement; the return statement should thus be used at the end of the function (after any print statements, etc)
In [162]: value = RolandsFunc(2,3)
Processing multiplication with values 2 and 3
In [163]: value
Out[163]: 6
In [86]: type(RolandsFunc) # functions have their own data type
Out[86]: function
In [87]: LuckysFunc = RolandsFunc # you can assign functions to other variables
In [88]: LuckysFunc(2,3)
Out[88]: 6
# This session will not cover global vs. local variable scope, but by default any variables not passed into the function cannot be accessed from inside it
# Likewise, any variables defined inside the function cannot be accessed from outside it
# Functions can have default values for arguments that aren't necessary to provide, which is standard when functions can take many arguments or have multiple settings
# Default values must always appear last in the function arguments
In [164]: def powerfunc(x,n): # no default values
...: return x**n
In [165]: powerfunc(2,3)
Out[165]: 8
In [170]: def powerfunc(x,n=2): # here n defaults to 2 if omitted
...: return x**n
In [171]: powerfunc(2)
Out[171]: 4
# Functional programming often uses recursion (functions calling themselves inside the function)
In [185]: def factorial(x):
...: if x >= 1:
...: return x*factorial(x-1)
...: else:
...: return 1 # recursive calls must have a terminal condition in order to be evaluated
In [186]: factorial(4)
Out[186]: 24
In [37]: list_x = [1,2,3,4]
In [61]: def sum_sq(list_x):
...: if len(list_x) > 1:
...: return list_x[0]**2 + sum_sq(list_x[1:])
...: elif len(list_x) == 1:
...: return list_x[0]**2
In [62]: sum_sq(list_x)
Out[62]: 30
# Note this could have also been accomplished using for loops... there are generally many ways to accomplish the same result in Python
# Anonymous functions use lambda notation as a shortcut for building functions -- also refered to as "synctactic sugar"
# Think of this as using shorthand to create an f(x) on the spot which does not need to be preserved in memory after it is used
In [64]: (lambda x: x**2)(2) # (lambda x: x**s) plays the role of f, translating to f(2)
Out[64]: 4
# Lambdas can be used to easily pass functions as arguments to other functions
In [37]: list_x = [1,2,3,4]
In [71]: def sum_f(list_x,f):
...: if len(list_x) > 1:
...: return f(list_x[0]) + sum_f(list_x[1:],f)
...: elif len(list_x) == 1:
...: return f(list_x[0])
In [73]: sum_power(list_x,lambda x: x**3)
Out[73]: 100
# There are some additional list methods: map, filter, reduce, that can be applied very quickly using lambdas; of these MAP is probably the most useful
# Map applies a function to every item in a list (assuming it is possible to do so) and returns a "map object" that can be converted into a list
In [83]: list_x
Out[83]: [1, 2, 3, 4]
In [84]: list(map(lambda s: s**2, list_x))
Out[84]: [1, 4, 9, 16]
# Filter returns a list items for which the function application evaluates to TRUE
In [86]: list(filter(lambda s: s%2 == 0, list_x))
Out[86]: [2, 4]
# Reduce applies a function to a sequence of list items and aggregates using a rolling computation
In [98]: product = reduce(lambda s,z: s*z, list_x)
In [99]: product
Out[99]: 24
# product is the evaluation of ((list_x[0]*list_x[1])*list_x[2])*list_x[3]
# Lastly, functions can include comments or docstrings with important information and can be referenced using the help(function) command
In [125]: def new_func(x):
...: ''' this is the docstring '''
...: return x
In [126]: help(new_func)
Help on function new_func in module __main__:
new_func(x)
this is the docstring
##########################
### SECTION 1 EXERCISE ###
##########################
# 30 MINUTES
(1) Write a Python function called connect_db that accepts one argument with default value 'td'
The function should have the following properties:
- A docstring that contains the text 'This is the docstring for connect_db'
- If the argument passed to the function is 'td', return an object with two variables packed into it, con and cur, with values 'td_con' and 'td_cur'
- If the argument passed to the function is 'hive', return an object with two variables packed into it, con and cur, with values 'hive_con' and 'hive_cur'
- A print statement that displays 'Connection to [DATABASE] Successful!', depending on which argument was passed to the connection
- Test the function with "connect_db('hive')" and "connect_db()"
(2) Write a Python function called join_str_args that accepts two arguments (both of these arguments will be lists)
The function should have the following properties
- Takes two list of integers (e.g. [1,2,3,4] and [5,6,7,8,9]) and uses the map() function to create 2 new lists of strings (e.g. ['1','2','3','4'], ['5','6','7','8','9'])
- Loops over an iterable with length of the longest of the two lists and returns a new combined list str_list that looks like ['1 5','2 6','3 7',...] (hint: use String Interpolation)
- If an error is encountered during the construction of str_list, print 'Error due to list length mismatch!'
- Test your script with join_str_args([1,2,3,4], [5,6,7,8,9])
#################
### SECTION 2 ###
#################
# 120 MINUTES
####################################
### PANDAS SERIES AND DATAFRAMES ###
####################################
In [15]: import pandas as pd
# A pandas SERIES is a column of data and can be constructed using either lists or dictionaries
In [40]: pd.Series({'jasper' : 29, 'roland' : 32, 'broesch': 32, 'minh' : 35}, name='age') # Series have an optional name argument (useful for assigning column names)
Out[40]:
broesch 32
jasper 29
minh 35
roland 32
Name: age, dtype: int64
# Series that are constructed from Dictionaries will also be unordered
# However, the Series will use an order if it gets passed to the index argument
In [41]: pd.Series({'jasper' : 29, 'roland' : 32, 'broesch': 32, 'minh' : 35}, index = ['jasper', 'roland', 'minh', 'broesch'], name='age')
Out[41]:
jasper 29
roland 32
minh 35
broesch 32
Name: age, dtype: int64
In [26]: pd.Series({'jasper' : 29, 'roland' : 32, 'broesch': 32, 'minh' : 35}, index = ['jasper', 'roland', 'jasper'], name='age')
Out[26]:
jasper 29
roland 32
jasper 29
Name: age, dtype: int64
In [12]: pd.Series([29, 32, 32, 35], index=['jasper', 'roland', 'broesch', 'minh'])
Out[12]:
jasper 29
roland 32
broesch 32
minh 35
dtype: int64
In [27]: pd.Series([[29,29], [32, 32], [32, 32], [35, 35]], index=['jasper', 'roland', 'broesch', 'minh']) # lists are passed as the Series data
Out[27]:
jasper [29, 29]
roland [32, 32]
broesch [32, 32]
minh [35, 35]
dtype: object
In [27]: pd.Series([[29,29], [32, 32], [32, 32], [35, 35]]) # no index passed to Series results in default range index being used
Out[27]:
0 [29, 29]
1 [32, 32]
2 [32, 32]
3 [35, 35]
dtype: object
# Take note of the data types the Series is storing
# dtypes can be checked using Series.dtype and DataFrame.dtypes (each column in a DataFrame and the index object will have a dtype)
In [25]: pd.Series([29, 32, 32, [35, 36]], index=['jasper', 'roland', 'broesch', 'minh']).dtype
Out[25]: dtype('O')
# 'O' stands for object, the designation for mixed types (which include strings)
# NOTE pay careful attention to dtypes as they can suggest when Pandas does not understand how to type the data, which can lead to undesirable behavior
# Pandas uses "duck typing", i.e. "if it looks like a duck and quacks like a duck, it's probably a duck"; it will try to figure out the type
# There are a few different ways to construct Pandas DATAFRAMES using lists, dictionaries, or Series
# When passing a single list or Series to a DataFrame, the data will be interpreted as column data
# When passing multiple lists or Series to a DataFrame, the data will be interpreted as row data
# When passing a single or multiple dictionaries to a DataFrame, the data will be interpreted as row data; however a single Dictionary can be very flexible!
# This can be a little confusing so play around with DataFrame construction to get comfortable with them
In [20]: pd.DataFrame(pd.Series({'jasper' : 29, 'roland' : 32, 'broesch': 32, 'minh' : 35}, name = 'age')) # single Series
Out[20]:
age
broesch 32
jasper 29
minh 35
roland 32
In [21]: pd.DataFrame([29, 32, 32, 35], columns = ['age'], index = ['jasper', 'roland', 'broesch', 'minh']) # single list
Out[21]:
age
jasper 29
roland 32
broesch 32
minh 35
In [19]: pd.DataFrame({'jasper' : 29, 'roland' : 32, 'broesch': 32, 'minh' : 35}, index = ['age']) # single Dictionary
Out[19]:
broesch jasper minh roland
age 32 29 35 32
In [29]: pd.DataFrame({'age':{'jasper':29,'roland':32,'broesch':32,'minh':35}}) # single Dictionary
Out[29]:
age
broesch 32
jasper 29
minh 35
roland 32
In [24]: pd.DataFrame({'age':[29,32,32,35],'department':['bnet','tox','bnet','esports']}, index=['jasper','roland','broesch','minh']) # single Dictionary
Out[24]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
In [24]: pd.DataFrame({'age':[29,32,32,35],'department':['bnet','tox','bnet','esports']}, index=['jasper','roland','broesch','minh']) # single Dictionary
Out[24]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
In [24]: pd.DataFrame({'age':{'jasper':29,'roland':32,'broesch':32,'minh':35},'department':{'roland':'tox','broesch':'bnet','minh':'esports','jasper':'bnet'}}, index=['jasper','roland','broesch','minh']) # single Dictionary
Out[24]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
In [30]: pd.DataFrame({'jasper':{'age':29,'department':'bnet'}, 'roland':{'age':32,'department':'tox'}}) # single Dictionary
Out[30]:
jasper roland
age 29 32
department bnet tox
In [23]: pd.DataFrame([[29, 32, 32, 35], ['m', 'm', 'm', 'm']], columns = ['jasper', 'roland', 'broesch', 'minh'], index = ['age', 'sex']) # multiple lists
Out[23]:
jasper roland broesch minh
age 29 32 32 35
sex m m m m
# DataFrames can be transposed using df.T
In [23]: pd.DataFrame([[29, 32, 32, 35], ['m', 'm', 'm', 'm']], columns = ['jasper', 'roland', 'broesch', 'minh'], index = ['age', 'sex']).T # multiple lists
Out[32]:
age sex
jasper 29 m
roland 32 m
broesch 32 m
minh 35 m
# The above transpose is equivalent to the formulation below
In [31]: pd.DataFrame([[29,'m'], [32,'m'], [32,'m'], [35,'m']], columns = ['age','sex'], index = ['jasper', 'roland', 'broesch', 'minh']) # multiple lists
Out[31]:
age sex
jasper 29 m
roland 32 m
broesch 32 m
minh 35 m
In [100]: pd.DataFrame([pd.Series({'age':29,'sex':'m'},name='jasper'), pd.Series({'age':32,'sex':'m'},name='roland'), pd.Series({'age':32,'sex':'m'},name='broesch'), pd.Series({'age':35,'sex':'m'},name='minh')])
# multiple Series
Out[100]:
age sex
jasper 29 m
roland 32 m
broesch 32 m
minh 35 m
In [30]: pd.DataFrame([{'roland' : 32, 'jasper' : 29, 'minh' : 35, 'broesch' : 32}, {'roland' : 'm', 'jasper' : 'm', 'broesch' : 'm', 'minh': 'm'}], index = ['age', 'sex'])
# multiple Dictionaries
Out[30]:
broesch jasper minh roland
age 32 29 35 32
sex m m m m
# DataFrames can also be built from external sources, including read_csv(), read_excel(), and read_sql(); Python can also connect to APIs
# There are many arguments that can be passed to these functions, such as whether to include a header, how many lines to skip, etc; see documentation for more details
In [20]: df = pd.read_excel('C:\\users\\rheinze\\desktop\\test_excel.xlsx')
In [21]: df
Out[21]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
In [46]: from roland_toolbox import connect_db, query_db
In [47]: td = connect_db('td')
In [48]: df2 = query_db(td, 'select * from dlab_rheinze.wow_free_game_time_times sample 1')
In [49]: df2
Out[49]:
agent_key issue_key created_at closed_at gm_time
0 0.25345 2.599012 2017-10-08 11:51:08 2017-10-08 11:51:08 0.0
#########################################
### FILTERING AND QUERYING DATAFRAMES ###
#########################################
In [53]: df
Out[53]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
# To gather some quick information on a df use descriptive methods such as .shape, .index, .columns, .dtypes, and .describe()
In [58]: df.shape
Out[58]: (4, 2)
In [59]: df.index
Out[59]: Index(['jasper', 'roland', 'broesch', 'minh'], dtype='object') # Index is its own type of object in Pandas
In [60]: df.columns
Out[60]: Index(['age', 'department'], dtype='object') # columns also use Index objects; MultiIndex objects are used to create hierarchies on either index or columns
In [61]: df.dtypes
Out[61]:
age int64
department object
dtype: object
In [11]: df.describe()
Out[11]:
age
count 4.00000
mean 32.00000
std 2.44949
min 29.00000
25% 31.25000
50% 32.00000
75% 32.75000
max 35.00000
# To filter columns, pass the df a single column name using the attribute operator . or a list of column names using the indexing operator []
In [20]: df.age
Out[20]:
jasper 29
roland 32
broesch 32
minh 35
Name: age, dtype: int64
In [20]: df['age']
Out[20]:
jasper 29
roland 32
broesch 32
minh 35
Name: age, dtype: int64
In [54]: df[['age','department']]
Out[54]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
# To filter rows, first create a BOOLEAN MASK to calculate the truth of a set of conditions for each index
# The boolean mask is a Series with True/False labels for each index
In [28]: df['age']==32
Out[28]:
jasper False
roland True
broesch True
minh False
Name: age, dtype: bool
# Then pass the boolean mask to the df
In [62]: df[df['age']==32]
Out[62]:
age department
roland 32 tox
broesch 32 bnet
# Use other operators (such as ~, >, <, !=) or methods (such as .isin(), .contains(), isnull()) to modify the conditions of the boolean mask
In [30]: df[df['age'].isin([32,35])]
Out[30]:
age dpt
roland 32 tox
broesch 32 tox
minh 35 esports
In [69]: df[~(df['age'] < 34)] # as a best practice always encapsulate conditions in parentheses
Out[69]:
age department
minh 35 esports
In [67]: df[df['department'].str.contains('o')] # when using string methods you must generally pass the .str accessor to a Series
Out[67]:
age department
roland 32 tox
minh 35 esports
In [65]: df[df['age'].isnull()] # Note NaN is not the same as None, more reference at https://stackoverflow.com/questions/17534106/what-is-the-difference-between-nan-and-none
Out[65]:
Empty DataFrame
Columns: [age, department]
Index: []
# Boolean masks can be created using multiple conditions; the operators for "and" and "or" are & and | respectively
In [32]: df[(~df['age'].isin([32])) & (df['dpt']=='bnet')]
Out[32]:
age dpt
jasper 29 bnet
In [33]: df[(~df['age'].isin([32])) & ~(df['dpt']=='bnet')]
Out[33]:
age dpt
minh 35 esports
In [34]: df[(~df['age'].isin([32])) | ~(df['dpt']=='bnet')]
Out[34]:
age dpt
jasper 29 bnet
roland 32 tox
broesch 32 tox
minh 35 esports
# At this point, consider querying only a specific column or set of columns using what is called "chain indexing"
In [71]: In [33]: df[(~df['age'].isin([32])) & ~(df['department']=='bnet')]['age']
Out[71]:
minh 35
Name: age, dtype: int64
# While this can still work depending on the task, it is generally considered BAD PRACTICE to chain like this!
# *** Rule of Thumb: never use back-to-back brackets! ][ ***
# For more reference see the first section of https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
# The problem comes down to unpredictable behavior about whether the object returned is a copy or a view of the df
# Instead there are two better ways to query dfs, .loc and .iloc attributes
# Try to remember .loc as "name-based" and .iloc as "index-based" querying
In [73]: df.loc['roland'] # name-based querying on the index
Out[73]:
age 32
department tox
Name: roland, dtype: object
In [74]: df.iloc['roland'] # attempting to pass a name to an index-based query results in an error
# TypeError: cannot do positional indexing on class pandas.core.indexes.base.Index with these indexers [roland] of class str
In [75]: df.iloc[1] # index location 1 is the same as name-based location 'roland'
Out[75]:
age 32
department tox
Name: roland, dtype: object
# The first argument of the .loc and .iloc methods is the rows index and the second argument is the columns index (not necessary to include a columns index)
# Use boolean masks to pass conditions to the indices/rows and also pass a list of columns to return
# Note how passing lists vs. singular values can lead to different results of DataFrame vs. Series... this can be confusing!
# Below are various examples for reference
In [307]: df.loc['roland'] # Series
Out[307]:
age 32
department tox
Name: roland, dtype: object # declaration of Series name and dtype
In [312]: df.loc[['roland']] # DataFrame
Out[312]:
age department
roland 32 tox
In [322]: df.loc[['roland'],'age'] # Series
Out[322]:
roland 32
Name: age, dtype: int64
In [324]: df.loc['roland',['age']] # Series, but with a different index and name!
Out[324]:
age 32
Name: roland, dtype: object
In [323]: df.loc[['roland'],['age']] # DataFrame
Out[323]:
age
roland 32
In [313]: df.loc['roland','age'] # scalar :)
Out[313]: 32
In [156]: df.loc[:] # the : operator returns a list of indices, DataFrame
Out[156]:
age department
jasper 29 bnet
roland 32 tox
broesch 32 bnet
minh 35 esports
In [155]: df.loc[:,['age']] # DataFrame
Out[155]:
age
jasper 29
roland 32
broesch 32
minh 35
In [157]: df.loc[:,'age'] # Series
Out[157]:
jasper 29
roland 32
broesch 32
minh 35
Name: age, dtype: int64
In [140]: df.loc[df['age']==32,['age']] # boolean mask returns a list with multiple indices, DataFrame
Out[140]:
age
roland 32
broesch 32
In [144]: df.loc[df['age']==32,'age'] # Series
Out[144]:
roland 32
broesch 32
Name: age, dtype: int64
# To return a value from a SERIES with a single entry use the .item() method; note if the query returns multiple values this will generate an error
In [146]: df.loc[df['age']==32,'age'].item() # Series with multiple values
# ValueError: can only convert an array of size 1 to a Python scalar
In [147]: df.loc[df['age']==35,'age'].item() # Series with single value
Out[147]: 35
############################
### MODIFYING DATAFRAMES ###
############################
# To create a copy of a df slice use the .copy() method
In [81]: df2 = df.loc['roland'].copy()
In [81]: df2
In [82]: df2
Out[82]:
age 32
department tox
Name: roland, dtype: object
# df slices can be modified using loc/iloc and new columns can be defined directly using scalars, lists, existing columns, or Series
In [154]: df2.loc['roland','age'] = 33
Out[82]:
age 33
department tox
Name: roland, dtype: object
In [43]: df['tenure'] = 0
In [44]: df
Out[44]:
age department tenure
jasper 29 bnet 0
roland 32 tox 0
broesch 32 tox 0
minh 35 esports 0
In [50]: df2['tenure'] = [1,1,2,10]
In [51]: df2
Out[51]:
age department tenure
jasper 29 bnet 1
roland 32 tox 1
broesch 32 tox 2
minh 35 esports 10
In [88]: df['tenure'] = df['age']/2
In [89]: df
Out[89]:
age department tenure
jasper 29 bnet 14.5
roland 32 tox 16.0
broesch 32 bnet 16.0
minh 35 esports 17.5
In [94]: df['tenure'] = pd.Series({'roland': 2, 'jasper' : 0, 'broesch' : 3, 'minh' : 10})
In [95]: df
Out[95]:
age department tenure
jasper 29 bnet 0
roland 32 tox 2
broesch 32 bnet 3
minh 35 esports 10
# Add rows to the df using the .append() method
In [241]: df2 = df.copy()
In [251]: df2.append(pd.Series({'age':26,'sex':'male'},name='kier')) # unassigned data will be filled with NaNs
Out[251]:
age department tenure sex
jasper 29 bnet 0.0 NaN
roland 32 tox 2.0 NaN
broesch 32 bnet 3.0 NaN
minh 35 esports 10.0 NaN
kier 26 NaN NaN male
# To rename a column, use the .rename() method and assign a dictionary to the "columns" argument
In [96]: df.rename(columns={'tenure' : 'years'})
Out[96]:
age department years
jasper 29 bnet 0
roland 32 tox 2
broesch 32 bnet 3
minh 35 esports 10
In [97]: df
Out[97]:
age department tenure
jasper 29 bnet 0
roland 32 tox 2
broesch 32 bnet 3
minh 35 esports 10
# NOTE *** sometimes calling a method on a df will not change the original df and will simply output a copy of the df with the changes applied ***
# To apply changes to the original df, either assign the modified df to a new df or use the "inplace" argument within the method
In [98]: df = df.rename(columns={'tenure' : 'years'})
In [99]: df
Out[99]:
age department years
jasper 29 bnet 0
roland 32 tox 2
broesch 32 bnet 3
minh 35 esports 10
In [100]: df.rename(columns={'years' : 'tenure'}, inplace=True)
In [101]: df
Out[101]:
age department tenure
jasper 29 bnet 0
roland 32 tox 2
broesch 32 bnet 3
minh 35 esports 10
# To rename a row, use the "index" argument instead of the "columns" argument
In [164]: df2 = df.rename(index={'jasper' : 'kush'})
In [165]: df2
Out[165]:
age department tenure
kush 29 bnet 0
roland 32 tox 2
broesch 32 bnet 3
minh 35 esports 10
# To delete columns use the .drop() method with the "columns" argument
In [102]: df2 = df.drop(columns=['department','tenure'])
In [103]: df2
Out[103]:
age
jasper 29
roland 32
broesch 32
minh 35
# To delete rows pass the indices to the .drop() method (with or without the "index" argument), or alternatively use a boolean mask to create a new df!
In [104]: df2 = df.drop(['roland'])
In [105]: df2
Out[105]:
age department tenure
jasper 29 bnet 0
broesch 32 bnet 3
minh 35 esports 10
In [166]: df2 = df.drop(index=['roland'])
In [167]: df2
Out[167]:
age department tenure
jasper 29 bnet 0
broesch 32 bnet 3
minh 35 esports 10
In [111]: df2 = df.loc[~(df.index=='roland')]
In [112]: df2
Out[112]:
age department tenure
jasper 29 bnet 0
broesch 32 bnet 3
minh 35 esports 10
In [115]: df2 = df.drop(df[df['department']=='bnet'].index)
In [116]: df2
Out[116]:
age department tenure
roland 32 tox 2
minh 35 esports 10
In [117]: df2 = df[~(df['department']=='bnet')] # no .drop() method, only using a boolean mask
In [118]: df2
Out[118]:
age department tenure
roland 32 tox 2
minh 35 esports 10
# Drop duplicates by passing a list of columns to the .drop_duplicates() method
In [95]: df2.drop_duplicates(['department'])
Out[95]:
age department
jasper 29 bnet
roland 32 tox
minh 35 esports
In [96]: df2.drop_duplicates(['department'],keep='last')
Out[96]:
age department
roland 32 tox
broesch 32 bnet
minh 35 esports
# Use the .dropna() method as a shortcut to remove subsets of the df with missing values (instead of using boolean masks)
# By default, this method applies to rows (axis=0) but can also apply to columns (axis=1)
# By default, this method drops rows/columns with 'any' missing values but can also drop rows/columns with 'all' missing values using the 'how' argument
In [254]: import numpy as np
In [219]: df2 = df.copy().append(pd.Series(name='kier'))
In [231]: df2['sex'] = np.nan
In [220]: df2
Out[233]:
age department tenure sex
jasper 29.0 bnet 0.0 NaN
roland 32.0 tox 2.0 NaN
broesch 32.0 bnet 3.0 NaN
minh 35.0 esports 10.0 NaN
kier NaN NaN NaN NaN
In [223]: df2.dropna() # this drops rows with any missing values (which is all rows)
Out[234]:
Empty DataFrame
Columns: [age, department, tenure, sex]
Index: []
In [237]: df2.dropna(how='all') # this drops rows with all values missing (which is only kier)
Out[237]:
age department tenure sex
jasper 29.0 bnet 0.0 NaN
roland 32.0 tox 2.0 NaN
broesch 32.0 bnet 3.0 NaN
minh 35.0 esports 10.0 NaN
In [235]: df2.dropna(axis=1) # this drops columns with any missing values (which is all columns because kier row is missing all values)
Out[235]:
Empty DataFrame
Columns: []
Index: [jasper, roland, broesch, minh, kier]
In [238]: df2.dropna(axis=1, how='all') # this drops columns with all values missing (which is only sex)
Out[238]:
age department tenure
jasper 29.0 bnet 0.0
roland 32.0 tox 2.0
broesch 32.0 bnet 3.0
minh 35.0 esports 10.0
kier NaN NaN NaN
In [266]: df2.dropna(subset=['tenure','sex'],how='any') # drop rows where either 'tenure' or 'sex' have any missing values (which is all rows since sex has all values missing)
Out[266]:
Empty DataFrame
Columns: [age, department, tenure, sex]
Index: []
In [265]: df2.dropna(subset=['tenure','sex'],how='all') # drop rows where both 'tenure' and 'sex' have all values missing (which is only kier)
Out[265]:
age department tenure sex
jasper 29.0 bnet 0.0 NaN
roland 32.0 tox 2.0 NaN
broesch 32.0 bnet 3.0 NaN
minh 35.0 esports 10.0 NaN
In [270]: df2.dropna(axis=1,subset=['jasper','kier']) # drop columns where either jasper or kier have any missing values (which is all columns since kier has all values missing)
Out[270]:
Empty DataFrame
Columns: []
Index: [jasper, roland, broesch, minh, kier]
In [271]: df2.dropna(axis=1,subset=['jasper','kier'],how='all') # drop columns where both jasper and kier have all values missing (which is only sex)
Out[271]:
age department tenure
jasper 29.0 bnet 0.0
roland 32.0 tox 2.0
broesch 32.0 bnet 3.0
minh 35.0 esports 10.0
kier NaN NaN NaN
# Use .fillna() to fill missing values instead of dropping them; fillna() offers both forward and back fill methods, which are useful for time series data
In [285]: df2.fillna('filled') # applies to all missing values
Out[285]:
age department tenure sex
jasper 29 bnet 0 filled
roland 32 tox 2 filled
broesch 32 bnet 3 filled
minh 35 esports 10 filled
kier filled filled filled filled
In [278]: df2['sex'] = df2['sex'].fillna('male') # queries the 'sex' column, fills missing values with 'male' and replaces the existing 'sex' column in df2 with the filled Series
In [279]: df2
Out[279]:
age department tenure sex
jasper 29.0 bnet 0.0 male
roland 32.0 tox 2.0 male
broesch 32.0 bnet 3.0 male
minh 35.0 esports 10.0 male
kier NaN NaN NaN male
In [302]: df2.fillna({'age' : 'who', 'department' : 'wha', 'tenure' : '?', 'sex' : 'whoa there...'}) # pass a dictionary of each column and its fill value
Out[302]:
age department tenure sex
jasper 29 bnet 0 whoa there...
roland 32 tox 2 whoa there...
broesch 32 bnet 3 whoa there...
minh 35 esports 10 whoa there...
kier who wha ? whoa there...
In [293]: df2.loc['roland','sex'] = 'male'
In [294]: df2.loc['minh','sex'] = 'cooler male'
In [295]: df2
Out[295]:
age department tenure sex
jasper 29.0 bnet 0.0 NaN
roland 32.0 tox 2.0 male
broesch 32.0 bnet 3.0 NaN
minh 35.0 esports 10.0 cooler male
kier NaN NaN NaN NaN
In [296]: df2.fillna(method='ffill') # fills using the previous non-null value, if it exists
Out[296]:
age department tenure sex
jasper 29.0 bnet 0.0 NaN # no previous value
roland 32.0 tox 2.0 male
broesch 32.0 bnet 3.0 male # filled by roland
minh 35.0 esports 10.0 cooler male
kier 35.0 esports 10.0 cooler male # filled by minh
In [297]: df2.fillna(method='bfill') # fills using the next non-null value, if it exists
Out[297]:
age department tenure sex
jasper 29.0 bnet 0.0 male # filled by roland
roland 32.0 tox 2.0 male
broesch 32.0 bnet 3.0 cooler male # filled by minh
minh 35.0 esports 10.0 cooler male
kier NaN NaN NaN NaN # no value after
# To change the columns of data used as the index of the df use the .set_index() method
# This can be useful to assign new column data to a df with a Series
In [170]: df.set_index(pd.Series(['a','b','c','d']))
Out[170]:
age department tenure
a 29 bnet 0
b 32 tox 2
c 32 bnet 3
d 35 esports 10
# Instead of directly replacing the current index, append another level to the index (creating a MultiIndex) using the "append" argument
In [183]: df2 = df.set_index(pd.Series(['a','b','c','d']), append=True) # indexes with multiple levels are called MultiIndex
In [185]: df2
Out[185]:
age department tenure
jasper a 29 bnet 0
roland b 32 tox 2
broesch c 32 bnet 3
minh d 35 esports 10
In [186]: df2 = df.set_index(['department', 'tenure'])
Out[190]:
age
department tenure
bnet 0 29
tox 2 32
bnet 3 32
esports 10 35
In [191]: df2.index
Out[191]:
MultiIndex(levels=[['bnet', 'esports', 'tox'], [0, 2, 3, 10]],
labels=[[0, 2, 0, 1], [0, 1, 2, 3]],
names=['department', 'tenure'])
# Resetting the index of a df can be useful when indices are duplicated, such as after concatenating multiple dfs together
# However the current index can hold valuable data, so it is generally desirable to rename and write it to the df as a new column
# .reset_index() by default promotes the existing index into a new column and applies a new range index to the df
In [211]: df2 = df.copy()
In [211]: df2.index.name = 'emp'
In [204]: df2.reset_index()
Out[204]:
emp age department tenure
0 jasper 29 bnet 0
1 roland 32 tox 2
2 broesch 32 bnet 3
3 minh 35 esports 10
# Group By can sometimes result in indices with tuples and needs to be converted into MultiIndex before being promoted into columns using .reset_index()
# df.index = pd.MultiIndex.from_tuples(df.index)
# df.reset_index(level=[0,1]) 0 is the outer-most index in either a row or column MultiIndex
###################
### AGGREGATION ###
###################
# For additional reference on concat and merge see https://pandas.pydata.org/pandas-docs/stable/merging.html
# For additional reference on aggregation see https://pandas.pydata.org/pandas-docs/stable/groupby.html
# .append() was introduced earlier as a method to add rows to a df, and is a shortcut for .concat()
# .concat() can append either rows or columns to a df
# .merge() is the analog to SQL join
In [69]: df3 = pd.DataFrame({'age':{'jasper':80,'n':5,'s':12},'dpt':{'jasper':None,'n':None,'s':None}},index=['jasper','n','s'])
In [69]: df4 = pd.concat([df2,df3], axis=0) # concat along rows
In [70]: df4
Out[70]:
age dpt
jasper 29 bnet
roland 32 tox
broesch 32 tox
minh 35 esports
jasper 80 None # duplicate index is allowed
n 5 None
s 12 None
In [71]: df4 = pd.concat([df2,df3],axis=1) # concat along columns
In [73]: df4
Out[73]:
age dpt age dpt
broesch 32.0 tox NaN NaN
jasper 29.0 bnet 80.0 NaN # jasper is the only row from df2 with data in the 'age' column
minh 35.0 esports NaN NaN
n NaN NaN 5.0 none
roland 32.0 tox NaN NaN
s NaN NaN 12.0 none
# concat is very useful for aggregating DataFrames using for loops
# MERGE
# Pandas features a wide range of general aggregation and window functions
In [75]: df2['age'].max()
Out[75]: 35
# These can be applied to columns of groupby sub-frames
In [76]: df2.groupby(['dpt'])['age'].agg('max')
Out[76]:
dpt
bnet 29
esports 35
tox 32
Name: age, dtype: int64
# Can Pass functions to Groupby to essentially create hash functions / similar to CASE in SQL
# Can also sequentially merge groupbys to the original data frame to concatenate levels of detail
# Merges follow the df.merge(df2, how, left, right) format, where how can be inner, left, right, outer, and left/right are left_index=True or right_on= list of columns depending on keys or columns are being joined on
# APPLY
###########################
### SECTION 2 EXERCISES ###
###########################
"""
40 MINUTES
(1) Write a function called connect_db that accepts a single argument with default value 'td'
The function should have the following properties:
- A docstring that states your name
- A print statement that displays your name using string interpolation
- If the argument passed to the function is 'hive', return a variable with two lists packed into it [1,2,3,4] and [5,6,7,8,9]
- If the argument passed to the function is 'td', return a list that uses an anonymous function to take sqrt of all the values in [1,2,3,4]
- Test your function with "connect_db('hive')" and "connect_db()"
In [142]: from math import sqrt
...: def connect_db(x='td'):
...: '''roland'''
...: print('{}'.format('roland'))
...: if x == 'hive':
...: return ([1,2,3,4],[5,6,7,8,9])
...: if x == 'td':
...: return list(map(lambda x: sqrt(x), [1,2,3,4]))
...:
(2) Write a script that does the following:
- Takes a list of lists of integers [[1,2,3,4],[5,6,7,8,9]] and creates 2 new lists where each list is a list of strings of those same integers
- Loops over an iterable with length of the longest list in the set and creates a new list str_list that looks like ['1 5','2 6','3 7',...]
- If an error is encountered, print 'Error due to list length mismatch!'
- Test your script with "str_list"
In [140]: list1 = [1,2,3,4]
...: list2 = [5,6,7,8,9]
...: list1 = list(map(lambda x: str(x),list1))
...: list2 = list(map(lambda x: str(x),list2))
...: str_list = []
...: for i in range(max(len(list1),len(list2))):
...: try:
...: str_list.append('{0} {1}'.format(list1[i],list2[i]))
...: except:
...: print('Error due to list length mismatch!')
"""
#################
### SECTION 3 ###
#################
# ROLAND_TOOLBOX
# The functions in roland_toolbox are shortcuts to improve data source connectivity and the ability to write tables from SQL queries and DataFrames
# These functions make heavy use of pyodbc connections, which include both a connection and a cursor object
def connect_db(db_name='td'):
"""
use format " conn_obj = connect_db(str) ", e.g. " hive = connect_db('hive') "
"""
print('CALLED CONNECT_DB FROM ROLAND_TOOLBOX')
if db_name == 'hive':
con = pyodbc.connect(dsn='{}'.format(os.environ.get('HIVE_DSN')), # os library calls system environment variable 'HIVE_DSN' which is my odbc connection name in Windows
trusted_connection='yes',
autocommit=True)
print('Connected to Hive!')
elif db_name == 'irvaag':
con = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}', # this connection string specifies everything directly instead of calling the odbc connection name
server='irvaag4003.corp.blizzard.net,54003',
database='salesforce',
trusted_connection='yes',
autocommit=True)
print('Connected to IRVAAG!')
elif db_name == 'td':
con = pyodbc.connect(dsn='{}'.format(os.environ.get('TD_DSN')), # odbc connection name
database='bidw',
autocommit=True)
print('Connected to Teradata!')
elif db_name == 'tox':
con = pyodbc.connect(driver='{MySQL ODBC 8.0 ANSI Driver}',
server='dev17-bi-toxicity.dev.cloud.blizzard.net',
port='3306',
database='toxic_db',
user='{%s}' % (os.environ.get('TOX_LOGIN')), # os library calls my logins and passwords
password='{%s}' % (os.environ.get('TOX_PASS')))
print('Connected to ToxOrNot!')
cur = con.cursor()
return con, cur
# query_db returns a df as a result of running query_str against src_obj
def query_db(src_obj, query_str):
print('CALLED QUERY_DB FROM ROLAND_TOOLBOX')
src_con, src_cur = src_obj
start_time = time.time() # counts time required for query execution
df = pd.read_sql(query_str, src_con)
end_time = time.time()
print('Successfully Ran Query in {} Minutes!'.format(round((end_time-start_time)/60, 1)))
return df
# write_table_from_query writes the output of query_str against src_obj to table in dst_obj with defined cols and types
def write_table_from_query(src_obj, dst_obj, query_str, table, cols, types, primary_index = None):
"""
this function writes single rows sequentially to a table
pass connect_db objects to src_obj and dst_obj
e.g. write_table_from_query(td, hive, ...)
pass column names and data types as lists of strings
e.g. write_table_from_query(..., ['name_col1', 'name_col2'], ['data_type_col1', 'data_type_col2'], ...)
primary_index is not required, but must be passed as a list of strings if included
"""
print('CALLED WRITE_TABLE_FROM_QUERY FROM ROLAND_TOOLBOX')
src_con, src_cur = src_obj
dst_con, dst_cur = dst_obj
cols_str = ', '.join(map(lambda x: str(x), cols)) # create a single string of columns from the list
cols_types_str = ''
for element in range(len(cols)):
cols_types_str = cols_types_str + '{} {},'.format(cols[element], types[element])
cols_types_str = cols_types_str[:len(cols_types_str)-1] # drop the last comma
df = pd.read_sql(query_str,src_con)
df.dropna(how='all', inplace=True)
try:
dst_cur.execute('drop table {}'.format(table))
print('{} Table Dropped!'.format(table))
except:
print('No {} Table to Drop!'.format(table))
try:
if primary_index == None:
dst_cur.execute('create table {} ( {} )'.format(table, cols_types_str))
print('Table {} Created!'.format(table))
else:
primary_index_str = ','.join(primary_index)
dst_cur.execute('create table {} ( {} ) unique primary index ( {} )'.format(table, cols_types_str, primary_index_str)) # this needs to be updated to be any custom text
print('Table {} Created!'.format(table))
except:
print('{} Table Already Exists!'.format(table))
df_tuples = list(map(lambda x: tuple(x), df.values.tolist()))
values_str = '?,'*len(cols)
values_str = values_str[:len(values_str)-1] # removes the last comma
print('Writing {} Records to {}...'.format(len(df_tuples), table))
start_time = time.time()
dst_cur.executemany('insert into {} ( {} ) values ( {} )'.format(table, cols_str, values_str), df_tuples)
end_time = time.time()
print('Table {} Successfully Written in {} Minutes!'.format(table, round((end_time-start_time)/60, 1)))
###########################
### SECTION 3 EXERCISES ###
###########################
# Practice using the roland_toolbox functions by copy/pasting them into the shell
# After having downloaded the data, try to create multiple dfs and merge/concat them, add columns and/or fill in missing values, group and aggregate them
# It may be necessary to either create environmental variables or change connection parameters to properly connect to data sources
# Here are some examples of things to try
# EXAMPLE 1
# td = connect_db("td")
# td_query_str = '''
# SELECT *
# FROM acct.blizzard_login_daily bld
# JOIN acct.d_bnet_account dba
# ON dba.bnet_account_key = bld.bnet_account_key
# WHERE bld.login_date = '2018-10-23'
# SAMPLE 10
# '''
# td_df = query_db(td, td_query_str)
# EXAMPLE 2
# from roland_toolbox import connect_db, query_db, write_table_from_query_batch
# td = connect_db("td")
# hive = connect_db("hive")
# hive_query_str = "SELECT * FROM telem_pro.pro_lobby_endorsementlevelchange LIMIT 10"
# write_table_from_query_batch(
# hive,
# td,
# hive_query_str,
# 'dlab_rheinze.new_table',
# ['col_name1', 'col_name2', ...],
# ['integer', 'varchar(30)', 'col_name3 dtype', ...],
# 10000
# )
# query_db(td, 'dlab_rheinze.new_table')
#################
### APPENDIX ###
#################
# FULL PYTHON INSTALLATION
# Install the latest version of Python from https://www.python.org/downloads/ and make sure to check the option "Install to System Environment Path"
# After installation, open the command prompt by typing "cmd" into your Start menu
# Next install Python libraries -- pandas, numpy, pyodbc, ipython -- by typing "pip install pandas" and hitting Enter in the Command Prompt
# iPython will serve as the shell for our Python interpreter; it's easy to copy/paste large blocks of Python code into the iPython shell
''' IMPORTANT: You may encounter some errors when installing Python libraries using Windows...
When that occurs, try using https://www.lfd.uci.edu/~gohlke/pythonlibs/ to find the .whl file associated with your version of Python and Operating System
Once downloaded, navigate to your Python directory's Lib folder (similar to C:\Users\rheinze\AppData\Local\Programs\Python\Python36\Lib)
Move the .whl file into the Lib folder, change the Commmand Prompt's current working directory to the Lib directory, and use pip to install the .whl file
Do this using a sequence of Command Prompt commands: "c:", "cd C:\Users\rheinze\AppData\Local\Programs\Python\Python36\Lib", "pip install filename.whl"
# SECTION 1 ANSWERS
In [23]: def connect_db(x='td'):
...: '''This is the docstring for connect_db'''
...: if x == 'td':
...: con, cur = 'td_con', 'td_cur'
...: if x == 'hive':
...: con, cur = 'hive_con', 'hive_cur'
...: print('Connection to {0} Successful!'.format(x))
...: return (con, cur)
In [34]: def join_str_args(list1, list2):
...: str_list1 = list(map(lambda x: str(x), list1))
...: str_list2 = list(map(lambda x: str(x), list2))
...: str_list = []
...: for i in range(max(len(str_list1), len(str_list2))):
...: try:
...: str_list.append('{0} {1}'.format(str_list1[i], str_list2[i]))
...: except:
...: print('Error due to list length mismatch!')
...: return str_list
|
0c8feaa9deb60096505a719975647972d8c32d71 | btparker70/Python-Basics | /basics/app.py | 835 | 3.84375 | 4 | # variable
students_count = 1000
# float
rating = 4.99
# boolean
is_published = True
# string
course_name = "Python"
# you can do triple quotes if your string has multiple lines
course_name_2 = """
Python
Course
"""
# you can initailize multiple variables on the same line
x = 1
y = 2
x, y = 1, 2
# we can set multiple variables to the same value
x = y = 1
# we can run this to print the type of variable students_count is
students_count = 1000
print(type(students_count))
# returns <class 'int'>
print(type(1.1))
print(type(True))
print(type("hello"))
age = 20
age = "Python"
print(age)
x = 1
id(x)
print(id(x))
# this returns the address of the memory location where we've stored x
x = x + 1
print(id(x))
# this is a list
x = [ 1, 2, 3]
print(id(x))
# lists are mutable, so the address doesn't change
x.append(4)
print(id(x)) |
d35e96bed8b86b957d315df9c205ef8cfb1c9c6b | armada74/webcrawling | /test.py | 823 | 3.609375 | 4 | import requests
from bs4 import BeautifulSoup
def spider():
base_url = "http://www.naver.com/index.html"
# storing all the information including headers in the variable source code
source_code = requests.get(base_url)
# sort source code and store only the plaintext
plain_text = source_code.text
print(plain_text)
# converting plain_text to Beautiful Soup object so the library can sort thru it
convert_data = BeautifulSoup(plain_text, 'lxml')
# sorting useful information
for link in convert_data.findAll('a', {'class': 'h_notice'}):
href = base_url + link.get('href') # Building a clickable url
title = link.string # just the text not the html
print(href) # displaying href
print(title) # displaying title
# 수정 확인
spider()
|
61c95de3fab85b42767cf0e48b4adabd4467c76e | mariosantiago/githubActividad2FD | /3.lsp.py | 709 | 3.875 | 4 | import abc
from abc import ABCMeta
class Coche (object):
__metaclass__ = ABCMeta
def init(self, name: str):
self.name = name
@abc.abstractmethod
def numAsientos(self) -> str:
pass
class Renault(Coche):
def numAsientos(self):
return 'Asientos Renault ' + str(5)
class Audi(Coche):
def numAsientos(self):
return 'Asientos Audi ' + str(2)
class Mercedes(Coche):
def numAsientos(self):
return 'Asientos Mercedes ' + str(4)
def imprimirNumAsientos(coches: list):
for coche in coches:
print(coche.numAsientos())
coches = [
Renault(),
Audi(),
Mercedes()
]
if __name__ == '__main__':
imprimirNumAsientos(coches)
|
57ba134935bace9288850296e2435cf6e36902cb | Diffblue-benchmarks/Lucafon-DesignPatterns | /lucafontanili.designpatterns.python/src/structural/composite/Worker.py | 966 | 3.765625 | 4 | '''
Created on Nov 5, 2016
@author: Admin
'''
class EmployeeClass(object):
_name = None
_salary = None
def __init__(self, name):
self._name = name
def set_salary(self, salary):
self._salary = salary
def name(self):
return self._name
def salary(self):
return self._salary
class Employee(EmployeeClass):
_role = None
_office = None
def __init__(self, name, office, role):
super(Employee, self).__init__(name)
self._role = role
self._office = office
class Office(EmployeeClass):
_people = []
def __init__(self, name):
super(Office, self).__init__(name)
def add(self, worker):
self._people.append(worker)
def remove(self, worker):
self._people.remove(worker)
def salary(self):
return sum(person.salary() for person in self._people) |
e682aedba9e99847d892189b482617e73d1e4c76 | BennoKrojer/DLexperiments | /MNISTwithFunctionalAPI.py | 1,158 | 3.5625 | 4 | from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras import models
from tensorflow.python.keras import layers
from tensorflow.python.keras.utils import to_categorical
#define the data
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
#define the network architecture
input_tensor = layers.Input(shape=(784,))
x = layers.Dense(32, activation="relu",)(input_tensor)
output_tensor = layers.Dense(10, activation="softmax")(x)
network = models.Model(inputs=input_tensor, outputs=output_tensor)
#choose the optimizer,loss function and metrics
network.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"])
train_images = train_images.reshape(60000, 28*28)
train_images = train_images.astype("float32") / 255
test_images = test_images.reshape(10000, 28*28)
test_images = test_images.astype("float32") / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
#train, iterate over data
network.fit(train_images, train_labels, epochs=5, batch_size=128)
test_loss, test_accuracy = network.evaluate(test_images, test_labels)
print(test_accuracy) |
c5ab556c5524d512bc61654fbed1622b981fbe63 | NikhilBhargav/Joy_Of_Learning_Python | /lottery.py | 691 | 3.875 | 4 | ##########################
# Py Lottery simulation
##########################
import random
import matplotlib.pyplot as plt
fee=100
prize=1000
myAccountBalance=0
numTurns=365
#X and Y Axis
x=[]
y=[]
for i in range(numTurns):
#bet=int(input("What is your bet (1-10)"))
bet=random.randint(1,10)
x.append(i+1)
luckyDraw=random.randint(1,10)
y.append(myAccountBalance)
#I am lucky as my bet matched
if(bet==luckyDraw):
myAccountBalance=myAccountBalance+prize-fee
else:
#No prize
myAccountBalance=myAccountBalance-fee
y.append(myAccountBalance)
print("My Account Balance after",numTurns," : ",myAccountBalance)
plt.plot(x,y)
plt.show()
|
ab6b9b0cdf9051169cfd19f30f939d5dbc88c9fb | SebastianDica/LeetCode-Solutions | /0006. ZigZag Conversion/main.py | 1,355 | 3.671875 | 4 | def convert(s: str, numRows: int) -> str:
selectedRow = 0
result = ""
coreJump = numRows * 2 - 2
if (coreJump == 0):
coreJump = 1
while(selectedRow < numRows):
jump1 = coreJump - selectedRow * 2
jump2 = coreJump - jump1
jumped1 = False
if (jump1 == 0 and jump2 != 0):
jump1 = jump2
elif (jump1 != 0 and jump2 == 0):
jump2 = jump1
selectedIndex = selectedRow
while selectedIndex < len(s):
result = result + s[selectedIndex]
if(jumped1):
selectedIndex = selectedIndex + jump2
jumped1 = False
else:
selectedIndex = selectedIndex + jump1
jumped1 = True
selectedRow = selectedRow + 1
return result
if __name__ == "__main__":
print (convert("PAYPALISHIRING", 3), "expected PAHNAPLSIIGYIR")
print (convert("PAYPALISHIRING", 4), "expected PINALSIGYAHRPI")
print (convert("A", 1), "expected A")
print (convert("PAYPALISHIRING", 1), "expected PAYPALISHIRING")
print (convert("PAYPALISHIRING", 5), "expected PHASIYIRPLIGAN")
# 3
# P A H N
# A P L S I I G
# Y I R
#
# 4
#
# 1 6 6 P I N
# 2 4 2 A L S I G
# 3 2 4 Y A H R
# 4 6 6 P I
#
# 5
#
# P H
# A S I
# Y I R
# P L I G
# A N
|
8baa119b1907cd39883f03712763a0de11d0376c | thoan741/lek | /Hemuppgifter/Hemuppgift_3.py | 1,113 | 3.984375 | 4 | # Uppgift 13
#BMI
def BMI():
"""
vikt skrivs in kg och längd i cm. längden konverteras till meter innan beräkning.
värdet rundas till hundradel och jämförs mot alla viktklasser. sedan skrivs BMI och viktklass ut.
"""
weight = float(input("Ange vikt (i kg): "))
height = float(input("Ange längd (i cm): "))
height = height / 100
a = weight / height ** 2
# a = float('{:.2f}'.format(a))
a = round(a, 2)
if a >= 30:
b = "Fetma"
elif a >= 25:
b = "Övervikt"
elif a >= 20:
b = "Normalvikt"
else:
b = "Undervikt"
print("BMI = ", a)
print("Viktklass = ", b)
BMI()
# Uppgift 14
def read_lines(n):
"""
En input loopas n gånger, varje gång appendas inskriften i en lista och sedan returneras listan.
:param n: ett heltal som beskriver hur många inskrifter som ska göras.
:return: returnerar en lista där varje element är en enskild input.
"""
a = 0
b = []
while a < n:
c = input("skriv något: ")
b.append(c)
a += 1
return b
print(read_lines(3)) |
376f3ee3e5266531f32418a99b0d89e884b40d22 | susurrant/LeetCode | /17.py | 704 | 3.578125 | 4 | """
17. Letter Combinations of a Phone Number
"""
class Solution:
def letterCombinations(self, digits: 'str') -> 'List[str]':
t = {'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz'}
r = []
for d in digits:
if r:
tem = []
for item in r:
for c in t[d]:
tem.append(item+c)
r = tem.copy()
else:
r = list(t[d])
return r
if __name__ == '__main__':
s = Solution()
print(s.letterCombinations('23'))
|
952bc52d3f81edae1018289ac11172f351513150 | cameron-stewart/simphys1 | /sim2/templates/plot_samples.py | 1,187 | 3.921875 | 4 | from numpy import *
from matplotlib.pyplot import *
# Create 100 equidistant points between 0 and 2*pi
xs = linspace(0, 2.*pi, 100)
# Create a title for the plot
title("How to make plots")
# Create labels for the axes
# Note that in the label, you can use TeX-strings!
xlabel("$x$")
ylabel("$f(x)$")
# Now create two plots of different functions in a single figure
plot(xs, sin(xs), 'o-', label="$f(x)=\sin(x)$")
plot(xs, sin(xs)**2, '*:', label="$f(x)=\sin^2(x)$")
# Now create the legend box
legend()
# Create a second plot in loglog scale
figure()
title("A second plot, this time in loglog scale")
loglog(xs, xs**2, 'o-', label="$f(x)=x^2$")
loglog(xs, xs**0.5, '*:', label="$f(x)=\sqrt{x}$")
legend()
# Create a third plot with four subplots
figure("A title for the window")
# Select a subplot
# '221' describes the number of subplots in the figure and which subplot to select
# '22' tells to make a grid of 2 by 2 subplots
# '1' tells to select the first plot
subplot(221, title="$\sin(x)$")
plot(xs, sin(xs))
subplot(222, title="$\cos(x)$")
plot(xs, cos(xs))
subplot(223, title="$\sin^2(x)$")
plot(xs, sin(xs)**2)
subplot(224, title="$\cos^2(x)$")
plot(xs, cos(xs)**2)
show()
|
930d44f72d3fbc06e9a2218f5c5e24632de0eec1 | gabriellaec/desoft-analise-exercicios | /backup/user_119/ch22_2019_03_01_16_46_36_166389.py | 130 | 3.703125 | 4 | ano=int(input('escolha um ano: ')
def eh_bissexto('ano'):
y=ano/4
if y=0
return True
else return False |
30db67376a5787a1468ba4262b9aa22878f43cf5 | piotrautuch/CryptoNoise | /main.py | 950 | 3.515625 | 4 | import requests
import json
import time
def get_price(r):
return r.json()["USD"]["last"]
def main():
# Get a request from an API
r = requests.get("https://blockchain.info/ticker")
if (r.status_code == 200):
print("Success! Site is up. Monitoring...")
elif (r.status_code == 400):
print("Bad request")
print(get_price(r))
stream(get_price(r))
def stream(price):
last_price = price
time.sleep(1)
r = requests.get("https://blockchain.info/ticker")
## If the request get an OK resposne, the program continues
if (r.status_code == 200):
if(get_price(r) > last_price):
print("UP: "+ str(get_price(r)), "BY "+ str(get_price(r) - last_price))
elif (get_price(r) < last_price):
print("DOWN: "+ str(get_price(r)), "BY "+str(last_price-get_price(r)))
return stream(get_price(r))
else:
return
if __name__ == '__main__':
main()
|
475e707878f84c12048021c4dad6ca7e6fcf4dab | oplt/Codecademy-Projects | /Data-Science-Path/Pandas/Central Tendency for Housing Data.py | 2,099 | 3.875 | 4 | # Central Tendency for Housing Data
# In this project, you will find the mean, median, and mode cost of one-bedroom apartments in three of the five New York City boroughs: Brooklyn, Manhattan, and Queens.
import numpy as np
import pandas as pd
from scipy import stats
# Read in housing data
brooklyn_one_bed = pd.read_csv('brooklyn-one-bed.csv')
brooklyn_price = brooklyn_one_bed['rent']
manhattan_one_bed = pd.read_csv('manhattan-one-bed.csv')
manhattan_price = manhattan_one_bed['rent']
queens_one_bed = pd.read_csv('queens-one-bed.csv')
queens_price = queens_one_bed['rent']
# check the data
print(brooklyn_one_bed)
print(manhattan_one_bed)
print(queens_one_bed)
print(brooklyn_price)
print(manhattan_price)
print(queens_price)
# Find the average value of one-bedroom apartments in Brooklyn and save the value to brooklyn_mean
brooklyn_mean = np.average(brooklyn_one_bed)
# Find the average value of one-bedroom apartments in Manhattan and save the value to manhattan_mean
manhattan_mean = np.average(manhattan_one_bed)
# Find the average value of one-bedroom apartments in Queens and save the value to queens_mean
queens_mean = np.average(queens_one_bed)
# Find the median value of one-bedroom apartments in Brooklyn and save the value to brooklyn_median
brooklyn_median = np.median(brooklyn_one_bed)
# Find the median value of one-bedroom apartments in Manhattan and save the value to manhattan_median.
manhattan_median = np.median(manhattan_one_bed)
# Find the median value of one-bedroom apartments in Queens and save the value to queens_median
queens_median = np.median(queens_one_bed)
# Find the mode value of one-bedroom apartments in Brooklyn and save the value to brooklyn_mode.
brooklyn_mode = stats.mode(brooklyn_one_bed)
# Find the mode value of one-bedroom apartments in Manhattan and save the value to manhattan_mode.
manhattan_mode = stats.mode(manhattan_one_bed)
# Find the mode value of one-bedroom apartments in Queens and save the value to queens_mode.
queens_mode = stats.mode(queens_one_bed)
|
030fb6997dfd66ac0ad5822093687c65b9b61b0d | adam7902/Commonly-used-Python | /Python读写csv文件/writer写入带有header的csv文件.py | 1,053 | 3.796875 | 4 | # UTF-8
# https://thepythonguru.com/python-how-to-read-and-write-csv-files/
import csv
header = ['id', 'name', 'address', 'zip']
rows = [
[1, 'Hannah', '4891 Blackwell Street, Anchorage, Alaska', 99503],
[2, 'Walton', '4223 Half and Half Drive, Lemoore, California', 97401],
[3, 'Sam', '3952 Little Street, Akron, Ohio', 93704],
[4, 'Chris', '3192 Flinderation Road, Arlington Heights, Illinois', 62677],
[5, 'Doug', '3236 Walkers Ridge Way, Burr Ridge', 61257],
]
# 单行写入
with open('customers.csv', 'wt') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(header) # write header
for row in rows:
csv_writer.writerow(row)
print(' write ok ...')
# 多行写入
with open('customers2.csv', 'wt') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(header) # write header
csv_writer.writerows(rows)
print(' write ok ...')
with open('customers.csv', 'rt') as f:
csv_reader = csv.DictReader(f)
for row in csv_reader:
print(row)
|
9c4082d83e309e0231d3a4d8621666042823d315 | daniel-reich/ubiquitous-fiesta | /bGRYmEZvzWFK2sbek_8.py | 130 | 3.546875 | 4 |
def get_missing_letters(s):
ret = ""
for i in range(97, 123):
if not chr(i) in s:
ret = ret + chr(i)
return ret
|
12179ad3495adc03fc337c30371ccdefb02aac18 | cothuyanninh/Python_Code | /fsoft/Week 1/B1/bai2.py | 346 | 3.921875 | 4 | """C1"""
list_temp = [20, 18, 23, 4, 8, 3, 19, 16, 45, 25]
max_ = list_temp[0]
min_ = list_temp[0]
for i in list_temp:
if (i >= max_):
max_ = i
if (i < min_):
min_ = i
print("MAx: %d"%max_)
print("Min: %d"%min_)
"""C2"""
list_temp = [20, 18, 23, 4, 8, 3, 19, 16, 45, 25]
print("Max is: ", max(list_temp))
print("Min is: ", min(list_temp)) |
ef86b5c50049d5756568ed994582277e5ad541cb | VitaliStanilevich/Md-PT1-40-21 | /Tasks/Zhukovskii_ClassWork/FirstClassWork/first work.py | 775 | 3.65625 | 4 | l = input("Input digts: ")
from operator import itemgetter
d = {'one': 1, 'two': 2, 'three':3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelfth': 12, 'thirteen': 13, 'forteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20}
#t = "five thirteen two eleven seventeen two one thirteen ten four eight five nineteen".split ( )
print("Your dights: ",itemgetter(*l.split())(d))
z = list(set(itemgetter(*l.split())(d)))
print("sorted:", z)
l = len(z)
i = 0
while i < l:
p = z[i]*z[i+1]
i +=2
print("product =",p)
i = 1
while i < l-1:
s = z[i]+z[i+1]
i +=2
print("sum =", s)
S = 0
for i in range (l):
if z[i]%2==1:
S +=z[i]
print("sum odd =", S) |
3ae9cb1e4fb856cfe7bbbc26f5179a5d7d8ed377 | jeremyosborne/python | /general/wrestling/db.py | 2,283 | 3.84375 | 4 | """All of our database stuff.
"""
import sqlite3
import os
# Makes/opens database relative to this file.
db_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "wrestlers.db3")
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# When we first init this module, create what we need.
cursor.execute("""CREATE TABLE IF NOT EXISTS wrestlers (
name text NOT NULL UNIQUE,
brawn integer,
finesse integer,
wins integer,
losses integer
);""")
conn.commit()
def cleanup():
"""Call when it's time to close and cleanup the database.
"""
cursor.close()
conn.close()
def create_wrestler(**stats):
"""Create a new wrestler in the database.
"""
try:
cursor.execute(
"""INSERT INTO wrestlers
VALUES ('{0[name]}', {0[brawn]}, {0[finesse]}, {0[wins]}, {0[losses]})
""".format(stats))
conn.commit()
except sqlite3.IntegrityError as err:
# reraise error so that external things don't need to know about
# the database error types.
raise ValueError("Wrestler already exists: %s" % err)
def update_wrestler(**stats):
"""Create a new wrestler in the database.
"""
try:
cursor.execute(
"""UPDATE wrestlers SET
brawn={0[brawn]},
finesse={0[finesse]},
wins={0[wins]},
losses={0[losses]}
WHERE name='{0[name]}'
""".format(stats))
conn.commit()
except sqlite3.Error as err:
# reraise error so that external things don't need to know about
# the database error types.
raise ValueError("Something Bad Happened in update_wrestler: %s" % err)
def get_wrestlers():
"""Returns a the raw data of wrestlers as a dictionary.
"""
results = []
try:
cursor.execute("""SELECT * FROM wrestlers""")
fieldnames = map(lambda x: x[0], cursor.description)
for wrestler in cursor:
# Compress with field names and turn into a dictionary
wrestler = dict(zip(fieldnames, wrestler))
results.append(wrestler)
except sqlite3.Error as err:
print "ERROR in get_wrestlers: %s" % err
# Make sure we always return a list.
return results
|
bcc5ff4c0f5dcc409170897544925b77d5bb2592 | ashaju2/HackerRank_30DC | /hR_Day6.py | 208 | 3.609375 | 4 | #!/usr/bin/python3
import sys
n = int(input().strip())
for i in range(0,n):
string = input()
letters = list(string)
j = letters[0::2]
k = letters[1::2]
print(''.join(j), ''.join(k))
|
cf512b8ee6944972f4919f0aa02c8853a1604aa3 | JhonArias97/Python | /Retos mintic/retos semanales/reto_1.py | 524 | 3.84375 | 4 | def run():
producto = input("Introduce el nombre del prodocuto: ")
costo = int(input("Introduce el costo unitario: "))
precio = int(input("Introduce el precio de venta: "))
unidades = int(input("Introduce las unidades disponibles: "))
ganacias = (precio - costo) * unidades
print(f'Producto: {producto}')
print(f'CU: ${costo}')
print(f'PVP: ${precio}')
print(f'Unidades Disponibles: {unidades}')
print(f'Ganancia: ${ganacias}')
if __name__ == "__main__":
run() |
4efcdbe725e66e8c8460a4a144d0be9891414e76 | amalmhn/PythonDjangoProjects | /flow_controls/looping_statements/for_loop/for_loop.py | 157 | 4.03125 | 4 | for i in range(0,11):
print(i)
print("----")
for i in range(0,11,2):
print(i)
print("----")
for i in range(10,0,-1): #decrement loop
print(i) |
dd700303ffa4718c81de34d3fb321f824db13ff1 | gerswin/HAP-python | /main.py | 2,041 | 3.578125 | 4 | """An example of how to setup and start an Accessory.
This is:
1. Create the Accessory object you want.
2. Add it to an AccessoryDriver, which will advertise it on the local network,
setup a server to answer client querries, etc.
"""
import logging
import os
import pickle
import signal
import pyhap.util as util
from pyhap.accessories.TemperatureSensor import TemperatureSensor
from pyhap.accessory import Bridge
from pyhap.accessory_driver import AccessoryDriver
logging.basicConfig(level=logging.INFO)
def get_bridge():
"""Call this method to get a Bridge instead of a standalone accessory."""
bridge = Bridge(display_name="Bridge", pincode=b"203-23-999")
temp_sensor = TemperatureSensor("Termometer")
temp_sensor2 = TemperatureSensor("Termometer2")
bridge.add_accessory(temp_sensor)
bridge.add_accessory(temp_sensor2)
# Uncomment if you have RPi module and want a LED LightBulb service on pin 16.
# from pyhap.accessories.LightBulb import LightBulb
# bulb = LightBulb("Desk LED", pin=16)
# bridge.add_accessory(bulb)
return bridge
def get_accessory():
"""Call this method to get a standalone Accessory."""
acc = TemperatureSensor("MyTempSensor",
pincode=b"203-23-999",
mac=util.generate_mac())
return acc
# The AccessoryDriver preserves the state of the accessory
# (by default, in the below file), so that you can restart it without pairing again.
if os.path.exists("accessory.pickle"):
with open("accessory.pickle", "rb") as f:
acc = pickle.load(f)
else:
acc = get_accessory() # Change to get_bridge() if you want to run a Bridge.
# Start the accessory on port 51826
driver = AccessoryDriver(acc, 51826)
# We want KeyboardInterrupts and SIGTERM (kill) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGINT, driver.signal_handler)
signal.signal(signal.SIGTERM, driver.signal_handler)
# Start it!
driver.start()
|
74fe61033adeed1666f64caa807e673a0135b7f6 | narenchandra859/PythonLabExam | /Solutions/13a.py | 330 | 3.5 | 4 | def wellbracketed(s):
l=[]
for c in s:
if c == "(":
l.append(c)
elif c == ")":
if l == []:
return False
l.pop()
else:
pass
if l == []:
return True
else:
return False
print(wellbracketed("22)"))
print(wellbracketed("(a+b)(a-b)"))
print(wellbracketed("(a(b+c)-d)((e+f)")) |
f7d2dc6966b9c25fe9422f328d2d40400094b17d | NikolaosPanagiotopoulos/PythonLab | /lectures/source/lecture_04/lecture_04_example_4a.py | 157 | 3.875 | 4 | num = int(input("Δώσε έναν αριθμό: ").strip())
while num > 0:
print(num)
num = int(input("Δώσε έναν αριθμό: ").strip())
|
c5468cab63129d7c22efd9ce84b4c03d60c614ea | zhuozhi-ge/Fundamentals-of-Computing-Specialization | /Algorithmic Thinking II/Applications/A3 Clustering Algorithms.py | 17,519 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Student template code for Project 3
Student will implement five functions:
slow_closest_pair(cluster_list)
fast_closest_pair(cluster_list)
closest_pair_strip(cluster_list, horiz_center, half_width)
hierarchical_clustering(cluster_list, num_clusters)
kmeans_clustering(cluster_list, num_clusters, num_iterations)
where cluster_list is a 2D list of clusters in the plane
"""
import math
import alg_cluster
import random
import urllib
import time
import matplotlib.pyplot as plt
######################################################
# Code for closest pairs of clusters
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function that computes Euclidean distance between two clusters in a list
Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters
Output: tuple (dist, idx1, idx2) where dist is distance between
cluster_list[idx1] and cluster_list[idx2]
"""
return (cluster_list[idx1].distance(cluster_list[idx2]), min(idx1, idx2), max(idx1, idx2))
def slow_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum distance dist.
"""
ans = (float("inf"), -1, -1)
size = len(cluster_list)
for idx1 in range(size):
for idx2 in range(idx1+1, size):
temp = pair_distance(cluster_list, idx1, idx2)
if temp[0] < ans[0]:
ans = temp
return ans
def fast_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (fast)
Input: cluster_list is list of clusters SORTED such that horizontal positions of their
centers are in ascending order
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum distance dist.
"""
# =============================================================================
# cluster_list.sort(key = lambda cluster: cluster.horiz_center())
# =============================================================================
size = len(cluster_list)
if size < 4:
return slow_closest_pair(cluster_list)
mid_idx = size//2
l_dist = fast_closest_pair(cluster_list[:mid_idx])
_r_dist = fast_closest_pair(cluster_list[mid_idx:])
r_dist = (_r_dist[0], _r_dist[1]+mid_idx, _r_dist[2]+mid_idx)
if l_dist[0] < r_dist[0]:
ans = l_dist
else:
ans = r_dist
mid_center = (cluster_list[mid_idx-1].horiz_center() +
cluster_list[mid_idx].horiz_center())/2
half_width = min(l_dist[0], r_dist[0])
m_dist = closest_pair_strip(cluster_list, mid_center, half_width)
if m_dist[0] < ans[0]:
ans = m_dist
return ans
def closest_pair_strip(cluster_list, horiz_center, half_width):
"""
Helper function to compute the closest pair of clusters in a vertical strip
Input: cluster_list is a list of clusters produced by fast_closest_pair
horiz_center is the horizontal position of the strip's vertical center line
half_width is the half the width of the strip (i.e; the maximum horizontal distance
that a cluster can lie from the center line)
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] lie in the strip and have minimum distance dist.
"""
ans = (float("inf"), -1, -1)
idx_in_strip = []
for cluster in cluster_list:
if - half_width <= cluster.horiz_center() - horiz_center <= half_width:
idx_in_strip.append(cluster_list.index(cluster))
idx_in_strip.sort(key=lambda idx: cluster_list[idx].vert_center())
size = len(idx_in_strip)
for idx1 in range(size-1):
for idx2 in range(idx1+1, min(idx1+4, size)):
dist = cluster_list[idx_in_strip[idx1]].distance(cluster_list[idx_in_strip[idx2]])
if dist < ans[0]:
min_idx = min(idx_in_strip[idx1], idx_in_strip[idx2])
max_idx = max(idx_in_strip[idx1], idx_in_strip[idx2])
ans = (dist, min_idx, max_idx)
return ans
######################################################################
# Code for hierarchical clustering
def hierarchical_clustering(cluster_list, num_clusters):
"""
Compute a hierarchical clustering of a set of clusters
Note: the function may mutate cluster_list
Input: List of clusters, integer number of clusters
Output: List of clusters whose length is num_clusters
"""
cluster_list.sort(key=lambda cluster: cluster.horiz_center())
while len(cluster_list) > num_clusters:
pair = fast_closest_pair(cluster_list)
idx1, idx2 = pair[1], pair[2]
cluster_list[idx1].merge_clusters(cluster_list[idx2])
cluster_list.pop(idx2)
cluster_list.sort(key=lambda cluster: cluster.horiz_center())
return cluster_list
######################################################################
# Code for k-means clustering
def kmeans_clustering(cluster_list, num_clusters, num_iterations):
"""
Compute the k-means clustering of a set of clusters
Note: the function may not mutate cluster_list
Input: List of clusters, integers number of clusters and number of iterations
Output: List of clusters whose length is num_clusters
"""
temp = []
for cluster in cluster_list:
temp.append(cluster.copy())
temp.sort(key=lambda _: _.total_population(), reverse=True)
centers = [(temp[idx].horiz_center(), temp[idx].vert_center()) for idx in range(num_clusters)]
for _ in range(num_iterations):
ans = [alg_cluster.Cluster(set(), center[0], center[1], 0, 0) for center in centers]
sort = [[] for _ in centers]
for cluster in cluster_list:
min_dist = float("inf")
for idx in range(num_clusters):
dist = cluster.distance(ans[idx])
if dist < min_dist:
min_dist = dist
close_idx = idx
sort[close_idx].append(cluster)
for idx in range(num_clusters):
for cluster in sort[idx]:
ans[idx].merge_clusters(cluster)
centers = [(cluster.horiz_center(), cluster.vert_center()) for cluster in ans]
return ans
#%% question 1
def gen_random_clusters(num_clusters):
"""
Parameters
----------
num_clusters : int, number of clusters
Returns
-------
a list of points randomly within square (+/-1, +/-1)
"""
clusters = []
for _ in range(num_clusters):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
cluster = alg_cluster.Cluster(set(), x, y, 0, 0)
clusters.append(cluster)
return clusters
def running_time(fun, arg):
"""
return the running time of a function, with input arg
"""
start = time.time()
fun(arg)
stop = time.time()
return stop - start
def question_1():
"""
run question 1
"""
x = list(range(2, 201))
y_slow = []
y_fast = []
for n in x:
clusters = gen_random_clusters(n)
time_slow = running_time(slow_closest_pair, clusters)
y_slow.append(time_slow)
time_fast = running_time(fast_closest_pair, clusters)
y_fast.append(time_fast)
plt.figure("question_1")
plt.clf()
plt.plot(x, y_slow, "red", label="slow cloeset pair")
plt.plot(x, y_fast, "blue", label="fast closest pair")
plt.title("Comparing running time of slow/fast closest pair algorithm")
plt.xlabel("Number of clusters")
plt.ylabel("Running time (s)")
plt.legend(loc="best")
plt.tight_layout()
plt.show()
# =============================================================================
# question_1()
# =============================================================================
#%% questions 2, 3
"""
Example code for creating and visualizing
cluster of county-based cancer risk data
Note that you must download the file
http://www.codeskulptor.org/#alg_clusters_matplotlib.py
to use the matplotlib version of this code
"""
# Flavor of Python - desktop or CodeSkulptor
#import alg_project3_solution # desktop project solution
import alg_clusters_matplotlib
###################################################
# Code to load data tables
# URLs for cancer risk data tables of various sizes
# Numbers indicate number of counties in data table
DIRECTORY = "http://commondatastorage.googleapis.com/codeskulptor-assets/"
DATA_3108_URL = DIRECTORY + "data_clustering/unifiedCancerData_3108.csv"
DATA_896_URL = DIRECTORY + "data_clustering/unifiedCancerData_896.csv"
DATA_290_URL = DIRECTORY + "data_clustering/unifiedCancerData_290.csv"
DATA_111_URL = DIRECTORY + "data_clustering/unifiedCancerData_111.csv"
def load_data_table(data_url):
"""
Import a table of county-based cancer risk data
from a csv format file
"""
data_file = urllib.request.urlopen(data_url)
data = data_file.read()
data = data.decode("utf-8")
data_lines = data.split('\n')
print("Loaded", len(data_lines), "data points")
data_tokens = [line.split(',') for line in data_lines]
return [[tokens[0], float(tokens[1]), float(tokens[2]), int(tokens[3]), float(tokens[4])]
for tokens in data_tokens]
############################################################
# Code to create sequential clustering
# Create alphabetical clusters for county data
def sequential_clustering(singleton_list, num_clusters):
"""
Take a data table and create a list of clusters
by partitioning the table into clusters based on its ordering
Note that method may return num_clusters or num_clusters + 1 final clusters
"""
cluster_list = []
cluster_idx = 0
total_clusters = len(singleton_list)
cluster_size = float(total_clusters) / num_clusters
for cluster_idx in range(len(singleton_list)):
new_cluster = singleton_list[cluster_idx]
if math.floor(cluster_idx / cluster_size) != \
math.floor((cluster_idx - 1) / cluster_size):
cluster_list.append(new_cluster)
else:
cluster_list[-1] = cluster_list[-1].merge_clusters(new_cluster)
return cluster_list
#####################################################################
# Code to load cancer data, compute a clustering and
# visualize the results
def question_2_3():
"""
Load a data table, compute a list of clusters and
plot a list of clusters
Set DESKTOP = True/False to use either matplotlib or simplegui
"""
data_table = load_data_table(DATA_3108_URL)
singleton_list = []
for line in data_table:
singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4]))
# =============================================================================
# cluster_list = sequential_clustering(singleton_list, 15)
# print("Displaying", len(cluster_list), "sequential clusters")
# =============================================================================
# =============================================================================
# cluster_list = hierarchical_clustering(singleton_list, 15)
# print("Displaying", len(cluster_list), "hierarchical clusters")
# =============================================================================
cluster_list = kmeans_clustering(singleton_list, 15, 5)
print("Displaying", len(cluster_list), "k-means clusters")
# draw the clusters using matplotlib or simplegui
#alg_clusters_matplotlib.plot_clusters(data_table, cluster_list, False)
alg_clusters_matplotlib.plot_clusters(data_table, cluster_list, True) #add cluster centers
# =============================================================================
# question_2_3()
# =============================================================================
#%% questions 5, 6
def question_5_6():
"""
Load a data table, compute a list of clusters and
plot a list of clusters
Set DESKTOP = True/False to use either matplotlib or simplegui
"""
data_table = load_data_table(DATA_111_URL)
singleton_list = []
for line in data_table:
singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4]))
# =============================================================================
# cluster_list = sequential_clustering(singleton_list, 15)
# print("Displaying", len(cluster_list), "sequential clusters")
# =============================================================================
cluster_list = hierarchical_clustering(singleton_list, 20)
print("Displaying", len(cluster_list), "hierarchical clusters")
# =============================================================================
# cluster_list = kmeans_clustering(singleton_list, 9, 5)
# print("Displaying", len(cluster_list), "k-means clusters")
# =============================================================================
# draw the clusters using matplotlib or simplegui
#alg_clusters_matplotlib.plot_clusters(data_table, cluster_list, False)
alg_clusters_matplotlib.plot_clusters(data_table, cluster_list, True) #add cluster centers
# =============================================================================
# question_5_6()
# =============================================================================
#%% question 7
def compute_distortion(cluster_list, data_table):
"""
compute the distortion for a clustering of the data_table
"""
distortion = 0
for cluster in cluster_list:
distortion += cluster.cluster_error(data_table)
return distortion
def question_7():
"""
run question 7
"""
data_table = load_data_table(DATA_111_URL)
singleton_list = []
for line in data_table:
singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4]))
num_clusters = 9
num_iterations = 5
# =============================================================================
# hierarchical_list = hierarchical_clustering(singleton_list, num_clusters)
# print("Hierarchical distortion")
# print(compute_distortion(hierarchical_list, data_table))
# =============================================================================
kmeans_list = kmeans_clustering(singleton_list, num_clusters, num_iterations)
print("Kmeans distortion")
print(compute_distortion(kmeans_list, data_table))
# =============================================================================
# question_7()
# =============================================================================
#%% question 10
def question_10():
"""
run question 10
"""
url_data = [DATA_111_URL, DATA_290_URL, DATA_896_URL]
for url in url_data:
data_table = load_data_table(url)
start = url.rfind("_")
stop = url.rfind(".")
num_counties = url[start+1:stop]
num_iterations = 5
x = list(range(6, 21))
y_hcc = []
y_km = []
for num_clusters in x:
singleton_list = []
for line in data_table:
singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4]))
hcc_list = hierarchical_clustering(singleton_list, num_clusters)
hcc_distortion = compute_distortion(hcc_list, data_table) / (1e11)
singleton_list = []
for line in data_table:
singleton_list.append(alg_cluster.Cluster(set([line[0]]), line[1], line[2], line[3], line[4]))
y_hcc.append(hcc_distortion)
km_list = kmeans_clustering(singleton_list, num_clusters, num_iterations)
km_distortion = compute_distortion(km_list, data_table) / (1e11)
y_km.append(km_distortion)
plt.figure("question_10")
plt.clf()
plt.plot(x, y_hcc, "red", label="hierarchical clustering distortion")
plt.plot(x, y_km, "blue", label="k-means clustering distortion")
plt.title("Comparing distortion of different clusterings"
+ "(" + num_counties + " counties)")
plt.xlabel("Number of output clusters")
plt.ylabel("Distortion (e11)")
plt.legend(loc="best")
plt.tight_layout()
plt.show()
# =============================================================================
# question_10()
# =============================================================================
|
29fd5d0ba5d0d3f70af3fe46616171d7b2a98796 | Ruby-Dog/III | /人工智慧與機器學習/lab/2-2-data.py | 378 | 4.15625 | 4 | x = "good good good"
y = x.replace("good", "bad")
print("舊名:", x)
print("新名:", y)
print("新名2:", x.replace("good", "bad"))
z = x.replace("good", "bad", 1)
print("只取代幾個:", z)
x = x.replace("good", "bad")
print("覆蓋x:", x)
###
print("轉成大寫", "good".upper())
print("轉成小寫", "BAD".lower())
###
a = "aaa \
bbb"
print(a)
b = "aaa\nbbb"
print(b) |
35f18de8d2d8aa0a186681ad98398f16f453280c | smootlight2/SmootLight | /util/ColorOps.py | 709 | 3.875 | 4 | import random
from util.TimeOps import Stopwatch
def randomColor():
return [random.randint(0,255) for i in range(3)]
def chooseRandomColor(colorList):
"""Given a list of colors, pick one at random"""
return random.choice(colorList)
def safeColor(c):
"""Ensures that a color is valid"""
c[0] = c[0] if c[0] < 255 else 255
c[1] = c[1] if c[1] < 255 else 255
c[2] = c[2] if c[2] < 255 else 255
return c
def combineColors(colors):
result = [0,0,0]
for c in colors:
result[0] += c[0]
result[1] += c[1]
result[2] += c[2]
return safeColor(result)
def multiplyColor(color, percent):
return safeColor([channel*(percent) for channel in color])
|
4aa27952d5990ae8342efe079c5e4e6a5cfde916 | LauroJr/Atividades-Linguagem_II | /occupation.py | 1,563 | 4.28125 | 4 | ''' Encontramos neste programa várias funções criadas, para serem importadas para outro programa.
Dessa forma ganhamos tempo sem precisar ficar codando tudo denovo uma vez que o código já está pronto
OBS: Para importar, abra um NEW FILE , e use FROM (occupation) IMPORT (nome da função). Explicação:
occupation é o nome da pasta de onde será importado a sua função. '''
def calcula_soma(a, b): # FUNÇÃO P/ CALCULAR DOIS NÚMEROS
soma = a + b
return soma # retorna o valor para o programa ao qual será importado essa função
####################################################################################################################
def intercala(): # FUNÇÃO QUE CONCATENA DUAS TUPLAS
tupla1 = ()
tupla2 = ()
tupla_Concatenada = ()
print("PRIMEIRA TUPLA: ")
for I in range(3):
n = int(input("Digite um número : "))
tupla1 = tupla1 + (n,)
print("")
print("SEGUNDA TUPLA: ")
for I in range(3):
n = int(input("Digite um número : "))
tupla2 = tupla2 + (n,)
tupla_Concatenada = tupla1 + tupla2
tupla_real = ()
cont1 = 0
cont2 = 3
c1 = 0
c2 = 3
while cont1 <= 2:
n1 = tupla_Concatenada[c1]
n2 = tupla_Concatenada[c2]
tupla_real = tupla_real + (n1,) + (n2,)
cont1 = cont1 + 1
cont2 = cont2 + 1
c1 = c1+1
c2 = c2+1
# tupla_Concatenada = tupla_real
print("")
return tupla_real
def soma(a):
s = 0
for I in a:
s = s+I
return s
|
b5861c1c7f5cca32a29618fa21384e02a6fcb599 | brij1823/CodeChef-Easy | /mytesting.py | 151 | 3.578125 | 4 | from fractions import gcd
test=int(input())
while(test):
a,b=input().split()
a=int(a)
b=int(b)
print(gcd(a,b))
test=test-1
|
769e4a83115261208fb32d4672c0e4ca2d2b1d71 | gagnongr/Gregory-Gagnon | /Exercises/fibonacci.py | 354 | 3.875 | 4 | n = int(input("what is n: "))
result = int(0)
i = int(0)
#if n == 0:
#result = 0
#elif n == 1:
#result = 1
#elif n == 2:
#result = 1
#else:
i = 0
j = 1
k = n
result = 0
while k > 1:
i, j = j, (j+i)
result = j
k -= 1
print ("i: ", i, ", j: ", j, ",n: ", n)
print("n is", n, " and ", "result is ", result)
|
25eb5dfa643993606717382b300960fed4442007 | Sergey0987/firstproject | /Архив/11_Raznie_raznosti - variant 2.py | 965 | 3.671875 | 4 | #Решение с использованием циклов
N=int(input())
list1=[]
list2=[]
for i in range(N): #подготовили список, с которым будем работать
list1.append(int(input()))
for i in range(len(list1)): # Добавили в список все возможные разности чисел (тут есть повторения)
for j in range(len(list1)-1):
list2.append(list1[i]-list1[j])
list2.append(list1[j]-list1[i])
list2.sort() # отсортировали для последующего поочередного сравнения
list1=[] # обнулили первый список
for i in range(len(list2)-1): #стали сравнивать поочередно элементы отсортированного списка
if list2[i]!=list2[i+1]:
list1.append(list2[i])
if i==(len(list2)-2):
list1.append(list2[i+1])
print(list1)
|
4f7a7aa93e3ddf4afb95ce837e010a5a075994c8 | LEEBONGHAK/basic-of-python | /chapter8/class(8-1).py | 1,677 | 3.59375 | 4 | # 8-1 클래스(class)
# 스타크래프트 예로 들 것임
# 마린 : 공격 유닛, 군인, 총을 쏠 수 있음
name = "마린" # 유닛 이름
hp = 40 # 유닛 체력
damage = 5 # 유닛 공격력
print("{} 유닛이 생성되었습니다.".format(name))
print("체력 {0}, 공격력 {1}\n".format(hp, damage))
# 탱크 : 공격 유닛, 탱크, 포 사용, 일반 / 시즈 모드
tank_name = "탱크"
tank_hp = 150
tank_damage = 35
print("{} 유닛이 생성되었습니다.".format(tank_name))
print("체력 {0}, 공격력 {1}\n".format(tank_hp, tank_damage))
tank2_name = "탱크"
tank2_hp = 150
tank2_damage = 35
print("{} 유닛이 생성되었습니다.".format(tank2_name))
print("체력 {0}, 공격력 {1}\n".format(tank2_hp, tank2_damage))
def attack(name, location, damage):
print(" {0} : {1} 방향으로 적군을 공격합니다. [공격력 {2}]".
format(name, location, damage))
attack(name, "1시", damage)
attack(tank_name, "1시", tank_damage)
attack(tank2_name, "1시", tank2_damage)
print("\n")
# 매번 적어주기 번거러움 -> 클래스 사용
# 클래스는 붕어빵 틀로 비유 / 연관있는 변수와 함수의 집합
# 위의 것을 클래스로 만들어서 사용
# 일반 유닛
class Unit:
# __init__을 통해 필요한 값 정의해줌
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
print("{0} 유닛이 생성되었습니다.".format(self.name))
print("체력 {0}, 공격력 {1}\n".format(self.hp, self.damage))
marine1 = Unit("마린", 40, 5)
marine2 = Unit("마린", 40, 5)
tank1 = Unit("탱크", 150, 35)
|
2997e09df0632b65795b8ca060f8ccf3261f1c37 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2537/61053/294728.py | 787 | 3.671875 | 4 | def adjustHeap(heap:list):
i = 0
child = 2 * i + 1
while child < len(heap):
#先定位到较大的子节点
if child + 1 < len(heap) and heap[child + 1]<heap[child]:
child += 1
#然后与父节点进行比较
if heap[child] < heap[i]:
temp = heap[child]
heap[child] = heap[i]
heap[i] = temp
i = child
child = 2 * child + 1
else:
break
def find_k(numlst,k):
heap = numlst[0:k]
heap = sorted(heap)
for i in range(k,len(numlst)):
if numlst[i] > heap[0]:
heap[0] = numlst[i]
adjustHeap(heap)
print(heap[0])
if __name__ == "__main__":
numlst = eval(input())
k = int(input())
find_k(numlst,k) |
4a0d27e107103a239a690bac85a28398a9fdf7ec | davelpat/Fundamentals_of_Python | /Ch2 exercises/cube.py | 435 | 4.9375 | 5 | """
You can calculate the surface area of a cube if you know the length of an edge.
Write a program that takes the length of an edge (an integer) as input and prints the cube’s surface area as output.
An example of the program input and output is shown below:
Enter the cube's edge: 4
The surface area is 96 square units.
"""
edge = int(input("Enter the cube's edge: "))
print("The surface area is", edge**2*6, "square units.")
|
22cf3729b80c8deab5375d5756a1063d845f2f2c | flame4ost/Python-projects | /§4(77-119)/z114.py | 1,701 | 3.8125 | 4 | import math
print("Задание 114(a) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 1
for i in range(1, n):
result = (result * (1/(i**2)))
print("n!!",result)
print("Задание 114(b) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 1
while n>=i:
result = result +1/(math.exp(3*(math.log(i))))
i = i+1
print("Результат = ",result)
print("Задание 114(c) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 1
f = 1
for i in range(1,n):
f = f*i
result = result + (1/f)
print("Результат = ",result)
print("Задание 114(g) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 1
for i in range(1,n):
result = result + 1/(pow(2*i,2))
print("Результат = ",result)
print("Задание 114(d) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 1
for i in range(1,n):
result = result * (pow(i,2)/(pow(i,2)+((2*i)+3)))
print("Результат = ",result)
print("Задание 114(e) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 1
f = 1
for i in range(1,n):
f = f*i
result = (result * (2+(1/f)))
print("Результат = ",result)
print("Задание 114(j) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
i = 2
for i in range(1,n):
result = result * ((i+1)/(i+2))
print("Результат = ",result)
print("Задание 114(z) ")
n = input("Введите n ")
n = int(n)
print("n = ",n)
result = 1
f = 1
i = 2
for i in range(1,n):
f = f*i
result = result * (pow(1 * 1/f,2))
print("Результат = ",result)
|
3e4c833af54ace80b07c47fead7d913372c9178b | henrycc2015/python | /Documents/workspace/python/demo1.py | 140 | 3.921875 | 4 | score = int(input("please input a int"))
if 90 <= score <= 100 :
print("A")
elif 80<= score < 90 :
print("B")
else :
print("c")
|
f525a83d56bc698825b1a329b78e04d5b1aab6be | projectPythonator/portfolio | /ProjectEuler/Python/p15.py | 2,067 | 3.53125 | 4 |
mm = nn = 20
cache_grid1=[[0 for i in range(nn+1)] for j in range(mm+1)]
cache_grid2=[[0 for i in range(nn+1)] for j in range(mm+1)]
'''
//long count_ways(int m, int n)
//returns the count from a recursive version
//param m and n which equal to x and y
//return 1 if we hit an edge otherwise sum of both
'''
def count_ways(n, m):
if n == 0 or m == 0:
return 1
else:
return count_ways(m-1, n)+count_ways(m, n-1)
def sol1(n, m):
print('there are {} through a {}x{} grid'.format(count_ways(n, m), n, m))
'''
//long count_ways2(int m, int n)s
//returns the count from a recursive version by divide and conqur
//param m and n are used for the cache
//return 1 if we hit edge retrun catch pos if already known otherwise calc the spot
'''
def count_ways2(n, m):
global cache_grid1
if n == 0 or m == 0:
return 1
elif 0 < cache_grid1[m][n]:
return cache_grid1[m][n]
else:
cache_grid1[m][n] = count_ways2(m, n-1)+count_ways2(m-1, n)
return cache_grid1[m][n]
def sol2(n, m):
print('there are {} through a {}x{} grid'.format(count_ways2(n, m), n, m))
'''
//long count_ways3(int m, int n)
//returns the count from a iterative version by divide and conqur
//param m and n are used for the grid cords
//return the answer after doing iteration
'''
def count_ways3(m, n):
global cache_grid2
for i in range(m+1):
cache_grid2[i][0] = 1
for i in range(n+1):
cache_grid2[0][i] = 1
for i in range(1, m+1):
for j in range(1, n+1):
cache_grid2[i][j] = cache_grid2[i-1][j] + cache_grid2[i][j-1]
return cache_grid2[m][n]
def sol3(n, m):
print('there are {} through a {}x{} grid'.format(count_ways3(m, n), n, m))
'''
//long Combinatorial_sol(int n)
//returns the count using Combinatorial
//param n is the size of the grid
//return the anser
'''
def count_ways4(n):
res = 1
for i in range(1, n + 1):
res = res * (n+i)//i
return res
def sol4(n, m):
print('there are {} through a {}x{} grid'.format(count_ways4(n), n, m))
def main():
#sol1(20, 20)
sol2(20, 20)
sol3(20, 20)
sol4(20, 20)
main()
|
c5b0a99d76d2815b38e807ba96ab1ff4bc284054 | mug31416/PubAdmin-Discourse | /src/utils/roman.py | 2,130 | 3.90625 | 4 | # A Python-3 adapted version of the code from
# http://code.activestate.com/recipes/81611-roman-numerals/#c3
def roman_to_int(input):
"""
Convert a roman numeral to an integer.
>>> r = range(1, 4000)
>>> nums = [int_to_roman(i) for i in r]
>>> ints = [roman_to_int(n) for n in nums]
>>> print r == ints
1
>>> roman_to_int('VVVIV')
Traceback (most recent call last):
...
ValueError: input is not a valid roman numeral: VVVIV
>>> roman_to_int(1)
Traceback (most recent call last):
...
TypeError: expected string, got
>>> roman_to_int('a')
Traceback (most recent call last):
...
ValueError: input is not a valid roman numeral: A
>>> roman_to_int('IL')
Traceback (most recent call last):
...
ValueError: input is not a valid roman numeral: IL
"""
try:
input = input.upper()
except AttributeError:
raise ValueError('expected string, got %s' % type(input))
# map of (numeral, value, maxcount) tuples
roman_numeral_map = (('M', 1000, 3), ('CM', 900, 1),
('D', 500, 1), ('CD', 400, 1),
('C', 100, 3), ('XC', 90, 1),
('L', 50, 1), ('XL', 40, 1),
('X', 10, 3), ('IX', 9, 1),
('V', 5, 1), ('IV', 4, 1), ('I', 1, 3))
result, index = 0, 0
for numeral, value, maxcount in roman_numeral_map:
count = 0
while input[index: index +len(numeral)] == numeral:
count += 1 # how many of this numeral we have
if count > maxcount:
raise ValueError('input is not a valid roman numeral: %s' % input)
result += value
index += len(numeral)
if index < len(input): # There are characters unaccounted for.
raise ValueError('input is not a valid roman numeral: %s'%input)
else:
return result
def roman_to_int_wrapper(s):
'''
Convert a roman numeral to an integer.
:param s: input string
:return: A simple wrapper that returns None when no valid number is given as input.
'''
try:
return roman_to_int(s)
except:
return None
|
e0fd487dce785fd825fe9988bdc51033a4cb0cc3 | Mwnesbitt/mastermind | /mastermind.py | 3,454 | 3.921875 | 4 | import sys
import cbreakstrat
import cmakestrat
import helperfunctions
def runGame(rounds, colors, slots, codemakestrategy, codebreakstrategy):
rounds=int(rounds)
colors=int(colors)
slots=int(slots)
history=[]
"""
The way implementing a game works is that runGame keeps track of the state of the game with the "history" object. The state of the
game is simply what guesses have been made and what were their grades. That combined with # of total rounds, # of colors, and # of slots
is all that a strategy has available to make a guess.
The history object is a list of the results of different rounds. A particular round is a list with two items: the guess and its grade.
The guess is a string of digits, and the grade is a list of 2 numbers-- the black pegs and white pegs.
"""
code = cmakestrat.cmakestratHelper(codemakestrategy, rounds, colors, slots)
"""
^^^There has to be a better way than using the helper methods I made, but they work for now.
Something like: cmakestrat.codemakestrategy(rounds, colors, slots)
Below: Now we start looping through the rounds-- this process builds up the history object
after every guess from a cbreakstrat method, and then hands the new history back to
that method to make another guess on. runGame and whatever cbreakstrat method was
selected pass the action back and forth until the game is over.
"""
while rounds>0:
guess=cbreakstrat.cbreakstratHelper(codebreakstrategy,rounds, colors, slots, history) #check your indexing on what the strats are expecting-- round n or n-1?
roundgrade=helperfunctions.gradeguess(colors, slots, code, guess)
temp=[]
temp.append(guess)
temp.append(roundgrade)
history.append(temp)
if(codemakestrategy=="askAHuman" or codebreakstrategy=="askAHuman"):
print("round "+str(len(history)))
for item in history:
print(item)
rounds = rounds-1
if(roundgrade[0]==slots):
return ("broken",code,len(history))
if(rounds==0):
return ("unbroken",code,len(history))
def main(): #now that the wrapper is built, we may not need a main method. We're not deleting anything just yet, but consider streamlining.
#main method assumes that setting up a game, the user will define a 5-tuple:
#number of rounds, number of colors, number of slots, codemaking strategy, codebreaking strategy
if (len(sys.argv) != 6):
print("pre-screen")
print("Here are the params required to run this program:")
print("mastermind.py rounds colors slots cmakestrat cbreakstrat")
for item in sys.argv:
print(item)
sys.exit(0)
#try:
outcome=runGame(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5])
if(outcome[0]=="broken"):
print("Code Broken!")
print("Code was: "+outcome[1]+". It took you "+str(outcome[2])+" guesses to get this.")
elif(outcome[0]=="unbroken"):
print("That was the last round!")
print("Code not broken. Code was: "+outcome[1]+". It took you "+str(outcome[2])+" guesses to get this.")
else:
print("An error has occurred")
"""
except:
print("Exception catch")
print("Here are the params required to run this program:")
print("python mastermind.py rounds colors slots cmakestrat cbreakstrat")
for item in sys.argv:
print(item)
sys.exit(0)
"""
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main() |
dbe4051377f5c0cb2e0a690a555c390ed02c2254 | mia2628/Python | /Machine_Learning/1.Pythonic Code/Asterisk.py | 828 | 3.71875 | 4 | # 단순곱셉 활용, 제곱연산, 가변인자 활용 등 다양하게 사용
# def asterisk_test(a, *args):
# print(a,args)
# print(type(args))
#
# asterisk_test(1,2,3,4,5,6)
# def asterisk_test(a, **kargs):
# print(a,kargs)
# print(type(kargs))
#
# asterisk_test(1,b=2,c=3,d=4,e=5,f=6)
# def asterisk_test(a, *args):
# print(a,args)
# print(type(args))
#
# asterisk_test(1,(2,3,4,5,6))
#
# #Unpacking container
# def asterisk_test(a, args):
# print(a,*args)
# print(type(args))
#
# asterisk_test(1,(2,3,4,5,6))
# data = ([1,2], [3,4], [5,6])
# print(*data)
#
# for data in zip(*([1,2],[3,4],[5,6])):
# print(sum(data))
#
# def asterisk_test(a,b,c,d,e=0):
# print(a,b,c,d,e)
#
# data = {"d":1, "c":2, "b":3, "e":56}
# asterisk_test(10, **data)
|
49a066b1f78761d36795370c9739edb9e296d468 | chinuteja/CSPP1 | /cspp1-practice/cspp1 assignment/m4/p2/bob_counter.py | 312 | 3.9375 | 4 | '''
author:teja
date:8/2/2018
'''
def main():
'''
this function gives no of bobs in a string
'''
s_1 = input()
x_1 = len(s_1)
count = 0
for i in range(0, x_1, 1):
if s_1[i:i+3] == "bob":
count = count + 1
print(count)
if __name__ == "__main__":
main()
|
6b55ad0cce98d262d38a647da0b6a61f3fc26c3f | Techsrijan/techpython | /twodarray.py | 376 | 3.75 | 4 | from numpy import *
arr=array([
[1,2,3],
[4,5,6],
[7,8,9]
])
print(arr)
print(arr.ndim)
print(arr.shape)
print(arr.size)
# converting 2 d arrray into 1-d array
arr2=arr.flatten()
print(arr2)
arr3=array([
[1,2,3,4,5,6],
[4,5,6,1,2,3]
])
print(arr3.shape)
print(arr3.reshape(3,4))
print(arr3.ndim)
arr5=arr3.reshape(2,2,3)
print(arr5.ndim)
print(arr5)
|
fe62ccad67e06f480b59a25454ad4d9b0aa9340a | sam1208318697/Leetcode | /Leetcode_env/2019/8_27/Intersection_of_Two_Arrays_II.py | 1,310 | 3.84375 | 4 | # 350. 两个数组的交集 II
# 给定两个数组,编写一个函数来计算它们的交集。
# 示例 1:
# 输入: nums1 = [1,2,2,1], nums2 = [2,2]
# 输出: [2,2]
# 示例 2:
# 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# 输出: [4,9]
# 说明:输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。我们可以不考虑输出结果的顺序。
# 进阶:
# 如果给定的数组已经排好序呢?你将如何优化你的算法?
# 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
# 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
class Solution:
def intersect(self, nums1, nums2):
res = []
if len(nums1) > len(nums2):
cur = nums1
pos = nums2
else:
cur = nums2
pos = nums1
dict = {}
for i in cur:
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
for i in pos:
if i in dict:
if dict[i] >= 1:
dict[i] -= 1
res.append(i)
return res
sol = Solution()
print(sol.intersect([1,2,2,1],[1,2,3,4,5,6]))
|
8e3708fdb99e4e4506a153f6c435ee33d4ae5e85 | VikramadityaJakkula/one-week-python | /queuearray.py | 919 | 3.703125 | 4 | from exceptions import Empty
class queuearray:
def __int__(self):
self.data = []
self.size = 0
self.front = 0
def __len__(self):
return len(self.size)
def first(self):
if self.is_empty:
raise "Queue is empty"
else:
return (self.data[self.front])
def is_empty(self):
return (self.size == 0)
def enqueue(self,e):
self.data.append(e)
self.size = self.size + 1
def dequeue(self):
if self.size == 0:
raise "Queue is Empty"
value = self.data[self.front]
self.data[self.front] = None
self.size = self.size -1
self.front = self.front + 1
return value
c = queuearray()
print(c)
c.enqueue(10)
c.enqueue(20)
c.enqueue(30)
print(c,c.size)
print(c.dequeue())
print(c,c.size)
|
1ebd50691b45a7f4ba755e4cd1726f3e3e75ad37 | a1dien/Python3Learning | /IntroductionToStrings/tuples.py | 966 | 4.3125 | 4 | tuple1 = (1, 2, 3)
tuple2 = ('Hello', 'one')
tuple3 = 544, 0.233, 'tst'
print(tuple1)
print(tuple2)
print(tuple3)
print(type(tuple3))
print(tuple1[1])
#tuple1[1] = 1 #not work for tuples
new_tuple = tuple1[0], 22, tuple1[2]
print(new_tuple)
x = y = z = 12
print(x, y, z)
x, y, z = 12, 13, 14
print(x, y, z)
person_tuple = ('John', 'Smith', 1967)
f_name, l_name, year_birth = person_tuple
print(f_name, l_name, year_birth)
t1 = (1, 2, 3, 1, 5, 1)
print(t1.count(1))
print(t1.count(5))
greetings_tuple = ('hi', 'hey', 'hi', 'hello')
print(greetings_tuple.count('hi'))
print (t1.index(5))
print(greetings_tuple.index('hi'))
#Создайте объект tuple, описывающий компьютер и распакуйте его в соответствующие переменные. Выведите переменные вызвав функцию print() один раз
computer = ('PC', '16GB', '500GB')
type, ram, hd = computer
print(type, ram, hd)
|
a6550bf6b1f27577c4a47b36810908489b2170f8 | HugoPorto/PythonCodes | /CursoPythonUnderLinux/Aula0021ComparandoTipos/ComparandoTipos.py | 541 | 4.15625 | 4 | #!/bin/usr/env python
#-*- coding:utf8 -*-
var = input("Informe uma variavel para ser analisada: ")
tipo = type(var)
if tipo == int:
print 'Você infomrou um numero inteiro.'
elif tipo == float:
print 'Você infomrou um numero ponto flutuante.'
elif tipo == str:
print 'Você infomrou uma string.'
elif tipo == dict:
print 'Você infomrou um dicionario.'
elif tipo == list:
print 'Você infomrou uma lista.'
elif tipo == tuple:
print 'Você infomrou uma tupla.'
else:
print 'Desconheço esse tipo de variável.'
|
10cd60a326c2ee6645836d5472d993559ab1876f | Ivanqza/Python | /Python Fundamentals/FinalsExamTraining/PROBLEM 3.py | 1,148 | 3.875 | 4 | data = input()
records = {}
while not data == "Log out":
splitted_data = data.split(": ")
command = splitted_data[0]
username = splitted_data[1]
if command == "New follower":
if username not in records:
records[username] = {"likes": 0, "comments": 0}
elif command == "Like":
count = int(splitted_data[2])
if username not in records:
records[username] = {"likes": count, "comments": 0}
else:
records[username]["likes"] += count
elif command == "Comment":
if username not in records:
records[username] = {"likes": 0, "comments": 1}
else:
records[username]["comments"] += 1
elif command == "Blocked":
if username not in records:
print(f"{username} doesn't exist.")
else:
records.pop(username)
data = input()
sorted_info = sorted(records.items(), key=lambda kvp: (-(kvp[1]["likes"] + kvp[1]["comments"]), kvp[0]))
print(f"{len(records)} followers")
for username, values in sorted_info:
total = values["likes"] + values["comments"]
print(f"{username}: {total}")
|
e9d1bd6799fb8a974dd4eee6a364b2f3957f401f | rolfis/ableton-pack-info | /src/utils.py | 1,128 | 3.9375 | 4 | import os
def get_size_format(b, factor=1024, suffix="B"):
"""
Scale bytes to its proper byte format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if b < factor:
return f"{b:.2f}{unit}{suffix}"
b /= factor
return f"{b:.2f}Y{suffix}"
def get_directory_size(directory):
"""Returns the `directory` size in bytes."""
total = 0
try:
# print("[+] Getting the size of", directory)
for entry in os.scandir(directory):
if entry.is_file():
# if it's a file, use stat() function
total += entry.stat().st_size
elif entry.is_dir():
# if it's a directory, recursively call this function
total += get_directory_size(entry.path)
except NotADirectoryError:
# if `directory` isn't a directory, get the file size then
return os.path.getsize(directory)
except PermissionError:
# if for whatever reason we can't open the folder, return 0
return 0
return total
|
690270017925c11b5b85132673ce6905a25763ab | ProfessorKazarinoff/piston_motion | /piston_motion.py | 2,274 | 3.609375 | 4 | """
Piston Motion Animation using Python and Matplotlib
Author: Peter D. Kazarinoff, 2019
MIT License
"""
# import necessary packages
import numpy as np
from numpy import pi, sin, cos, sqrt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# input parameters
r = 1.0 # crank radius
l = 4.0 # connecting rod length
rot_num = 4 # number of crank rotations
increment = 0.1 # angle incremement
# create the angle array, where the last angle is the number of rotations*2*pi
angle_minus_last = np.arange(0, rot_num * 2 * pi, increment)
angles = np.append(angle_minus_last, rot_num * 2 * pi)
X1 = np.zeros(len(angles)) # array of crank x-positions: Point 1
Y1 = np.zeros(len(angles)) # array of crank y-positions: Point 1
X2 = np.zeros(len(angles)) # array of connecting rod x-positions: Point 2
Y2 = np.zeros(len(angles)) # array of connecting rod y-positions: Point 2
# find the crank and connecting rod positions for each angle
for index, theta in enumerate(angles, start=0):
x1 = r * cos(theta) # x-cooridnate of the crank: Point 1
y1 = r * sin(theta) # y-cooridnate of the crank: Point 1
x2 = 0 # x-coordinate of the rod: Point 2
# y-coordinate of the rod: Point 2
y2 = (r * cos(theta - pi / 2)) + (
sqrt((l ** 2) - (r ** 2) * ((sin(theta - pi / 2)) ** 2))
)
X1[index] = x1 # store the crank x-position
Y1[index] = y1 # store the crank y-position
X2[index] = x2 # store the connecting rod x-position
Y2[index] = y2 # store the connecting rod y-position
# set up the figure and subplot
fig = plt.figure()
ax = fig.add_subplot(
111, aspect="equal", autoscale_on=False, xlim=(-4, 4), ylim=(-2, 6)
)
ax.grid()
line, = ax.plot([], [], "o-", lw=5, color="g")
# initialization function
def init():
line.set_data([], [])
return (line,)
# animation function
def animate(i):
thisx = [0, X1[i], X2[i]]
thisy = [0, Y1[i], Y2[i]]
line.set_data(thisx, thisy)
return (line,)
# call the animation
ani = animation.FuncAnimation(
fig, animate, init_func=init, frames=len(X1), interval=20, blit=True, repeat=False
)
## to save animation, uncomment the line below:
## ani.save('piston_motion.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
# show the animation
plt.show()
|
ea5ce4981d92c0856bcf63bfc97afb19590ad787 | Uche-Clare/python-challenge-solutions | /Darlington/phase1/python Basic 1/day 9 solution/qtn9.py | 345 | 4.09375 | 4 | #program to get the size of an object in bytes.import sys
import sys
str1 = "one"
str2 = "four"
str3 = "three"
print()
print("Memory size of '"+str1+"' = "+str(sys.getsizeof(str1))+ " bytes")
print("Memory size of '"+str2+"' = "+str(sys.getsizeof(str2))+ " bytes")
print("Memory size of '"+str3+"' = "+str(sys.getsizeof(str3))+ " bytes")
print() |
911c1e7e79aeb4ea647a791892f26620d27b6847 | ankitchoudhary49/Daily-Assignments | /Assignment-12.py | 583 | 4.03125 | 4 | #Assignment 12
#Question 1: Print the Current Day
import datetime
print(datetime.date.today())
x=datetime.date.today()
print("OR")
print(x.strftime("%A, %B %d,%Y"))
print("*"*50)
#Question 2: Use Webbrowser Module in Python
'''
import webbrowser
google=input("Enter your google search here: ")
webbrowser.open_new_tab("https://www.google.co.in/search?btnG=1&q=%s"%google)
'''
#Question 3: Rename All the Files in a Directory And Convert Them Into .jpg File Format
import os
print(os.getcwd())
os.rename('Empty file 1.txt','file 1.jpg')
os.rename('Empty file 2.txt','file 2.jpg')
|
73597b62cdc7d9f33b7fba31713ed951c065c11a | Papashanskiy/face-recognition | /face-recognition/src0/recognition/description/dlib1/__init__.py | 3,036 | 3.78125 | 4 | # This example shows how to use dlib's face recognition tool. This tool maps
# an image of a human face to a 128 dimensional vector space where images of
# the same person are near to each other and images from different people are
# far apart. Therefore, you can perform face recognition by mapping faces to
# the 128D space and then checking if their Euclidean distance is small
# enough.
#
# When using a distance threshold of 0.6, the dlib model obtains an accuracy
# of 99.38% on the standard LFW face recognition benchmark, which is
# comparable to other state-of-the-art methods for face recognition as of
# February 2017. This accuracy means that, when presented with a pair of face
# images, the tool will correctly identify if the pair belongs to the same
# person or is from different people 99.38% of the time.
#
# Finally, for an in-depth discussion of how dlib's tool works you should
# refer to the C++ example program dnn_face_recognition_ex.cpp and the
# attendant documentation referenced therein.
import os
import cv2
import dlib
from imutils import face_utils
from core.image import shape_to_np
from .utils.eyes import eyes_are_closed, align_eyes_angle
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
class EyesAreClosed(Exception):
pass
class FaceDescriptor(object):
def __init__(self):
# Load all the models we need: a shape predictor
# to find face landmarks so we can precisely localize the face and the
# face recognition model.
data = lambda name: os.path.join(THIS_DIR, 'data', name)
self.sp = dlib.shape_predictor(data('shape_predictor_68_face_landmarks.dat'))
self.facerec = dlib.face_recognition_model_v1(data('dlib_face_recognition_resnet_model_v1.dat'))
def draw_shape(self, img, shape):
img = img.copy()
for point in shape.parts():
# img[point.x, point.y] = (0, 0, 200)
# print("draw", (point.x, point.y))
cv2.circle(img, (point.x, point.y), 1, (0, 255, 0), -1)
return img
def to_vector(self, img, debug=False, ignore_closed_eyes=True):
"""
Возвращаем вектор, в данном случае 128 точек
:param img:
:return:
"""
rect = dlib.rectangle(0, 0, img.shape[0], img.shape[1])
shape = self.sp(img, rect)
shape_np = shape_to_np(shape)
if ignore_closed_eyes and eyes_are_closed(shape_np):
raise EyesAreClosed()
img_rotated = align_eyes_angle(img, shape_np)
shape_rotated = self.sp(img_rotated, rect)
if debug:
#img_debug = face_utils.visualize_facial_landmarks(img_rotated, shape_to_np(shape_rotated))
img_debug = self.draw_shape(img_rotated, shape_rotated)
else:
img_debug = img_rotated
face_descriptor = self.facerec.compute_face_descriptor(img_rotated, shape_rotated)
return img_debug, face_descriptor, shape_to_np(shape).tolist()
|
d05a4a6e512001e125fda21d0188b176452583f1 | iSumitYadav/python | /Binary_Tree/LevelOrderTraversal_O(n)2.py | 808 | 4.1875 | 4 | class node:
def __init__(self, key):
self.data = key
self.left = self.right = None
def height(root):
if root is None:
return 0
return max(height(root.left), height(root.right)) + 1
def printSecondary(root, level):
if root is None:
return
if level == 1:
print(root.data, end = ' ')
printSecondary(root.left, level-1)
printSecondary(root.right, level-1)
def printLevelOrder(root):
h = height(root)
for x in range(1, h+1):
printSecondary(root, x)
print('\n')
root = node(1)
root.left = node(2)
root.right = node(3)
root.left.left = node(4)
root.left.right = node(5)
root.right.left = node(6)
root.right.right = node(7)
print('Level Order of tree is ')
printLevelOrder(root)
print('Level Order Traversal O(n)2') |
1b9d6759d4b98714b3558bff695a9c580e7aa23b | sergio9977/SUMMER_BOOTCAMP_2018_Python | /lesson8/task1/class_definition.py | 569 | 4.25 | 4 | """
Un objeto combina variables y funciones en una sola entidad.
Los objetos obtienen sus variables y funciones de las clases.
Las clases son esencialmente plantillas para crear tus objetos.
Se puede pensar en un objeto como una única estructura de datos
que contiene datos y funciones.
Las funciones de los objetos se llaman métodos.
la variable "my_object" contiene un objeto
de la clase "MyClass" que contiene la variable y la función "foo"
"""
class MyClass:
variable = 12
def foo(self):
print("Hello from function foo")
my_object = MyClass()
|
c9cd84cce80ff47435183f8869e8cd91c89fdc66 | drinkingcode/PythonDemo | /python-02.py | 487 | 3.859375 | 4 | #对真假值取反
print(not True) #False
#if-else
a = 3
b = 5
if a>b:
print('a > b')
elif a<b:
print('a < b')
else:
print('a = b')
#循环
#while...:
#for...in...:
i = 0
while i<10:
print('while-i: ' + str(i)) #打印0-9
i = i + 1
for i in range(0,10,1): #这里的range是python中的一个函数
print('for-in-i: ' + str(i)) #打印0-9
#错误处理 (待定)
try:
a = 10
b = 0
c = a/b
except:
print('this is an error')
|
f18ce4f257b1aebcbf52b0cb8b3abeeeda1e2e14 | aobrien89/cti110 | /M3HW2_SoftwareSales_O'Brien.py | 431 | 3.671875 | 4 | # CTI-110
# M3HW2 - Software Sales
# Anthony O'Brien
# 09/19/2017
#
def main():
purchase = float(input("Packages purchased: "))
if purchase <= 9:
print("No discount :(")
elif purchase <= 19:
print("10% discount!")
elif purchase <= 49:
print("20% discount!")
elif purchase <= 99:
print("30% discount!")
elif purchase >= 100:
print("40% discount!")
main()
|
5e677c590a5134c62fe7e99a107ad0cf4e449570 | ddoplayer2012/leecode | /递归/3爬楼梯.py | 1,092 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
每一级楼梯都是由 n - 2 + n-1 级楼梯组成,所以可以等效于斐波那契数列
"""
class Solution ( object ):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
由于必定是n -1 和 n-2 组成的 f (n),所以可以用斐波那契的解法来求解
"""
if n < 2:
return n
first = 1
second = 2
for i in range(3, n + 1):
third = first + second
first = second
second = third
return second
'''
高手解法
f=[]
f.append(1)
f.append(2)
if n==1:
return 1
if n==2:
return 2
for i in range(2,n):
f.append(f[i-1]+f[i-2])
return f[-1]
'''
a = Solution()
b = a.climbStairs(5)
print(b) |
20c28fef79ae1e7d6806ce574f7433dfc5604480 | rogeroger-yu/LeetCode | /sort_1_bubble.py | 289 | 3.828125 | 4 | class Solution:
def bubble_sort(self, nums):
if not nums:
return
size = len(nums)
for i in range(size):
for j in range(i):
if nums[j] > nums[i]:
nums[i], nums[j] = nums[j], nums[i]
return nums
|
b066a5b71f4d85e145871a89f3fd2ffd1f5b8bac | ykataoka/top100Like | /36_ValidSudoku.py | 1,159 | 3.59375 | 4 | class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
return (self.isValid_rows(board)
and self.isValid_cols(board)
and self.isValid_3x3(board))
# time: O(N^2), N = 9
def isValid_rows(self, board):
for row in board:
row = [r for r in row if r != '.']
if len(set(row)) != len(row):
return False
return True
# time: O(N^2), N = 9
def isValid_cols(self, board):
for col in zip(*board):
col = [c for c in col if c != '.']
if len(set(col)) != len(col):
return False
return True
# time: O(N^2), N = 9
def isValid_3x3(self, board):
for i in [0, 3, 6]:
for j in [0, 3, 6]:
tmp = []
for x in range(i, i+3):
for y in range(j, j+3):
tmp.append(board[y][x])
tmp = [t for t in tmp if t != '.']
if len(set(tmp)) != len(tmp):
return False
return True
|
09f93a5ce5ddbd9588c24ffd070a93930fbf5171 | Gaurav-2804/Scheduler | /shedule.py | 1,090 | 3.5 | 4 | import pandas as pd
import datetime
from plyer import notification
import time
def sendnot(msg):
notification.notify(
title = msg,
message = "Study Hard",
app_icon = "./book.ico",
timeout = 5
)
if __name__ == "__main__":
df = pd.read_excel("Tt.xlsx")
#print(df)
while True: # to continue program
now = datetime.datetime.now().strftime("%H:%M")
day = datetime.datetime.now().strftime("%A")
for index, item in df.iterrows():
#print(index, item['Time'])
tm = item['Time'].strftime("%H:%M")
dy = item['Day']
msg = item['Subject']
if(dy == day):
if(tm == now):
sendnot(msg)
time.sleep(60*60) #program will run for every 1 hr
# instead of while loop you can use task scheduler in your OS to run your program every time you turn your system on
# Also you can run pythonw .\shedule.py so that even if you turn off terminal code will run |
75fc2490445dfcaf1b2367bf664b19259b115596 | sumeyragulsoyy/RNN-ATM-DATA | /rnn_Atm.py | 2,308 | 3.65625 | 4 | # Recurrent Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd.read_csv('b9383file.csv')
training_set = dataset_train.iloc[:,2:3].values
# Feature Scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)
# Creating a data structure with 60 timesteps and t+1 output
X_train = []
y_train = []
for i in range(30, 367):
X_train.append(training_set_scaled[i-30:i, 0])
y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
# Reshaping
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# Part 2 - Building the RNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
# Initialising the RNN
regressor = Sequential()
# Adding the input layer and the LSTM layer
regressor.add(LSTM(units = 3, input_shape = (None, 1)))
# Adding the output layer
regressor.add(Dense(units = 1))
# Compiling the RNN
regressor.compile(optimizer = 'rmsprop', loss = 'mean_squared_error')
# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)
# Part 3 - Making the predictions and visualising the results
# Getting the real stock price for February 1st 2012 - January 31st 2017
dataset_test = pd.read_csv('b9383real.csv')
test_set = dataset_test.iloc[:,2:3].values
real_data = np.concatenate((training_set[0:367], test_set), axis = 0)
# Getting the predicted stock price of 2017
scaled_real_data = sc.fit_transform(real_data)
inputs = []
for i in range(367, 397):
inputs.append(scaled_real_data[i-30:i, 0])
inputs = np.array(inputs)
inputs = np.reshape(inputs, (inputs.shape[0], inputs.shape[1], 1))
predicted_data = regressor.predict(inputs)
predicted_data = sc.inverse_transform(predicted_data)
# Visualising the results
plt.plot(real_data[367:], color = 'red', label = 'Real Cash Withdraw')
plt.plot(predicted_data, color = 'blue', label = 'Predicted Cash Withdraw')
plt.title('Cash withdraw Prediction')
plt.xlabel('Time')
plt.ylabel('Cash withdraw ')
plt.legend()
plt.show() |
efbd6ca1721f946437897e2dc2675348036bdda5 | aryasoni98/Python | /Strings/manacher.py | 908 | 4.03125 | 4 | def palindromic_length(center, diff, string):
if (center - diff == -1 or center + diff == len(string)
or string[center - diff] != string[center + diff]):
return 0
return 1 + palindromic_length(center, diff + 1, string)
def palindromic_string(input_string):
max_length = 0
new_input_string = ""
output_string = ""
for i in input_string[:len(input_string) - 1]:
new_input_string += i + "|"
new_input_string += input_string[-1]
for i in range(len(new_input_string)):
length = palindromic_length(i, 1, new_input_string)
if max_length < length:
max_length = length
start = i
for i in new_input_string[start - max_length:start + max_length + 1]:
if i != "|":
output_string += i
return output_string
if __name__ == "__main__":
n = input()
print(palindromic_string(n))
|
2ebd013f9731fc2a15ad0eaaeee120fa5a6e72a9 | De-Yonis/My_first_project | /game.py | 1,332 | 3.734375 | 4 | import random
def vocab_file():
VocabD = {}
with open("spanish.txt") as f:
for line in f:
(key, value) = line.split(",")
VocabD[key] = value.rstrip()
return VocabD
def game():
response = input("Type Yes below to start:\n").lower()
if response == "yes":
VocabD = vocab_file()
question_list = list(VocabD.keys())
random.shuffle(question_list)
correct = 0
wrong = 0
for word in question_list:
presented = "{}"
print(" ")
print(presented.format(word))
inputAnswer = input("Answer: ").capitalize()
if inputAnswer == (VocabD[word]):
print("Great, thats correct \n")
correct += 1
else:
print("Wrong mate")
print("The correct answer is", VocabD[word])
wrong += 1
tally = "You have {} Correct and {} Wrong"
print(" ")
print(tally.format(correct, wrong))
repeat = input("Shall we go again?:\n ").lower()
if repeat == "Yes":
again()
else:
print("See you later")
else:
print("See you later")
def again():
return game()
print("Hello and Welcome to the quiz Yonis")
game()
|
e504beb328788bf82289d4f63daa7f2130622c5c | MysteriousSonOfGod/py | /string.py | 1,758 | 3.828125 | 4 | print('This\'s a\n \ttest')
print(r'This\'s a test') # for raw output
#Multiline text
print('''Dear Sir,
I came to know about the latest update you shared via email earlier this week from Dinesh.
Regards,
Ujjwal''')
""" This is
a multi line
comment
"""
print('---end---')
text = 'Testing Testing what are you testing?'
# slicing
print(text[0:5])
print(text)
# itirate individual characters in a string
for char in text:
print(char)
print(text.upper())
print(text.encode(encoding='utf-8',errors='strict'))
print(text.swapcase())
# validate case insensitive
feeling = input('How are you feeling?')
if feeling.lower() == 'great':
print('Me too')
else:
print('Have a good day')
print(text.lower().islower())
# substring in string
if 'Hello' in 'Hello World!':
print('Hello')
else:
print('Oops!')
# startswith() endswith()
if text.startswith('Test'):
print('Text starts with "Test"')
if text.endswith('ing'):
print('Text ends with "ing"')
# Validation
while True:
password = input('Please enter password of your choice: ')
if password.isalnum():
break
print('Try Entering Alpha Numeric Password')
# join() and split()
text1 = text.split()
print(text1)
print(', '.join(text1))
# split in the occurance of substring in the string and join
splitted = 'MyABCnameABCisABCSimon'.split('ABC')
print(splitted)
print(' '.join(splitted))
# justify - rjust(), ljust(), center()
print('Ujjwal'.rjust(20,'*'))
print('Ujjwal'.rjust(20))
print('Ujjwal'.ljust(20,'-'))
print('Ujjwal'.center(20,'-'))
# strip() from the ends of the text
# Typically used to take out white spaces in the text
print(text.strip('Tg?'))
# Regardless of the order 'ting?' gets removed from the right
print(text.rstrip('gi?tn'))
|
76ca01c95d7a1d2033f03035bf0159e034a6d0f0 | immayurpanchal/sudoPlacementGFG1 | /SudoPlacements/ArrayAndSearching/reverseArray.py | 209 | 3.53125 | 4 | for _ in range(int(input())):
size = int(input())
array = list(map(int, input().split()))
index = len(array) - 1
while index>=0:
print(array[index],end=' ')
index-=1
print() |
a48cfa7c6ce3cb31d67faf91a0d38f6d4f79e587 | kasa4565/DesignPatterns | /04Prototype/Students/2019/JarzembinskiBartlomiej/prototype/computer_prototype.py | 496 | 3.5625 | 4 | from abc import ABC, abstractmethod
import copy
class ComputerPrototype(ABC):
@abstractmethod
def clone(self):
pass
class Computer(ComputerPrototype):
def __init__(self, case, motherboard, power_supply, cpu, gpu, drive, ram):
self._case = case
self._motherboard = motherboard
self._power_supply = power_supply
self._cpu = cpu
self._gpu = gpu
self._drive = drive
self._ram = ram
def clone(self):
return copy.copy(self) |
1183632d6e70e20fd3961f29aba3a7c185729a0b | gitandlucsil/python_classes | /complet_curs/functions/var_scope.py | 369 | 3.890625 | 4 | def printName():
global name
print(name)
name = "andre"
print(name)
def sumList(list_num):
global sumvalue
for num in list_num:
if type(num) is list:
sumList(num)
else:
sumvalue += num
return sumvalue
name = "jose"
printName()
sumvalue = 0
print(sumList([5,7,2,3,8]))
print(sumList([[5,7],[2,3,8]])) |
6a1bbc059b9e720742f56d6a90a16b1f0dd28a6f | mtarbit/Project-Euler-Problems | /e062.py | 433 | 3.703125 | 4 | #!/usr/bin/python
# $Id$
""" """
__author__ = 'Matt Tarbit <matt.tarbit@isotoma.com>'
__docformat__ = 'restructuredtext en'
__version__ = '$Revision$'[11:-2]
def e62():
cubes = {}
n = 345
while True:
p = n ** 3
k = ''.join(sorted(str(p)))
n += 1
if not cubes.get(k):
cubes[k] = [p]
else:
cubes[k].append(p)
if len(cubes[k]) >= 3:
print k, cubes[k]
if len(cubes[k]) == 5:
return
if __name__ == "__main__":
e62()
|
65e155eb588042abb6b218c1eed5785d5185b948 | RonakR/CTCI-Solutions | /2_Linked_Lists/7_Intersection/intersection_1.py | 865 | 3.625 | 4 | def intersection_1(firstll, secondll):
diff = len(firstll) - len(secondll)
headfll, headsll = firstll.head, secondll.head
if diff > 0:
headfll = fix_length(headfll, diff)
elif diff < 0:
headfll = fix_length(headsll, abs(diff))
return find_intersection(headfll, headsll)
def fix_length(ll, diff):
while diff:
ll = ll.next
diff -= 1
return ll
def find_intersection(headfll, headsll):
intersection = False
currentfll = headfll
currentsll = headsll
while currentfll is not None:
if not intersection:
if currentfll is not currentsll:
intersection = False
if not intersection and (currentfll == currentsll):
intersection = currentfll
currentfll = currentfll.next
currentsll = currentsll.next
return intersection |
5de52e7c34749b8d5b56b927e6585b1413a62d91 | ChangxingJiang/LeetCode | /1601-1700/1641/1641_Python_1.py | 500 | 3.546875 | 4 | import functools
class Solution:
@functools.lru_cache(None)
def countVowelStrings(self, n: int, t=5) -> int:
if t == 0:
return 0
if n == 1:
return t
ans = 0
for i in range(1, t + 1):
ans += self.countVowelStrings(n - 1, i)
return ans
if __name__ == "__main__":
print(Solution().countVowelStrings(1)) # 5
print(Solution().countVowelStrings(2)) # 15
print(Solution().countVowelStrings(33)) # 66045
|
7d730ef76e68a0051937dc781ad297bb864ceda7 | Amit-Yadav21/Loop-Question-python | /loop-meraki.py | 1,308 | 3.671875 | 4 | # Q...............................................1
# x= 1
# while x<=100:
# print(x)
# x=x+1
# Q................................................2
# n=int(input("Enter how to sum number "))
# i=0
# sum=0
# while i<=n:
# sum=sum+i
# i=i+1
# if i==100:
# break
# print("the sum is - ",sum)
# Q ..............................................3
# i=1
# sum=0
# while i<=10:
# a=int(input("Enter number "))
# i+=1
# sum=sum+a
# print("Total-",sum)
# Q...............................................4
# a=0
# while a<100:
# a+=1
# if a%2==0:
# print(-a)
# else:
# print(a)
# Q...................................counter
# count=1
# while count<=5:
# print("Working")
# count = count + 1
# Q........counter Example.........1
# i = 891
# while i < 931:
# z = i - 890
# if z % 3 == 0:
# print(z)
# i = iExample + 1
# Q...............................Example.2
# i=0
# while i<=50:
# if i!=0:
# print(i)
# i=i+5
# Q..............................Example.3
# i=49
# while i<=98:
# i=i+2
# print(i)
# Q..............................Example.3(a)
# i=50
# while i<=100:
# if i%2!=0:
# print(i)
# i=i+1
# Q..............................Example.3(b)
# i=400
# while i>=350:
# z=i-300
# if z%2!=0:
# print(z)
# i=i-1
# Q............................Example.4
|
c5ad0115c1013e4afa7f764666f0edb1fe58e5c2 | edyoda/DSA-with-Rudrangshu-310321 | /Sorting/find_longest_consecutive_subsequence.py | 619 | 4 | 4 | # Python3 program to find longest
# contiguous subsequence
def findLongestConseqSubseq(arr, n):
ans = 0
count = 0
arr.sort()
v = []
v.append(arr[0])
for i in range(1, n):
if (arr[i] != arr[i - 1]):
v.append(arr[i])
for i in range(len(v)):
# Check if the current element is
# equal to previous element +1
if (i > 0 and v[i] == v[i - 1] + 1):
count += 1
else:
count = 1
ans = max(ans, count)
return ans
# Driver code
arr = [ 1, 2, 2, 3, 5, 7, 8, 10, 4, 13 ]
n = len(arr)
print("Length of the Longest contiguous subsequence is",
findLongestConseqSubseq(arr, n))
|
ad764cdf91f272a260165d8eb5f231ad25f31d3a | shubhamoli/solutions | /ctic/3.4.py | 892 | 4.0625 | 4 | """
3.4 - Implement queue using stack data structure
we'll be using two stacks for this
"""
class myQueue():
def __init__(self):
self.stk1 = []
self.stk2 = []
def push(self, val: int):
self.stk1.append(val)
# compromising pop() operation
# O(n) instead of O(1)
def pop(self) -> int:
while self.stk1:
self.stk2.append(self.stk1.pop())
item = self.stk2.pop() if len(self.stk2) else None
while self.stk2:
self.stk1.append(self.stk2.pop())
return item
def top(self) -> int:
return self.stk1[-1]
def size(self) -> int:
return len(self.stk1) + len(self.stk2)
if __name__ == "__main__":
q = myQueue()
q.push(1)
q.push(2)
q.push(3)
assert q.pop() == 1
q.push(4)
q.push(5)
assert q.pop() == 2
assert q.top() == 5
|
e7b92a5b9ad2b68d78d76a699db3953394720eca | digitaldave0/tutorials | /python/elif.py | 403 | 4 | 4 | a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
#nested if
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
a = 33
b = 200
if b > a:
pass |
0a9d3ae2c2561a0118c6811452f7649a36f03fe3 | rwzhao/working-open-data-2014 | /notebooks/Day_07_G_Calculating_Diversity.py | 14,248 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=1>
# Goals
# <markdowncell>
# * Learn about how to use the Census variables around Hispanic origin to calculate quantities around diversity (remembering the [Racial Dot Map](http://bit.ly/rdotmapintro) as our framing example)
# <codecell>
%pylab --no-import-all inline
# <codecell>
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame, Series, Index
import pandas as pd
from itertools import islice
# <codecell>
import census
import us
import settings
# <markdowncell>
# The census documentation has example URLs but needs your API key to work. In this notebook, we'll use the IPython notebook HTML display mechanism to help out.
# <codecell>
c = census.Census(key=settings.CENSUS_KEY)
# <codecell>
# generators for the various census geographic entities of interest
def states(variables='NAME'):
geo={'for':'state:*'}
states_fips = set([state.fips for state in us.states.STATES])
# need to filter out non-states
for r in c.sf1.get(variables, geo=geo):
if r['state'] in states_fips:
yield r
def counties(variables='NAME'):
"""ask for all the states in one call"""
# tabulate a set of fips codes for the states
states_fips = set([s.fips for s in us.states.STATES])
geo={'for':'county:*',
'in':'state:*'}
for county in c.sf1.get(variables, geo=geo):
# eliminate counties whose states aren't in a state or DC
if county['state'] in states_fips:
yield county
def counties2(variables='NAME'):
"""generator for all counties"""
# since we can get all the counties in one call,
# this function is for demonstrating the use of walking through
# the states to get at the counties
for state in us.states.STATES:
geo={'for':'county:*',
'in':'state:{fips}'.format(fips=state.fips)}
for county in c.sf1.get(variables, geo=geo):
yield county
def tracts(variables='NAME'):
for state in us.states.STATES:
# handy to print out state to monitor progress
# print state.fips, state
counties_in_state={'for':'county:*',
'in':'state:{fips}'.format(fips=state.fips)}
for county in c.sf1.get('NAME', geo=counties_in_state):
# print county['state'], county['NAME']
tracts_in_county = {'for':'tract:*',
'in': 'state:{s_fips} county:{c_fips}'.format(s_fips=state.fips,
c_fips=county['county'])}
for tract in c.sf1.get(variables,geo=tracts_in_county):
yield tract
# <codecell>
def block_groups(variables='NAME'):
# http://api.census.gov/data/2010/sf1?get=P0010001&for=block+group:*&in=state:02+county:170
# let's use the county generator
for county in counties(variables):
geo = {'for':'block group:*',
'in':'state:{state} county:{county}'.format(state=county['state'],
county=county['county'])
}
for block_group in c.sf1.get(variables, geo):
yield block_group
def blocks(variables='NAME'):
# http://api.census.gov/data/2010/sf1?get=P0010001&for=block:*&in=state:02+county:290+tract:00100
# make use of the tract generator
for tract in tracts(variables):
geo={'for':'block:*',
'in':'state:{state} county:{county} tract:{tract}'.format(state=tract['state'],
county=tract['county'],
tract=tract['tract'])
}
for block in c.sf1.get(variables, geo):
yield block
# <codecell>
# msa, csas, districts, zip_codes
def msas(variables="NAME"):
for state in us.STATES:
geo = {'for':'metropolitan statistical area/micropolitan statistical area:*',
'in':'state:{state_fips}'.format(state_fips=state.fips)
}
for msa in c.sf1.get(variables, geo=geo):
yield msa
def csas(variables="NAME"):
# http://api.census.gov/data/2010/sf1?get=P0010001&for=combined+statistical+area:*&in=state:24
for state in us.STATES:
geo = {'for':'combined statistical area:*',
'in':'state:{state_fips}'.format(state_fips=state.fips)
}
for csa in c.sf1.get(variables, geo=geo):
yield csa
def districts(variables="NAME"):
# http://api.census.gov/data/2010/sf1?get=P0010001&for=congressional+district:*&in=state:24
for state in us.STATES:
geo = {'for':'congressional district:*',
'in':'state:{state_fips}'.format(state_fips=state.fips)
}
for district in c.sf1.get(variables, geo=geo):
yield district
def zip_code_tabulation_areas(variables="NAME"):
# http://api.census.gov/data/2010/sf1?get=P0010001&for=zip+code+tabulation+area:*&in=state:02
for state in us.STATES:
geo = {'for':'zip code tabulation area:*',
'in':'state:{state_fips}'.format(state_fips=state.fips)
}
for zip_code_tabulation_area in c.sf1.get(variables, geo=geo):
yield zip_code_tabulation_area
# <codecell>
list(islice(msas(), 1))
# <codecell>
list(islice(csas(), 1))
# <codecell>
districts_list = list(islice(districts(), 1))
districts_list
# <codecell>
list(islice(zip_code_tabulation_areas(), 1))
# <markdowncell>
# **Note**: There are definitely improvements to be made in these generators. One of the most important would be to limit the generators to specific geographies -- typically, we don't want to have all the blocks in the country but the ones in a specific area. A good exercise to rewrite our generators to allow for limited geography.
# <markdowncell>
# We can compare the total number of tracts we calculate to:
#
# https://www.census.gov/geo/maps-data/data/tallies/tractblock.html
#
# and
#
# https://www.census.gov/geo/maps-data/data/docs/geo_tallies/Tract_Block2010.txt
# <headingcell level=1>
# Hispanic or Latino Origin and Racial Subcategories
# <markdowncell>
# http://www.census.gov/developers/data/sf1.xml
#
# compare to http://www.census.gov/prod/cen2010/briefs/c2010br-02.pdf
#
# I think the P0050001 might be the key category
#
# * P0010001 = P0050001
# * P0050001 = P0050002 + P0050010
#
# P0050002 Not Hispanic or Latino (total) =
#
# * P0050003 Not Hispanic White only
# * P0050004 Not Hispanic Black only
# * P0050006 Not Hispanic Asian only
# * Not Hispanic Other (should also be P0050002 - (P0050003 + P0050004 + P0050006)
# * P0050005 Not Hispanic: American Indian/ American Indian and Alaska Native alone
# * P0050007 Not Hispanic: Native Hawaiian and Other Pacific Islander alone
# * P0050008 Not Hispanic: Some Other Race alone
# * P0050009 Not Hispanic: Two or More Races
#
# * P0050010 Hispanic or Latino
#
# P0050010 = P0050011...P0050017
#
# From [Hispanic and Latino Americans (Wikipedia)](https://en.wikipedia.org/w/index.php?title=Hispanic_and_Latino_Americans&oldid=595018646):
#
# <blockquote>While the two terms are sometimes used interchangeably, Hispanic is a narrower term which mostly refers to persons of Spanish speaking origin or ancestry, while Latino is more frequently used to refer more generally to anyone of Latin American origin or ancestry, including Brazilians.</blockquote>
#
# and
#
# <blockquote>The Census Bureau's 2010 census does provide a definition of the terms Latino or Hispanic and is as follows: “Hispanic or Latino” refers to a person of Cuban, Mexican, Puerto Rican, South or Central American, or other Spanish culture or origin regardless of race. It allows respondents to self-define whether they were Latino or Hispanic and then identify their specific country or place of origin.[52] On its website, the Census Bureau defines "Hispanic" or "Latino" persons as being "persons who trace their origin [to]... Spanish speaking Central and South America countries, and other Spanish cultures".</blockquote>
#
# In the [Racial Dot Map](http://bit.ly/rdotmap): "Whites are coded as blue; African-Americans, green; Asians, red; Hispanics, orange; and all other racial categories are coded as brown."
#
# In this notebook, we will relate the Racial Dot Map 5-category scheme to the P005\* variables.
# <codecell>
# let's get the total population -- tabulated in two variables: P0010001, P0050001
# P0050002 Not Hispanic or Latino (total)
# P0050010 Hispanic or Latino
r = list(states(('NAME','P0010001','P0050001','P0050002','P0050010')))
r[:5]
# <codecell>
# Hispanic/Latino origin vs not-Hispanic/Latino
# Compare with http://www.census.gov/prod/cen2010/briefs/c2010br-02.pdf Table 1
# Hispanic/Latino: 50477594
# non-Hispanic/Latino: 258267944
df=DataFrame(r)
df[['P0010001', 'P0050001','P0050002','P0050010']] = \
df[['P0010001', 'P0050001','P0050002','P0050010']].astype('int')
df[['P0010001', 'P0050001', 'P0050002', 'P0050010']].sum()
# <codecell>
# is the total Hispanic/Latino population and non-Hispanic populations the same as reported in
# http://www.census.gov/prod/cen2010/briefs/c2010br-02.pdf Table 1
(df['P0050010'].sum() == 50477594,
df['P0050002'].sum() == 258267944)
# <codecell>
# How about the non-Hispanic/Latino White only category?
# P0050003
# total should be 196817552
df = DataFrame(list(states('NAME,P0050003')))
df['P0050003'] = df['P0050003'].astype('int')
df.P0050003.sum()
# <headingcell level=1>
# Converting to Racial Dot Map Categories
# <markdowncell>
# SUGGESTED EXERCISE: write a function `convert_to_rdotmap(row)` tha takes an input Python dict that has the keys:
# * NAME
# * P005001, P005002...,P0050016, P0050017
#
# and that returns a Pandas Series with the following columns:
#
# * Total
# * White
# * Black
# * Asian
# * Hispanic
# * Other
# * Name (note lowercase)
#
# that correspond to those used in the Racial Dot Map.
#
# Also write a function def convert_P005_to_int(df) that converts all the P005\* columns to `int`
# <codecell>
# USE a little convience function to calculate the variable names to be used
def P005_range(n0,n1):
return tuple(('P005'+ "{i:04d}".format(i=i) for i in xrange(n0,n1)))
P005_vars = P005_range(1,18)
P005_vars_str = ",".join(P005_vars)
P005_vars_with_name = ['NAME'] + list(P005_vars)
P005_vars_with_name
# <codecell>
# HAVE YOU TRIED THE EXERCISE....IF NOT....TRY IT....HERE'S ONE POSSIBLE ANSWER#
# http://manishamde.github.io/blog/2013/03/07/pandas-and-python-top-10/#create
def convert_P005_to_int(df):
# do conversion in place
df[list(P005_vars)] = df[list(P005_vars)].astype('int')
return df
def convert_to_rdotmap(row):
"""takes the P005 variables and maps to a series with White, Black, Asian, Hispanic, Other
Total and Name"""
return pd.Series({'Total':row['P0050001'],
'White':row['P0050003'],
'Black':row['P0050004'],
'Asian':row['P0050006'],
'Hispanic':row['P0050010'],
'Other': row['P0050005'] + row['P0050007'] + row['P0050008'] + row['P0050009'],
'Name': row['NAME']
}, index=['Name', 'Total', 'White', 'Black', 'Hispanic', 'Asian', 'Other'])
# <codecell>
from census import Census
import settings
from settings import CENSUS_KEY
import time
from itertools import islice
def P005_range(n0,n1):
return tuple(('P005'+ "{i:04d}".format(i=i) for i in xrange(n0,n1)))
P005_vars = P005_range(1,18)
P005_vars_str = ",".join(P005_vars)
# http://manishamde.github.io/blog/2013/03/07/pandas-and-python-top-10/#create
def convert_to_rdotmap(row):
"""takes the P005 variables and maps to a series with White, Black, Asian, Hispanic, Other
Total and Name"""
return pd.Series({'Total':row['P0050001'],
'White':row['P0050003'],
'Black':row['P0050004'],
'Asian':row['P0050006'],
'Hispanic':row['P0050010'],
'Other': row['P0050005'] + row['P0050007'] + row['P0050008'] + row['P0050009'],
'Name': row['NAME']
}, index=['Name', 'Total', 'White', 'Black', 'Hispanic', 'Asian', 'Other'])
def normalize(s):
"""take a Series and divide each item by the sum so that the new series adds up to 1.0"""
total = np.sum(s)
return s.astype('float') / total
def entropy(series):
"""Normalized Shannon Index"""
# a series in which all the entries are equal should result in normalized entropy of 1.0
# eliminate 0s
series1 = series[series!=0]
# if len(series) < 2 (i.e., 0 or 1) then return 0
if len(series) > 1:
# calculate the maximum possible entropy for given length of input series
max_s = -np.log(1.0/len(series))
total = float(sum(series1))
p = series1.astype('float')/float(total)
return sum(-p*np.log(p))/max_s
else:
return 0.0
def convert_P005_to_int(df):
# do conversion in place
df[list(P005_vars)] = df[list(P005_vars)].astype('int')
return df
def diversity(r):
"""Returns a DataFrame with the following columns
"""
df = DataFrame(r)
df = convert_P005_to_int(df)
# df[list(P005_vars)] = df[list(P005_vars)].astype('int')
df1 = df.apply(convert_to_rdotmap, axis=1)
df1['entropy5'] = df1[['Asian','Black','Hispanic','White','Other']].apply(entropy,axis=1)
df1['entropy4'] = df1[['Asian','Black','Hispanic','White']].apply(entropy,axis=1)
return df1
# <codecell>
# states
r=list(states(P005_vars_with_name))
diversity(r)
# <codecell>
# counties
r = list(counties(P005_vars_with_name))
# <codecell>
df2 = diversity(r)
# <codecell>
df2.sort_index(by='entropy5',ascending=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.