text stringlengths 37 1.41M |
|---|
import math as k
pi=k.pi
dimension=[float(c) for c in input().split(" ")]
len_wire=dimension[1]
area=dimension[0]
max_area= (len_wire**2)/(4*pi)
if max_area>=area:
print("Diablo is happy!")
else:
print("Need more materials!")
|
# solutions.py
"""Volume IB: Testing.
<Name>
<Date>
"""
import math
# Problem 1 Write unit tests for addition().
# Be sure to install pytest-cov in order to see your code coverage change.
def addition(a, b):
return a + b
def smallest_factor(n):
"""Finds the smallest prime factor of a number.
Assume n is a positive integer.
"""
if n == 1:
return 1
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return i
return n
# Problem 2 Write unit tests for operator().
def operator(a, b, oper):
if type(oper) != str:
raise ValueError("Oper should be a string")
if len(oper) != 1:
raise ValueError("Oper should be one character")
if oper == "+":
return a + b
if oper == "/":
if b == 0:
raise ValueError("You can't divide by zero!")
return a/float(b)
if oper == "-":
return a-b
if oper == "*":
return a*b
else:
raise ValueError("Oper can only be: '+', '/', '-', or '*'")
# Problem 3 Write unit test for this class.
class ComplexNumber(object):
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def conjugate(self):
return ComplexNumber(self.real, -self.imag)
def norm(self):
return math.sqrt(self.real**2 + self.imag**2)
def __add__(self, other):
real = self.real + other.real
imag = self.imag + other.imag
return ComplexNumber(real, imag)
def __sub__(self, other):
real = self.real - other.real
imag = self.imag - other.imag
return ComplexNumber(real, imag)
def __mul__(self, other):
real = self.real*other.real - self.imag*other.imag
imag = self.imag*other.real + other.imag*self.real
return ComplexNumber(real, imag)
def __truediv__(self, other):
if other.real == 0 and other.imag == 0:
raise ValueError("Cannot divide by zero")
bottom = (other.conjugate()*other*1.).real
top = self*other.conjugate()
return ComplexNumber(top.real / bottom, top.imag / bottom)
def __eq__(self, other):
return self.imag == other.imag and self.real == other.real
def __str__(self):
return "{}{}{}i".format(self.real, '+' if self.imag >= 0 else '-',
abs(self.imag))
# Problem 5: Write code for the Set game here
class Hand(object):
def __init__(self, filename):
if filename[-4:] != ".txt":
raise ValueError("This is not a valid file name.")
self.name = filename
file = open(filename, 'r')
cards = []
newlines = []
lines = file.readlines()
for line in lines:
newlines.append(line.replace("\n",""))
for line in newlines:
if line not in cards:
cards.append(line)
for card in cards:
if len(card) != 4:
raise ValueError("There is a 'card' with invalid number of attributes.")
for c in card:
if int(c) < 0 or int(c)>2:
raise ValueError("There is a 'card' with invalid attributes.")
if len(cards) != 12:
raise ValueError("There are not exactly 12 cards.")
self.cards = cards
file.close()
def setcount(self):
count = 0
def validset(card1, card2, card3):
checks = []
for i in range(4):
if (card1[i] == card2[i] and card1[i] == card3[i]) or (int(card1[i]) + int(card2[i]) + int(card3[i]) == 3):
checks.append(True)
if checks == [True, True, True, True]:
return True
else:
return False
for i in range(10):
for j in range(i+1, 11):
for k in range(j+1,12):
if validset(self.cards[i], self.cards[j], self.cards[k]):
count += 1
return count
|
# -*- coding: utf-8 -*-
# 读取文件~~~~~~~~放到主程序里面运行
import codecs
import os
def read_file(file_path):
f = codecs.open(file_path, 'r', "utf-8")
lines = f.readlines()
word_list=[] #在这里添加个新列表 word_list,用于存放遍历出来的单词
for line in lines:
line = line.strip()
words = line.split(' ')
word_list.extend(words) #extend函数的意思就是(用新列表扩展原来的旧列表)
#这里把words里面的列表单词添加到word_list这个空白列表里面
#再次重复遍历单词
return word_list #直到lines没有可以遍历的大东西了,返回 word_list 给read_file函数
def main():
words=read_file('data1/dt01.txt') #调用read_file函数的结果 word_list 并赋值words
print words # 打印 read_file 函数的结果 word_list
print'一共有%d个单词'%(len(words)) # 用 len函数可以看到总数
if __name__ == '__main__':
main() |
##################################################################
# Section 5
# Computer Project #7
# Strings, lists, files and their various operators
##################################################################
import random
def scramble_word(word_str):
"""Takes a single word from the file and returns a scrambled word
according to the following rules
1) First and last letter are preserved in the original positions
2) Seems like a waste to shuffle something of length 3 or less
3) Punctuation postions are preserved"""
if len(word_str) > 3:
letters_list = list(word_str)
if letters_list[-1] = '.':
letters_to_shuffle = letters_list[1:-2]
random.shuffle(letters_to_shuffle)
shuffled_str = ''.join(letters_to_shuffle)
word_scrambled = letters_list[0] + shuffled_str + letters_list[-2] + letters_list[-1]
letters_to_shuffle = letters_list[1:-1]
random.shuffle(letters_to_shuffle)
shuffled_str = ''.join(letters_to_shuffle)
word_scrambled = letters_list[0] + shuffled_str + letters_list[-1]
if len(word_str) <= 3:
word_scrambled = word_str
return word_scrambled
def scramble_line(line_str):
"""Takes an entire line of text and returns a new line with each word
scrambled using the scarmble_word function"""
shuffled_list = ''
word_list = line_str.split(' ')
for word in word_list:
shuffled_list += scramble_word(word) + ' '
return(shuffled_list)
def open_read_file(file_name_str):
"""Continuously prompts until it can open a file"""
while True:
try:
file_obj = open(file_name_str,"r")
break
# If file name is incorrect, reprompt
except IOError:
print("Bad file name, try again")
file_name_str = input("Open what file: ")
return file_obj
def main():
file_write = input('Name of file to write: ')
fileObjOut = open(file_write,"w")
file_read = input('Name of file to read: ')
file = open_read_file(file_read)
for line in file:
scrambled_line_str = scramble_line(line)
fileObjOut.write(scrambled_line_str)
main()
|
class Taxpayer:
income = 0
name = "Brenda"
def __init__ (self,name,icome):
self.income=icome
self.name = name
self.minimum = minimum
self.ValidateIncome()
self.ValidateName()
self.ValidateMinimum()
def ValidateIncome(self):
if self.income.isnumeric()== False:
raise ValueError("The income {} is not numeric".format(self.income))
def ValidateName(self):
if self.name.string():
raise ValueError("The name{} is not a string".format(self.name))
def ValidateMinimum(self):
if flaot(self.income) <10000:
raise ValueError("The income{}is below minimum ")
def calculate_tax(self):
return float(self.income)*0.3
income = input("What is the income")
name = input ("What is your name?")
employee = Taxpayer(name,income,minimum)
print(employee.calculate_tax())
|
# Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
#Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)
#Feature scaling = numbers should be almost at the same range
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)
|
#!/usr/bin/env python3
"""
Solution to Python Challenge #11.
Start: http://www.pythonchallenge.com/pc/return/5808.html
The start page has a picture in it (URL below). It looks rather fuzzy, and the
title of the page mentions odd and even. This gives me the idea that there are
two images "phased" together somehow. If you zoom in, you can see a
checkerboard pattern confirming this. So, you get your imaging library, and
split it into the four images corresponding to the four blocks of the
checkerboard. Turns out there were just two images, each duplicated twice.
The darker one says "evil", which is the key to the next level. This is
another one I had to hard code the ending to, but at least I get to display the
answer first.
"""
import webbrowser
from io import BytesIO
import requests
from PIL import Image
IMG_URL = r'http://huge:file@www.pythonchallenge.com/pc/return/cave.jpg'
URL = r'http://huge:file@www.pythonchallenge.com/pc/return/%s.html'
def main():
response = requests.get(IMG_URL)
image = Image.open(BytesIO(response.content))
image_pixels = image.load()
width, height = image.size
xodd = Image.new('RGB', (width//2, height//2))
xodd_pixels = xodd.load()
yodd = Image.new('RGB', (width//2, height//2))
yodd_pixels = yodd.load()
bothodd = Image.new('RGB', (width//2, height//2))
bothodd_pixels = bothodd.load()
even = Image.new('RGB', (width//2, height//2))
even_pixels = even.load()
for x in range(width):
for y in range(height):
if x % 2 == 1 and y % 2 == 1:
bothodd_pixels[x//2, y//2] = image_pixels[x, y]
elif x % 2 == 1:
xodd_pixels[x//2, y//2] = image_pixels[x, y]
elif y % 2 == 1:
yodd_pixels[x//2, y//2] = image_pixels[x, y]
else:
even_pixels[x//2, y//2] = image_pixels[x, y]
bothodd.show()
xodd.show()
yodd.show()
even.show()
webbrowser.open(URL % 'evil')
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
"""Solution to Python Challenge #6.
Start: http://www.pythonchallenge.com/pc/def/channel.html
The title of this challenge is "now there are pairs", and the depiction is of a
zipper. This is really unfair, because pairs + zipper = zip()!! Right? Wrong!
Instead of the builtin function zip(), this one is all about the zipfile module.
If you request channel.zip, you find an archive with tons of text files, and a
readme. And what do you know? They have the same linked list structure as that
other challenge. So, you iterate through them until you get to the end, when
you see the instructions to put together the comments. With the help of the
zipfile module doc, you find the getinfo() function, and string together the
comments into a wordart that says "hockey".
But you're not done. Instead of the answer *just* being hockey, you have to
look at the letters that each block letter are drawn out of -- 'oxygen'. And
that's the answer. I had to hardcode that one too, because there's no simple
Python equivalent.
"""
import webbrowser
from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO
import re
def main():
url = 'http://www.pythonchallenge.com/pc/def/channel.zip'
con = urlopen(url)
zf_bytes = con.read()
zf_file = BytesIO(zf_bytes)
zf = ZipFile(zf_file, 'r')
fn = '%d.txt'
curr = 90052
message = b''
while True:
message += zf.getinfo(fn % curr).comment
text = zf.open(fn % curr).read().decode('utf8')
print(text)
match = re.search('nothing is (?P<nothing>\d+)', text)
if match is None:
break
curr = int(match.group('nothing'))
print(message.decode('utf8'))
webbrowser.open('http://www.pythonchallenge.com/pc/def/oxygen.html')
if __name__ == "__main__":
main()
|
print("Hello World!")
x = "Hello Python"
print(x)
y = 42
print(y)
name = "Crystal"
print("Hello", name,"!")
print("Hello " + name + "!")
num = 2
print(f"Hello", {num}, "!")
print(f"Hello {num}!")
food_one = "prime rib"
food_two = "pizza"
print("I love to eat {} and {}.".format(food_one, food_two))
print(f"I love to eat {food_one} and {food_two}.") |
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
dogs = [
{'breed': 'chihuahua', 'age': '7 years old'},
{'breed': 'pomeranian', 'age': '5 years old'},
]
# iterateDictionary(students)
# # should output: (it's okay if each key-value pair ends up on 2 separate lines;
# # bonus to get them to appear exactly as below!)copy
# first_name - Michael, last_name - Jordan
# first_name - John, last_name - Rosales
# first_name - Mark, last_name - Guillen
# first_name - KB, last_name - Tonel
# Create a function iterateDictionary(some_list) that, given a list of dictionaries, the function loops through each dictionary in the list and prints each key and the associated value.
def iterateDictionary(some_list):
print(some_list)
for diction in some_list:
print(diction)
for key, val in diction.items():
print(key, "-", val)
iterateDictionary(students) |
def divide(a, b):
print(f"{a} dividido por {b} é {a / b}")
def subtrai(a, b):
print(f"{a} - {b} = {a - b}")
def soma(a, b):
print(f"{a} + {b} = {a + b}")
divide(20, 2)
subtrai(43, 1)
soma(41, 1)
|
str=input("enter the string\n")
r=" "
for c in str:
r=c+r
print(r)
|
# global variable using for finding the position of the number
POS=-1
def search (list,n):
i=0
while i<len(list):
if list[i]==n:
globals()['pos']=i
return True
i+=1
else:
return False
list = [5,8,6,9,7]
n=9
if search(list,n):
print("found at",pos)
else:
print("not found") |
class student:
# 1st statement
def sum (self,a=None,b=None,c=None):
s=0
if a!=None and b!=None and c!=None:
s=a+b+c
elif a!=None and b!=None:
s=a+b
else: s=a
return s
s1=student()
# overloading method we have two value but three parameters so by using overloading methods with 1st statement
# we solve it
print(s1.sum(5,5))
|
class student:
uversity='lahore leads university'
def __init__(self,m1,m2,m3):
self.m1= m1
self.m2 = m2
self.m3 = m3
def avg(self):
return (self.m1+self.m2+self.m3)/3
# this is a class method
@classmethod
def info(cls):
return cls.uversity
# this is a static method
@staticmethod
def info1():
print("this is studnet class")
s1=student(34,67,32)
s2=student(89,32,12)
# print he avg
print(s1.avg())
# print class method
print(student.info())
# print static method
student.info1()
|
class student:
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
# add methods
def __add__(self, other):
m1=self.m1+other.m1
m2=self.m2+other.m2
m3 = self.m3 + other.m3
s3=student(m1,m2,m3)
return s3
# greter method
def __gt__(self, other):
m1 = self.m1 + other.m1
m2 = self.m1 + other.m2
m3 = self.m3 + other.m3
if m1>m2:
return True
else:
return False
def __str__(self):
return self.m1,self.m2
s1=student(58,69,5)
s2=student(60,65,5)
s3=s1+s2
print(s3.m1,s3.m2)
if s1>s2:
print("s1 wins")
else:
print("s2 wins")
print(s1.__str__())
|
#Q3:
# For two dimensional grid, indexing the cells is done by 2-dimensional raster scan
# For example, a 2-dimensional grid with sizes (L1, L2)=(4, 3) (it means there are 4 columns and 3 rows)
# In this grid, coordinates (x1, x2)=(2, 1) corresponds to index I = 6, and vice versa.
# Given 2-dimensional grid with sizes (L1, L2) = (50, 57)
# part a)
# Write a code to convert given coordinates to index (i.e. given x1 and x2, find index I)
# Input: 1st column: x1
# 2nd column: x2
# Output: 1st column: index
n = int(input("Enter the number of coordinates: "))
a = []
for _ in range(n):
a.append(list(map(int, input().rstrip().split())))
def coor_2index(a):
print (" ********* results *********")
print ("index")
for i in a:
index= i[0] + (i[1]*50)
print(index)
coor_2index(a)
#Part 2
#Write a code to convert given index to coordinates (i.e. given I, find coordinates x1 and x2)
#Input : 1st column: index
#Output: 1st column: x1
# 2nd column: x2
m = int(input("Enter the number of indexes: "))
b = []
for _ in range(m):
b.append(int(input()))
def index_2coor(a):
print (" ********* results *********")
print ('x1', 'x2')
for i in a:
x1= i % 50
x2= int(i/50)
print (x1, x2)
index_2coor(b) |
# Challenge 5:
#Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros.
#The function will print the decimal value of each fraction on a new line.
#Input Format: "arr" is an array of numbers .
# Output Format:
#1. A decimal representing of the fraction of positive numbers in the array compared to its size.
#2. A decimal representing of the fraction of negative numbers in the array compared to its size.
#3. A decimal representing of the fraction of zeros in the array compared to its size.
def plusMinus(arr):
a=0
b=0
c=0
for i in range(len(arr)):
if arr[i]>0:
a+=1
elif arr[i]<0:
b+=1
else:
c+=1
e= format((a/len(arr)),'.6f')
f= format((b/len(arr)),'.6f')
g= format((c/len(arr)),'.6f')
print (e +"\n"+f+"\n"+g)
plusMinus([-4, 3, -9, 0, 4, 1]) |
"""
prompt: Given a set S, return the power set P(S), which is
a set of all subsets of S.
Input: A String
Output: An Array with the power set of the input string
Example: S = "abc", P(S) = ['', 'a', 'b','c','ab','ac','bc','abc'] *
Note: There should not be any duplicates in the power set
('ab' and 'ba' are considered the same), and it will always
begin with an empty string ('')
"""
def power_set(str):
result=[]
result = permute_powerset(result,str,str)
print result
def permute_powerset(result,str,remain,sub=""):
result.append(sub)
for i in range(len(remain)):
temp=sub
sub=sub+remain[i]
result = permute_powerset(result,str,remain[i+1:],sub)
sub=temp
return result
def main():
str='abcd'
power_set(str)
if __name__ == '__main__':
main()
|
def popadanie(a,b,c,d,e):
if(c-a) ** 2 + (d-b) ** 2 <= e ** 2:
return 1
else:
return 0
try:
X0 = float(input('введите координату центра X0:'))
Y0 = float(input('введите координату центра Y0:'))
X = float(input('введите координату X:'))
Y = float(input('введите координату Y:'))
R = float(input('введите радиус R:'))
if R > 0:
if popadanie(X0,Y0,X,Y,R) == 1:
print('попал')
else:
print('не попал')
else:
print('радиус не может быть неположительным. введите другое значение')
except ValueError:
print('это не число. введите число') |
# 2.10. Reassignment and Updating Variables
# Reassignment
a = 5
b = a
print(a, b) 5 5
a = 3
print(a, b) 3 5
x = 15
y = x
x = 22
result: x=22 y=15
# Updating Variables
x = 12
x = x - 3
x = x + 5
x = x + 1
print(x) # 15
|
#Exercise 1
pi=3.141592653
r=5
volume=(4/3)*pi*r**3
print('The volume of a sphere with radius 5 is {:.2f}.'. format(volume))
#Exercise 2
bookcost=24.95*60*0.6
shipcost=3+0.75*59
cost=bookcost+shipcost
print('The total cost for 60 copies is {:.2f}.'. format(cost))
#Exercise 3, note:escape key is for python to ignore everything after the escape key '\'
start_time_hr=6+52/60
easy_pace_hr=(8+15/60)/60
tempo_pace_hr=(7+12/60)/60
running_time_hr=2*easy_pace_hr+3*tempo_pace_hr
breakfast_hr=start_time_hr+running_time_hr
#Exercise 4
percentage=(89-82)/89
print('The percentage increased is {:.1f}%'. format(percentage))
#Session 3
#1.1 number 5
#1.2 string
#1.3 nonetype
#1.4 number 3
#1.5 Boolean True
#1.6 Boolean False
#2.1 false
# false
# true
# false
import time
today = int(1437746094.5735958)
countdays=today//3600//24
print('The number of days starting from the epoch is {:d}.'. format(countdays))
|
#####################
#
# YouTube Channel Scraper
# Author: Ryan Rossiter <https://github.com/ryanrossiter>
#
# This script will scrape queries from Channel Crawler (https://www.channelcrawler.com/),
# check if the YouTube channel has an email available, and then it will output a CSV of
# the scraped channels.
#
# Usage:
# python3 main.py <ChannelCrawler Request ID> <CSV filename> [page limit] [start page]
# - <ChannelCrawler Request ID>: The channel crawler request ID (see below to get one)
# - <CSV filename>: Where the output csf should be written
# - [page limit]: Max pages to fetch from channel crawler
# - [start page]: Channel crawler page to start on
#
# To get a Channel Crawler request ID:
# - Go to https://www.channelcrawler.com/ and perform a search with whatever parameters you need
# - Take the URL of the results page, and copy the ID part (https://www.channelcrawler.com/eng/results/[ID IS HERE])
#
# WARNING: Part of this script will GET about pages from YouTube to check if there is a
# business email available (via CAPTCHA). YouTube will rate limit these requests if
# this script is run too many times. (Nothing a VPN can't solve 🙃)
#
#####################
import sys
import csv
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
import multiprocessing.pool
from tqdm import tqdm
CONCURRENT = 10
DEFAULT_PAGE_LIMIT = 20
EMAIL_REGEX = re.compile(r'((([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,}))', re.MULTILINE)
def print_usage():
print("USAGE: %s <ChannelCrawler Request ID> <CSV filename> [page limit] [start page]" % sys.argv[0])
def check_if_yt_channel_has_business_email(channel_url: str):
about_url = re.sub(r'/about$', '', channel_url) + '/about'
try:
about_contents = urlopen(about_url).read()
except Exception:
return False
else:
has_business_email = str(about_contents).find('"businessEmailLabel":') != -1
return has_business_email
def fetch_channel_crawler_page(id, page=1):
channels = [] # tuples of (title, href, category, description, subscribers, scraped_email, has_email_available)
url = "https://www.channelcrawler.com/eng/results/%s/page:%d" % (id, page)
with urlopen(url) as f:
soup = BeautifulSoup(f, "html.parser", from_encoding="iso-8859-1")
for el in soup.find_all('div', class_='channel'):
title = el.h4.a.get('title')
href = el.h4.a.get('href')
category = el.small.b.get_text()
description = el.find_all('a', recursive=False)[0].get('title')
subscribers = el.p.small.contents[0].strip().replace(' Subscribers', '')
email_re_match = EMAIL_REGEX.findall(description)
scraped_email = email_re_match[0][0] if len(email_re_match) else None
has_email_available = bool(scraped_email or check_if_yt_channel_has_business_email(href))
channels.append((title, href, category, description, subscribers, scraped_email, has_email_available))
return channels
def do_thread_work(ccid, page):
try:
channels = fetch_channel_crawler_page(ccid, page)
return "success", page, channels
except Exception as err:
return "error", page, []
def write_channels_to_csv(channels, filename):
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(channels)
def main(ccid, filename, start_page, end_page):
print(f'Fetching pages {start_page}..{end_page} from Channel Crawler results ID {ccid}...')
pool = multiprocessing.pool.ThreadPool(processes=CONCURRENT)
work_fn = lambda p: do_thread_work(ccid, p)
imap = pool.imap_unordered(work_fn, range(start_page, end_page))
channel_lists = list(tqdm(imap, total=(end_page - start_page)))
pool.close()
print("Done.")
channels = []
for (status, page, data) in channel_lists:
if status == "error":
print(f"Page {page} encountered an error")
else:
channels.extend(data)
write_channels_to_csv(channels, filename)
if __name__ == "__main__":
if len(sys.argv) < 3:
print_usage()
else:
ccid = sys.argv[1]
filename = sys.argv[2]
page_limit = int(sys.argv[3]) if len(sys.argv) > 3 else DEFAULT_PAGE_LIMIT
start_page = int(sys.argv[4]) if len(sys.argv) > 4 else 1
end_page = start_page + page_limit - 1
main(ccid, filename, start_page, end_page)
|
# 7-18
age = {"steve":32,"lia":28,"vin":45,"katie":38}
print(age)
agedata = [age]
print(agedata)
agedata
aged
import pandas
agedf = pandas.DataFrame(agedata)
print(agedf)
studentallinfo = [["steve",32,"male"],["lia",28,"female"],["vin",45,"male"],["katie",38,"female"]]
print(studentallinfo)
df = pandas.DataFrame(studentallinfo)
print(df)
owo = "this aint it cheif"
\
df2= pandas.DataFrame(studentallinfo, columns=["Name","Age", "Gender"])
print(df2)
import plotly
studentlist = [["steve",32,"male"],["lia",28,"female"],["vin",45,"male"],["katie",38,"female"]]
print(studentlist)
studentlistdf = pandas.DataFrame(studentlist, columns = ["name", "age","gender"],
index = [1,2,3,4])
print(studentlistdf)
#graph our data
import plotly
dir(plotly)
import plotly.graph_objs as go
agename = go.Bar(x=studentlistdf["name"], y=studentlistdf["age"])
#qwertyuiopasdfghjklzxcvbnm
import pandas as pd
from plotly.offline import plot
import plotly.graph_objs as go
df = pd.read_excel("GISdata.xlsx", sheet_name = "womenOccupation")
womenoccupation = go.Bar(x= df["occupation"], y=df["women"])
plot([womenoccupation])
fig = go.Figure(data=[womenoccupation])
plot(fig)
titles = go.Layout(title = "",
xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text="Occupation",
)
),
yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(text="Percentage",
)
)
)
fig
womenoccupation = go.Bar(x= df["occupation"], y=df["women"],
marker = {"color": df["women"], "colorscale":"YlOrRd"}
)
fig= go.Figure(data=[womenoccupation], layout = titles)
plot(fig)
|
A = list(map(int, input().split()))
for i in range(len(A)):
if(i == 0 and A[i] == 7):
pass
elif(i == 0 and A[i] != 7):
print(A[i], end=' ')
elif(A[i] == 7 or A[i-1] == 7):
pass
else:
print(A[i],end=' ') |
'''
You are given a list. Print the sum of the list numbers. If the list is empty then 0 gets printed. Also, the element 7 and the element next to it won't contribute to the sum.
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input containing the elements of the list separated by spaces.
Output Format:
For each testcase, in a new line, print the sum as directed.
Your Task:
This is a function problem. You don't need to take input. Complete the function realSum and return the sum.
Constraints:
1 <= T <= 100
Examples:
Input:
2
1 2 2 1
7 4 7 3 7 1 9
Output:
6
9
Explanation:
Testcase 2 : 7 and its next element are skipped. skip(7,4), skip(7,3), skip(7,1). Add only 9.
'''
#User function Template for python3
def realSum(mylist):
##Your code here
if(len(mylist) == 0):
return 0
else:
n=mylist
while 7 in n:
wheres7 = n.index(7)
n = n[0:wheres7]+n[wheres7+2:]
return sum(n)
testcases = int(input()) # testcases
while (testcases > 0):
mylist = [int(x) for x in input().split()]
print(realSum(mylist))
testcases -= 1 |
'''
Given a list of N positive integers, and a sum S. The task is to check if any pair exists in the array whose sum is present in the array.
Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the list, next line contains sum, and last line contains n elements.
Output Format:
For each testcase, in a new line, print "Yes" if such pair is present, else print "No".
Constraints:
1 <= T <= 100
1 <= N <= 104
1 <= L[i] <= 104
User Task:
The task is to complete the function pair_sum() which returns True if required pair is present, else return False.
Example:
Input:
1
7
8
1 2 3 3 5 5 5
Output:
Yes
Explanation:
Testcase 1: Pair with sum 8 is present in the array which is (5, 3).
'''
# User function Template for python3
# Function to check if pair
# with given sum exists
def pair_sum(dict, n, arr, sum):
# Your code here
# Hint: You can use 'in' to find if any key is in dict
for i in arr:
x = list(filter(lambda a: a != i, arr))
if (sum - i in x):
return True
return False
testcase = int(input())
# looping through testcases
while (testcase > 0):
n = int(input())
sum = int(input())
dict = {}
x = n
p = [int(i) for i in (input().split())]
for i in p:
dict[i] = 0
for i in p:
dict[i] += 1
if pair_sum(dict, n, p, sum) is True:
print("Yes")
else:
print("No")
testcase -= 1 |
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
times = ["Morning", "Afternoon", "Evening"]
i = 1
for d in days:
for t in times:
print ("OR (#sched[0].#time"+str(i)+" = :v"+str(i)+" AND #sched[0].#time"+str(i)+" = :vtrue) \\")
i = i + 1
|
ac=int(input("dati anul curent:"))
lc=int(input("dari luna curenta:"))
zc=int(input("dati ziua curenta:"))
an=int(input("dati anul nasterii:"))
ln=int(input("dati luna nasterii:"))
zn=int(input("dati ziua nasterii:"))
if ln>lc:
print (ac-an-1,"ani")
if ln==lc:
if zn>zc:
print(ac-an-1,"ani")
if zn<zc:
print(ac-an,"ani")
if zn==zc:
print(ac-an,"ani")
else:
print(ac-an,"ani")
|
x=int(input("dati numarul concurentului"))
if x>100:
print("se dau premii primilor 100")
if x%4==0:
print:("neagra")
if x%4==1:
print("alba")
if x%4==2:
print("rosie")
if x%4==3:
print("albastra") |
x=0
while (x==0):
valor = float(input('Insira o valor do produto: '))
if valor>=0:
x=1
else:
print('Valor Inválido')
while(x==1):
metodo = int(input('Método a pagar (1-à vista, 2-parcelado): '))
if metodo==1 or metodo==2:
if metodo==1:
f = int(input('1-Dinheiro/Cheque 2-Cartão: '))
y=0
while (y==0):
if f==1:
desconto = valor*0.9
print(f'Valor final com desconto: R$ {desconto}')
x=2
y=1
elif f==2:
desconto = valor*0.95
print(f'Valor final com desconto: R$ {desconto}')
x=2
y=1
else:
print('Opção não existe!')
elif metodo==2:
f = int(input('Somente cartão => 1-Parcelar em 2x, 2-Parcelar em 3x ou mais: '))
y=0
while (y==0):
if f==1:
print(f'Valor final parcelado em 2x: R$ {valor}')
y=1
x=2
elif f==2:
desconto = valor*1.2
print(f'Valor final parcelado em 3x ou mais: R$ {desconto}')
y=1
x=2
else:
print('Opção não existe!')
|
print(' '*5,'Identificação de números primos',' '*5)
pr = int(input('Digite um número: '))
tot = 0
for c in range(1, pr+1):
if pr%c==0:
print('\033[33m', end=' ')
tot += 1
else:
print('\033[31m', end=' ')
print(f'{c}', end='')
print(f'\033[m\nO número {pr} foi divisível {tot} vezes.')
if tot == 2:
print('Por isso ele é primo.')
else:
print('Por isso ele não é primo.') |
import random
m = ('='*8)
print(f'{m} Jokenpö {m}')
print(f'{" "*4} Vença a Máquina')
maq = random.randint(1,3)
esc = int(input('1-Pedra 2-Papel 3-Tesoura: '))
if maq==1:
if esc==1:
print('Empate!')
elif esc==2:
print('Você ganhou! Papel ganha de pedra.')
else:
print('Você perdeu! Tesoura perde para pedra.')
elif maq==2:
if esc == 2:
print('Empate!')
elif esc == 3:
print('Você ganhou! Tesoura ganha de papel.')
else:
print('Você perdeu! Papel ganha de pedra.')
elif maq==3:
if esc==3:
print('Empate!')
elif esc == 1:
print('Você ganhou! Pedra ganha de tesoura.')
else:
print('Você perdeu! Tesoura ganha de papel.')
else:
print('Opção Inválida') |
sl = float(input('Digite o valor do salário: '))
if sl>1250:
reajuste=sl*1.1
print(f'Novo salário: R${reajuste:.2f}')
else:
reajuste=sl*1.15
print(f'Novo salário R${reajuste:.2f}') |
from datetime import date
now = date.today().year
ano = int(input('Digite o ano de nascimento: '))
dif = now-ano
if dif < 100:
if dif < 9:
print(f' {dif} anos: Categoria Mirim')
elif dif < 14:
print(f' {dif} anos: Categoria Infantil')
elif dif < 19:
print(f' {dif} anos: Categoria Junior')
elif dif < 20:
print(f' {dif} anos: Categoria Sênior')
else:
print(f' {dif} anos: Categoria Master')
else:
print('Ano Inválido') |
x = 0
soma = 0
entradas = 0
while x!= 999:
n = int(input('Digite um número: '))
entradas +=1
if n == 999:
x = n
else:
soma += n
print(f'Tentativas: {entradas}')
print(f'Soma das tentativas: {soma}')
|
import random
num = int(input('Vou pensar em um número entre 0 e 5... Tente adivinhar: '))
rnum = random.randint(0,5)
print(f'Você venceu' if num==rnum else f'Você perdeu, eu pensei no número {rnum}')
|
'''
Created on 2 Oct 2014
@author: simonm
'''
import array
import re
def decode(hexstr, char):
# decode the input
hex_data = hexstr.decode('hex')
# and put it into a byte array
byte_arr = array.array('B', hex_data)
# decoded array
result_arr = [b ^ char for b in byte_arr]
# convert bytes to chars and append to string
return "".join("{:c}".format(b) for b in result_arr)
def is_sentence(string):
return re.match("^[\w '-?!.,:;()&]+$", string)
def print_decoded(hexstr):
# loop over all characters
for i in xrange(0, 256):
# and try to decode using every single one
string = decode(hexstr, i)
# if the result contains only spaces, alphanumeric characters
# and punctuation characters print it
if is_sentence(string):
print(string)
if __name__ == '__main__':
hex_encoded = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
print_decoded(hex_encoded)
|
import csv
column_name = ["name", "id", "email", "blood group"]
student1 = ["MD estiak ahmed", "17-33434-1", "estiak97@gmail.com", "B+"]
student2 = ["fahim ahmed", "17-33458-1", "fahim011@gmail.com", "A+"]
student3 = ["adnan harun", "19-33433-1", "adnanharun@gmail.com", "A+"]
student_list = [student1, student2, student3]
print(student_list)
# with open("student.csv", "w") as csvf:
# csv_writer = csv.writer(csvf, delimiter=',', quotechar="\"", quoting=csv.QUOTE_MINIMAL)
# csv_writer.writerow(column_name)
# for book in student_list:
# csv_writer.writerow(book)
|
import turtle
turtle.color("blue")
turtle.speed(0)
count=0
while count<18:
for i in range(4):
turtle.forward(150)
turtle.right(90)
turtle.right(20)
count+=1
turtle.exitonclick()
|
x=(1,2,3)
y='a','hello',1
z=1,
print(x)
print(y)
print(z)
print(x[0])
####### nested tuple ###########
tpl=(1,2.5,'a','hello',['a','b'],('a','b'))
print(tpl)
print(type(tpl))
print(tpl[0])
print(type(tpl[0]))
print(tpl[1])
print(type(tpl[1]))
print(tpl[2])
print(type(tpl[2]))
print(tpl[3])
print(type(tpl[3]))
print(tpl[4])
print(type(tpl[4]))
print(tpl[4][0])
print(type(tpl[4][0]))
print(tpl[5])
print(type(tpl[5]))
print(tpl[5][0])
print(type(tpl[5][0]))
#create a tuple by taking input is impossible. because tuple in non-mutable.
"""
a=()
n=int(input("enter the number of list="))
for i in range(n):
num=int(input())
a.append(num)
print(a)
""" |
while True:
n=int(input("input a number="))
if n<0:
print("it is negative")
continue
if n==0:
print("it is zero")
break
print("square=",n*n)
|
import turtle
turtle.speed(15)
turtle.shape("turtle")
turtle.color("maroon")
def star(length):
for i in range(12):
turtle.forward(length)
turtle.left(150)
counter=0
while counter<30:
star(150)
turtle.right(12)
counter+=1
turtle.exitonclick()
|
LIST=[]
n=int(input("enter the number of list="))
for i in range(n):
num=int(input())
LIST.append(num)
print(LIST) |
def avarage(LIST):
l=len(LIST)
Sum=sum(LIST)
result=Sum/l
return result
'''
create a list by using for loop
'''
LIST=[]
for i in range(5):
num=int(input())
LIST.append(num)
x=avarage(LIST)
print(x)
|
month=["february","march","may","june"]
print(month)
month.append("july")
month.append("august")#here one can't input more then one value
print(month)
month.insert(0,"january")
print(month)
month.insert(3,"april")
print(month)
month.remove("august")#it can't delete more then two item
print(month)
|
class DataExtracter:
"""For extracting data"""
def data_extract(self, file):
"""For extracting and returning data"""
file_data = [row.strip().split() for row in open('data/{}'.format(file)).readlines()]
return file_data
class DataAnalyzer:
"""For analyzing data"""
def __init__(self):
"""Initializing variables used in class"""
data_extract=DataExtracter()
self.data = tuple()
def min_diff_return(self, data_useable):
"""For finding minimum difference
rtype: tuple
"""
min_diff = abs(data_useable[0][1] - data_useable[0][2])
for data_row in data_useable:
if abs(float(data_row[2]) - float(data_row[1])) < min_diff:
min_diff = abs(float(data_row[2]) - float(data_row[1]))
self.data = data_row
return self.data
|
## Problems of apples and oranges
##https://www.hackerrank.com/challenges/apple-and-orange/problem?h_r=profile
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
count_app = 0
count_org = 0
n_app = len(apples)
n_org = len(oranges)
for i in range(n_app):
dist_a = 0
dist_a = apples[i] + a
if dist_a < s or dist_a > t:
continue
else:
count_app = count_app + 1
for i in range(n_org):
dist_o = 0
dist_o = oranges[i] + b
if dist_o > t or dist_o < s:
continue
else:
count_org = count_org + 1
print(count_app)
print(count_org)
if __name__ == '__main__':
st = input().split()
s = int(st[0])
t = int(st[1])
ab = input().split()
a = int(ab[0])
b = int(ab[1])
mn = input().split()
m = int(mn[0])
n = int(mn[1])
apples = list(map(int, input().rstrip().split()))
oranges = list(map(int, input().rstrip().split()))
countApplesAndOranges(s, t, a, b, apples, oranges)
|
class Node:
def __init__ (self,val):
self.value = val
self.left = None
self.right = None
def insert(self,data):
if self.value == data:
return False
elif self.value > data:
if self.left:
return self.left.insert(data)
else:
self.left = Node(data)
return True
else:
if self.right:
return self.right.insert(data)
else:
self.right = Node(data)
def find(self,data):
if self.value == data:
return True
elif self.value > data:
if self.left:
return self.left.find(data)
else:
return False
else:
if self.right:
return self.right.find(data)
else:
return False
def preorder(self):
if self:
print(str(self.value))
if self.left:
self.left.preorder()
if self.right:
self.right.preorder()
def postorder(self):
if self:
if self.left:
self.left.postorder()
if self.right:
self.right.postorder()
print(str(self.value))
def inorder(self):
if self:
if self.left:
self.left.postorder()
print(str(self.value))
if self.right:
self.right.postorder()
###Inside Class Tree, we are going to call the methods associated with Class Node. We can do this with the help of Dot(.) operator. In the following code, we have called insert,find,preorder,postorder methods from Node class inside Tree class.
##pre-order traversal is Root, Left, Right
##post-order traversal is Left,Right,Root
##In-order traversal is Left, Root, Right
class tree:
def __init__ (self):
self.root = None
def insert(self,data):
if self.root:
return self.root.insert(data)
else:
self.root = Node(data)
return True
def find(self,data):
if self.root:
return self.root.find(data)
else:
return False
def preorder(self):
print("Preorder")
self.root.preorder()
def postorder(self):
print("Postorder")
self.root.postorder()
def inorder(self):
print("Inorder")
self.root.inorder()
bst = tree()
bst.insert(14)
bst.insert(11)
bst.insert(17)
bst.insert(8)
bst.insert(12)
bst.preorder()
bst.postorder()
bst.inorder()
|
# ----------------------------------------------------------------------
# Title : Class Example
# Author : Jagannath Banerjee
# Date : 12/15/2017
# ----------------------------------------------------------------------
#Import Library Block
import os
#class definition
class library(object):
#initializing
def __init__(self,name,author,date,issue=False):
self.name = name
self.author = author
self.date = date
self.issue = issue
#getter
def getName(self):
return self.name
def getAuthor(self):
return self.author
def getAuthor(self):
return self.date
def getAuthor(self):
return self.issue
#setter
def upateDate(self,setUpdateDate):
self.date = setUpdateDate
#Txt string class
def __str__(self):
return "Person[Book name= " + self.name + " from " + self.author + " Issued sucessfully!] "
#Main Function
def main():
lib = library('Book1','Jagannath','12/15/2017',True)
print(lib.getName())
print(lib)
#Main Function Call
if __name__=="__main__":
main()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 17:55:36 2016
@author: jagan
"""
legnth= int (input ("input legnth:"))
width= int (input ("input width:"))
print ("area=",legnth*width)
print ("perimeter=",2*(legnth+width))
|
test_str = input('Enter the String:')
rep = int(input('How many times you want to repeat:'))
print(test_str * rep)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 17:45:31 2017
@author: jagan
"""
def normal_function(var1,var2):
print("var1:",var1)
print("var2:",var2)
# ** is used to pass keyworded, variable length argument dictionary to a function
def learn_kwarg_function(**kwargs):
print(kwargs) # It will create a dictionary; underoredred
def learn_kwarg_function_1(**kwargs):
for key,value in kwargs.items():
print("The value of ",key,"is ",value)
#normal_function('hello','python')
#learn_kwarg_function(kwarg_1="Tuna",kwarg_2="Talapia",kwarg_3="Salmon")
learn_kwarg_function_1(kwarg_1="Tuna",kwarg_2="Talapia",kwarg_3="Salmon") |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 17:37:43 2016
@author: jagan
"""
pi= 3.14
radius= int (input ("input radius:"))
print ("area=", pi*radius*radius) |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 11 18:25:36 2016
@author: jagan
"""
celsius= int(input ("celsius:"))
fahrenheit = (celsius * 1.8) + 32
print ("fahrenheit:",fahrenheit) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 9 16:08:40 2017
@author: jagan
"""
input_name = input("Enter a name:")
if (( input_name == "amey") or ( input_name == "jack")) :
print("welcome to python")
else:
print("i dont know you") |
#Learning class with fraction example
class fraction:
def __init__(self,num,deno):
self.num = num
self.deno = deno
print(self.num,"/", self.deno)
fra1 = fraction(1,4)
fra2 = fraction(1,2)
f1.__add__(f2)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 16 16:43:53 2017
@author: jagan
"""
list1= [1,2,3,4,5]
for item in list1:
if item == 4:
print("found the item") |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 16 17:19:04 2017
@author: jagan
"""
statement = 'y'
while (statement != 'n') :
statement = input("y or n:")
print(statement) |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 22:04:04 2017
@author: jagan
"""
#Function to calculate sum
def sum(num1,num2):
result = (num1 + num2)
return(result)
def diff(num1,num2):
result = (num1 - num2)
return(result)
def mul(num1,num2):
result = (num1 * num2)
return(result)
def div(num1,num2):
result = (num1 / num2)
return(result)
def main():
#input
num1=float(input("First Number:"))
num2=float(input("Second Number:"))
user_choice_operator = input("Please enter an operator:")
if (user_choice_operator == '+'):
result = sum(num1,num2)
elif (user_choice_operator == '-'):
result = diff(num1,num2)
elif (user_choice_operator == '*'):
result = mul(num1,num2)
elif (user_choice_operator == '/'):
result = div(num1,num2)
else:
result="Incorrect Choice"
#Calculation
print("Result;",result)
if __name__ == "__main__":
main() |
#python class
class Person:
#constructor/initiliazor
def __init__(self,name):
self.name = name
#method to return a string
def whoami(self):
return ("You are " + self.name)
p1 = Person('tom') # now we have created a new person object p1
print(p1.whoami())
print(p1.name)
p2 = Person('jerry') # now we have created a new person object p1
print(p2.whoami())
print(p2.name)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 16 16:18:46 2017
@author: jagan
"""
table = 99
for counter in range(1,6,1):
print(table , " X " , counter, " = ", table * counter) |
import turtle
def test_drive():
turtle.forward(100)
turtle.left(87)
turtle.setheading(127)
turtle.up()
turtle.goto(50,40)
turtle.down()
turtle.home()
turtle.circle(25)
def turtle_state():
v1=turtle.isdown()
v2=turtle.heading()
vx=turtle.xcor()
vy=turtle.ycor()
print("is the turtle down? ",v1)
print("current angle: ",v2)
print("xcor: ",vx,"ycor: ",vy)
def main():
turtle_state()
test_drive()
turtle_state()
input("press enter to continue...")
main() |
#Assining a new List slice
print('I want to change the coffee and apples and replace them with coke')
Cart[0:2]=['Coke'] #Can also be written Cart[:2]=Coke *Notice brackets
print(Cart)
#Pro Tip: if you want to delete every 2 entry del cart [::2]
#notice the double colon
#Deleting items from a list
del Cart[1]
print(Cart)
|
#Counting numbers from 0 to 9
print("Counting")
for i in range(10):
print(i, end="-")
|
import scikitlearn
#Commonly used packages by data scientists
#Pandas / Pd / Pd.XxXxxx (using the pandas package)
#Scikitlearn --> Machine learning
#numpy --> math manipulation
#Practice
#print the letters in the word red, randomly 10 times
import random
Word = input('Word is:')
for i in range(10):
position= random.randrange(-len(Word), len(Word))
print(Word[position])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 12:24:51 2018
@author: arvind
"""
import numpy as np
import pandas as pd
train_set = \
pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data', header = None)
test_set = \
pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test', skiprows = 1, header = None)
col_labels = ['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital_status', \
'occupation','relationship', 'race', 'sex', 'capital_gain', 'capital_loss', 'hours_per_week', \
'native_country', 'wage_class']
train_set.columns = col_labels
test_set.columns = col_labels
# Check about the data once
print(train_set.info())
print(test_set.info())
# Found that there are no missing values, however reading the dataset we can see
# there are many vales as " ?"
# need to handle these missing values
print('train_set shape before dropping the missing values : {}'.format(train_set.shape))
# Dropping all missing values
train_set = train_set.replace(' ?',np.nan).dropna()
print('train_set shape before dropping the missing values : {}'.format(train_set.shape))
print("------------------------------------------------------------")
# Same need to be done on test data as well
print('test_set shape before dropping the missing values : {}'.format(test_set.shape))
# Dropping all missing values
test_set = test_set.replace(' ?',np.nan).dropna()
print('test_set shape before dropping the missing values : {}'.format(test_set.shape))
print("------------------------------------------------------------")
# Can see that the 'wage_class' have different vales in train_test and test_set
print(train_set.wage_class.unique())
print(test_set.wage_class.unique())
# replacing all '<=50K.' ' >50K.' to ' <=50K' ' >50K'
test_set = test_set.replace({' <=50K.':' <=50K' , ' >50K.':' >50K'})
# Applying Label encoding and one hot encoding
from sklearn.preprocessing import LabelEncoder
lblenc = LabelEncoder()
#df.apply(LabelEncoder().fit_transform)
#train_set = lblenc(train_set.fit_tr)
train_set_lblenc = train_set.apply(lblenc.fit_transform)
# makeing X_train and y_train from training data set
y_train = train_set_lblenc.wage_class
X_train = train_set_lblenc.drop('wage_class',axis=1)
# Applying Label encoding on test set
test_set_lblenc = test_set.apply(lblenc.fit_transform)
# makeing X_train and y_test from training data set
y_test = test_set_lblenc.wage_class
X_test = test_set_lblenc.drop('wage_class',axis=1)
# fitting xgboost to the training data
from xgboost import XGBClassifier
xgc = XGBClassifier()
xgc.fit(X_train, y_train)
# Printing the accuracy score
print("The accuracy score calculated is {}".format(xgc.score(X_train, y_train)))
# predicting the test set results
y_pred = xgc.predict(X_test)
#make the confusion matricx
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test,y_pred)
#print(xgc.score(y_test,y_pred))
from sklearn.metrics import mean_absolute_error
print("Mean Absolute Error : " + str(mean_absolute_error(y_pred, y_test)))
|
"""
Manipulando Strings
*Strings indices
*Fatiamento de Strings[inicio:fim:passo]
*Funções built-in len,abs,type,print,etc...
Essas funções podem ser usadas diretamento em cada tipo.
Posso conferir tudo isso em:
https://docs.python.org/3/library/stdtypes.html
https://docs.python.org/3/library/functions.html
"""
#Cada caractere de uma string têm um índice
#positivos [012345678]
texto = "python_s2"
#negativos -[987654321]
print(texto[2])
url = "www.google.com.br/"
print(url[:-1])
nova_string = texto[7:] #Exemplos: texto[0:2] texto[-9:-3] texto[:-1] texto[:]
print(nova_string)
mais_string = texto[0::3] #Exemplos: texto[::]
print(mais_string)
print(len(texto)) |
"""
Operador ternário em python
"""
logged_user = False
msg = "Usuario logado." if logged_user else "Usuario precisa logar."
print(msg)
idade = input("Qual a sua idade? ")
if not idade.isnumeric():
print("Voce precisa digitar apenas numeros")
else:
idade = int(idade)
maior = (idade>=18)
msg = "Pode acessar" if maior else "Nao pode acessar"
print(msg)
|
"""
while em Python
Utilizado para realizar ações enquanto uma condição for verdadeira
Requisitos: Entender condições e operadores
"""
x = 0
while x < 10:
if x == 3: #Se eu quiser por exemplo tirar o 3 do meu loop
x = x+1
continue
print(x)
x = x+1
print("Acabou!")
x = 0
while x < 10:
if x == 3:
x = x+1
break #O comando break para o loop instantaneamente
print(x)
x = x+1
print("Acabou!")
|
def sortwithloops(L):
'''
Using bubble sort
'''
k = 0
L_len = len(L)
while (k <= L_len):
for i in range(L_len - k - 1):
if(L[i] >= L[i+1]):
temp = L[i]
L[i] = L[i+1]
L[i+1] = temp
k = k + 1
return(L)
def sortwithoutloops(L):
'''
Using list.sort() to sort the input list
'''
L.sort()
return(L)
def searchwithloops(L, x):
'''
Search a list's element using loop(s).
Searches first occurrance and returns True if the element is found.
'''
for i in range(len(L)):
if(L[i] == x):
return(True)
return(False)
def searchwithoutloops(L, x):
'''
searching a list with "in" operator
'''
return(x in L)
if __name__ == "__main__":
L = [5,3,6,3,13,5,6]
print sortwithloops(L) # [3, 3, 5, 5, 6, 6, 13]
print sortwithoutloops(L) # [3, 3, 5, 5, 6, 6, 13]
print searchwithloops(L, 5) #true
print searchwithloops(L, 11) #false
print searchwithoutloops(L, 5) #true
print searchwithoutloops(L, 11) #false
|
length=5
breadth=2
area=length*breadth
print 'Area is', area
print 'Perimeter is', 2*(length+breadth)
|
#!/usr/bin/env python3
ipchk = input("Apply an IP address: ") # this line now prompts the user for input
# a provided string will test true
if ipchk == "192.168.70.1":
print("Looks like the IP address of the Gateway was set: " + ipchk) # indented under if
elif ipchk: # if any data is provided, this will test true
print("Looks like the IP address was set: " + ipchk)
else: #if data is not provided.
print("You did not provide the input")
|
# Import packages
import numpy as np
# Defined functions
def LeisenReimerBinomial(OutputFlag, AmeEurFlag, CallPutFlag, S, X, T, r, c, v, n):
# This functions calculates the implied volatility of American and European options
# This code is based on "The complete guide to Option Pricing Formulas" by Espen Gaarder Haug (2007)
# Translated from a VBA code
# OutputFlag:
# "P" Returns the options price
# "d" Returns the options delta
# "a" Returns an array containing the option value, delta and gamma
# AmeEurFlag:
# "a" Returns the American option value
# "e" Returns the European option value
# CallPutFlag:
# "C" Returns the call value
# "P" Returns the put value
# S is the share price at time t
# X is the strike price
# T is the time to maturity in years (days/365)
# r is the risk-free interest rate
# c is the cost of carry rate
# v is the volatility
# n determines the stepsize
# Start of the code
# rounds n up tot the nearest odd integer (the function is displayed below the LeisenReimerBinomial function in line x)
n = round_up_to_odd(n)
# Creates a list with values from 0 up to n (which will be used to determine to exercise or not)
n_list = np.arange(0, (n + 1), 1)
# Checks if the input option is a put or a call, if not it returns an error
if CallPutFlag == 'C':
z = 1
elif CallPutFlag == 'P':
z = -1
else:
return 'Call or put not defined'
# d1 and d2 formulas of the Black-Scholes formula for European options
d1 = (np.log(S / X) + (c + v ** 2 / 2) * T) / (v * np.sqrt(T))
d2 = d1 - v * np.sqrt(T)
# The Preizer-Pratt inversion method 1
hd1 = 0.5 + np.sign(d1) * (0.25 - 0.25 * np.exp(-(d1 / (n + 1 / 3 + 0.1 / (n + 1))) ** 2 * (n + 1 / 6))) ** 0.5
# The Preizer-Prat inversion method 2
hd2 = 0.5 + np.sign(d2) * (0.25 - 0.25 * np.exp(-(d2 / (n + 1 / 3 + 0.1 / (n + 1))) ** 2 * (n + 1 / 6))) ** 0.5
# Calculates the stepsize in years
dt = T / n
# The probability of going up
p = hd2
# The up and down factors
u = np.exp(c * dt) * hd1 / hd2
d = (np.exp(c * dt) - p * u) / (1 - p)
df = np.exp(-r * dt)
# Creates the most right column of the tree
max_pay_off_list = []
for i in n_list:
i = i.astype('int')
max_pay_off = np.maximum(0, z * (S * u ** i * d ** (n - i) - X))
max_pay_off_list.append(max_pay_off)
# The binominal tree
for j in np.arange(n - 1, 0 - 1, -1):
for i in np.arange(0, j + 1, 1):
i = i.astype(int) # Need to be converted to a integer
if AmeEurFlag == 'e':
max_pay_off_list[i] = (p * max_pay_off_list[i + 1] + (1 - p) * max_pay_off_list[i]) * df
elif AmeEurFlag == 'a':
max_pay_off_list[i] = np.maximum((z * (S * u ** i * d ** (j - i) - X)),
(p * max_pay_off_list[i + 1] + (1 - p) * max_pay_off_list[i]) * df)
if j == 2:
gamma = ((max_pay_off_list[2] - max_pay_off_list[1]) / (S * u ** 2 - S * u * d) - (
max_pay_off_list[1] - max_pay_off_list[0]) / (S * u * d - S * d ** 2)) / (
0.5 * (S * u ** 2 - S * d ** 2))
if j == 1:
delta = ((max_pay_off_list[1] - max_pay_off_list[0])) / (S * u - S * d)
price = max_pay_off_list[0]
# Put all the variables in the list
variable_list = [delta, gamma, price]
# Return values
if OutputFlag == 'P':
return price
elif OutputFlag == 'd':
return delta
elif OutputFlag == 'g':
return gamma
elif OutputFlag == 'a':
return variable_list
else:
return 'Indicate if you want to return P, d, g or a'
def round_up_to_odd(n):
# This function returns a number rounded up to the nearest odd integer
# For example when n = 100, the function returns 101
return np.ceil(n) // 2 * 2 + 1
#Body of the script
Eur_call_result = LeisenReimerBinomial('P', 'e', 'C', 90, 100, 1, 0.01, 0.01, 0.2, 300)
American_call_result = LeisenReimerBinomial('P', 'a', 'C', 90, 100, 1, 0.01, 0.01, 0.2, 300)
Eur_put_result = LeisenReimerBinomial('P', 'e', 'P', 90, 100, 1, 0.01, 0.01, 0.2, 300)
American_put_result = LeisenReimerBinomial('P', 'a', 'P', 90, 100, 1, 0.01, 0.01, 0.2, 300)
#Print the output of the results
print('The price of the European call option is equal to ' +str(Eur_call_result))
print('The price of the American call option is equal to ' +str(American_call_result))
print('The price of the European put option is equal to ' +str(Eur_put_result))
print('The price of the American put option is equal to ' +str(American_put_result))
|
from time import sleep
from random import random, seed
class GameOfLife():
def __init__(self):
self.resize((0, 0))
def get_size(self):
h = len(self._board)
return h, 0 if h == 0 else len(self._board[0])
def _create_board(self, size):
return [[False] * size[1] for y in range(size[0])]
def resize(self, size):
self._board = self._create_board(size)
def get_board(self):
return self._board
def set_is_alive(self, x, y, is_alive):
self._board[x][y] = is_alive
def get_board_as_display_at(self, x, y):
if not self._board[x][y]:
return " "
else:
return "*"
def board_to_display_str(self):
display = ""
for number in range(self.get_size()[0]):
col = self._board[number]
display = display + "".join([self.get_board_as_display_at(number, y) for y in range(len(col))]) + "\n"
return display
def will_it_live(self, x, y):
counter = 0
# x_range = range(max(x - 1, 0), min(x + 1, len(self._board) - 1) + 1)
# y_range = range(max(y - 1, 0), min(y + 1, (self.get_size()[1] - 1) + 1))
# # y_range = range(y - 1, y + 2)
for i in range(x - 1, x + 2):
for k in range(y - 1, y + 2):
if i < 0 or i >= self.get_size()[0]:
continue
if k < 0 or k >= self.get_size()[0]:
continue
if i == x and k == y:
pass
elif self._board[i][k]:
counter = counter + 1
if counter < 2:
return False # the cell is dead
if counter > 3:
return False # the cell is dead
if counter == 3:
""" the cell is either alive, and stays like
that, or comes back to life """
return True
return self._board[x][y]
def iterate(self):
# TODO: add test
size = self.get_size()
new_board = self._create_board(size)
for x in range(0, size[0]):
for y in range(0, size[1]):
new_board[x][y] = self.will_it_live(x, y)
self._board = new_board
def anim_print(self, iterations):
for i in range(iterations):
print self.board_to_display_str()
self.iterate()
sleep(1)
def randomize_board(self):
size = self.get_size()
for i in range(size[0]):
for j in range(size[1]):
self.set_is_alive(i, j, random() > 0.5)
if __name__ == "__main__":
life = GameOfLife()
# print dir(life)
life.resize((40, 40))
life.randomize_board()
life.set_is_alive(3, 3, True)
life.set_is_alive(3, 2, True)
life.set_is_alive(3, 4, True)
# print life.board_to_display_str()
# life.iterate()
# print life.board_to_display_str()
# # print life.board_to_display_str()
life.anim_print(240)
|
import os
import csv
# path to collect data from and to folder
file_to_load=os.path.join("..","pybankchallengeveredakeshia", "budget_data.csv")
#variables
date = []
total_months = 0
current_net_total = 0
last_months_loss= 0
net_total_loss = 0
avg_change_net_total = []
greatest_increase_month = []
greatest_increase_net_total = 0
greatest_decrease_net_total = 0
greatest_decrease_month = []
#read csv
with open(file_to_load) as bud_data:
budget_reader = csv.reader(bud_data, delimiter=',')
header = next(budget_reader)
for row in budget_reader:
#Total_months
total_months = total_months + 1
#Net_Total
current_net_total += int(row[1])
#Difference between months
if (total_months == 1):
last_months_loss = current_net_total
else:
avg_change_net_total = current_net_total - last_months_loss
date.append(row[0])
#Average Change
avg_change_net_total.append(avg_change_net_total)
last_months_loss =current_net_total
avg_change_net_total = round(current_net_total / ((len(total_months)-1),2)
#greatest_increase_in_profits
greatest_increase_net_total = max(avg_change_net_total)
#greatest_decrease_in_profits
greatest_decrease_net_total = min(avg_change_net_total)
#date for greatest_increase month
greatest_increase_month_index = avg_change_net_total.index(greatest_increase_net_total)
greatest_increase_month = date[greatest_increase_month_index]
#date for greatest_decrease month
greatest_decrease_month_index = avg_change_net_total.index(greatest_decrease_net_total)
greatest_decrease_month = date[greatest_decrease_month_index]
#print
print("Financial Analysis")
print("-------------------")
print(f"Total Months: {total_months}")
print(f"Total: ${current_net_total}")
print(f"Average Change: ${avg_change_net_total}")
print(f"Greatest Increase in Profits: {greatest_increase_month} {greatest_increase_net_total}")
print(f"Greatest Decrease in Profits: {greatest_decrease_month} {greatest_decrease_net_total}")
#rewrite
file_to_output=os.path.join("pybankchallengeveredakeshia","budget_data_analysis.txt")
with open(file_to_output, "w") as outfile:
outfile.write("Financial Analysis\n")
outfile.write("-------------------\n")
outfile.write(f"Total Months: {total_months}\n")
outfile.write(f"Total: ${current_net_total}\n")
outfile.write(f"Average Change: ${avg_change_net_total}\n")
outfile.write(f"Greatest Increase in Profits: {greatest_increase_month} {greatest_increase_net_total}\n")
outfile.write(f"Greatest Decrease in Profits: {greatest_decrease_month} {greatest_decrease_net_total}\n") |
def repetitionSize(s):
prev = None
ret = 0
total = 0
for c in s:
if c == prev:
total += 1
else:
total = 1
ret = max(ret, total)
prev = c
return ret
s = input()
print(repetitionSize(s))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 00:06:47 2020
@author: Dr. Z
Creates a turtle that moves to the location of a mouse click
"""
#Modified from https://keepthinkup.wordpress.com/programming/python/python-turtle-handling-with-mouse-click/
import turtle
import tkinter
import random
w = 1080
h = 720
turtle.setup(w,h) # sets up screen size and turns on listener ***REQUIRED***
window = turtle.Screen() # create our Screen variable
window.clear()
window.title("Go Fish!")
window.bgcolor("lightblue")
window.setworldcoordinates(0, w, h, 0)
# Create our turle variable
button = turtle.Turtle(shape = "square")
size = 10
button.shapesize(size)
"""
Define a class that will create 'card' objects
each card should hold a unique identifier
each card should have a unique value
each card should have a unique position
-------------------------------------------------
When you generate a card object:
It shall be given a random color
and a definite position.
let position = [1,2,3]
0 <= value <= 2
Create 3 buttons with turtle:
A = cardOne
B = cardTwo
C = cardThree
now A - C shares all attributes of cardOne - cardThree
-------------------------------------------------
Now create a 2nd round of cards and append them to new list
can use same class myCard:
create different randomVal function for second set of cards
Create 3 more buttons with turtle:
D = cardFour
E = cardFive
F = cardSix
now D - F share attributes of cardFour - cardFive
-------------------------------------------------
:::::::::::::handling the match checking piece:::::::::::::
When user clicks a button -> store those attributes in new array
doesItMatch[0]
When user clicks 2nd button -> store those attributes in doesItMatch[1]
if doesItMatch.length = 2:
compareCards()
def compareCards():
if doesItMatch[0].val = doesItMatch[1].val
print("its a match")
score + 1
delete clicked cards
else
print("go fish")
if score == 2:
score + 1
print("Theres only one set left, you won")
exit()
"""
class myCard:
def __init__(self,val,xCor,yCor):
self.val = val
self.xCor = xCor
self.yCor = yCor
"""
::::::Create Cards::::::::::
"""
card = [] #top row of cards get appended here
matchCard = [] #bottom row of cards get appended here
doesItMatch = [] # use to compare two clicked cards
randomVal = random.sample(range(0,3), 3)# create 3 card objects, and give them random but not equal values
cardOne = myCard(randomVal[0],w/6,h/4)
card.append(cardOne)# append each object to the card array
cardTwo = myCard(randomVal[1],2*w/6,h/4)
card.append(cardTwo)
cardThree = myCard(randomVal[2],3*w/6,h/4)
card.append(cardThree)
A = cardOne
B = cardTwo
C = cardThree
matchVal = random.sample(range(0,3), 3)
cardFour = myCard(matchVal[0],w/6,3*h/4)
cardFive = myCard(matchVal[1],2*w/6,3*h/4)
cardSix = myCard(matchVal[2],3*w/6,3*h/4)
matchCard.append(cardFour)
matchCard.append(cardFive)
matchCard.append(cardSix)
D = cardFour
E = cardFive
F = cardSix
"""
::::::End Create Cards::::::::::
"""
"""
::::::Create Buttons::::::::::
"""
style = ('Courier', 30, 'italic')
button.hideturtle()
for i in range(3):
button.penup()
button.color('black')
button.goto((i+1)*w/6,h/4)
button.stamp()
button.goto((i+1)*w/6, 3*h/4)
button.stamp()
for i in range(3):
button.penup()
button.color('magenta')
button.goto((i+1)*w/6,h/4)
button.write('Click', font = style, align = 'center')
button.goto((i+1)*w/6, 3*h/4)
button.write('Click', font = style, align = 'center')
"""
onclick(logCardClick)
def logCardClick():
get x/y coordinate
if x cord & y cord = card[0].xCor & card[0].yCor:
doesItMatch.append(A)
match +=
if x cord & y cord = card[1].xCor & card[1].yCor:
doesItMatch.append(B)
match +=
if x cord & y cord = card[2].xCor & card[2].yCor:
doesItMatch.append(C)
match +=
if x cord & y cord = matchCard[0].xCor & matchCard[0].yCor:
doesItMatch.append(D)
match +=
if x cord & y cord = matchCard[1].xCor & matchCard[1].yCor:
doesItMatch.append(E)
match +=
if x cord & y cord = matchCard[2].xCor & matchCard[2].yCor:
doesItMatch.append(F)
match +=
if score == 2:
compareCards()
def compareCards():
if doesItMatch[0].val == doesItMatch[1].val:
score +=
if score == 2:
button.goto(w/2,h/2)
button.write("you win", font = style, align='center')
exit()
"""
|
# Python 查找列表中最大元素
list1 = [10, 20, 30]
list1.sort()
print(list1[-1])
print(max(list1))
|
def add(a, b):
if isinstance(a, str):
return a + '+' + b
return a + b
def test_one():
print("我是方法一")
x = "this"
assert "h" in x
def test_two():
print("我是方法二")
x = 5
assert x > 6
class TestClass:
def test_one(self):
x="this"
assert "h" in x
def test_two(self):
x="hello"
assert hasattr(x,"check")
def test_three(self):
a="hello"
b="hello world"
assert a in b
def hello():
print("hello world")
if __name__=="__main__":
hello()
test_one()
test_two()
|
# 第9章 类 138
# 9.1 创建和使用类 138
# 根据Dog 类创建的每个实例都将存储名字和年龄
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over!")
# __init__() 是一个特殊的方法,每当你根 据Dog 类创建新实例时,Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突。
# 根据类创建实例
# 调用Dog 类 中的方法__init__() 。方法__init__() 创建一个表示特定小狗的示例,并使用我们提供的值来设置属性name 和age 。方法__init__() 并未显式地包含return 语句, 但Python自动返回一个表示这条小狗的实例。
my_dog = Dog('willie', 6)
# 访问属性
print(my_dog.name)
# 调用方法
my_dog.sit()
my_dog.roll_over()
# 创建多个实例
your_dog = Dog('lucy', 3)
# 9.2 使用类和实例 142
# 下面来编写一个表示汽车的类,它存储了有关汽车的信息
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# 给属性指定默认值
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
self.odometer_reading = mileage
def increment_odometer(self, miles):
self.odometer_reading += miles
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
# 直接修改属性的值
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# 通过方法修改属性的值
my_new_car.update_odometer(23)
my_new_car.read_odometer()
# 通过方法对属性的值进行递增
my_new_car.increment_odometer(100)
my_new_car.read_odometer()
# 9.3 继承 147
# 一个类继承 另一个类时,它将自动获得另一个类的所有属性和方法;原有的 类称为父类 ,而新类称为子类 。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
class ElectricCar(Car):
def __init__(self, make, model, year):
# super() 是一个特殊函数,帮助Python将父类和子类关联起来。
# 父类也称为超类 (superclass),名称super因此而得名
# 父类的方法__init__() ,让ElectricCar 实例包含父类的所 有属性
super().__init__(make, model, year)
self.battery_size = 70
self.battery = Battery()
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
# 让一个类继承另一个类后,可添加区分子类和父类所需的新属性和方法。
# 重写父类的方法
# 对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写
# 可以将大型类拆分成多个协同工作的小类
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
# 9.4 导入类
# 导入模块中的所有类
# from module_name import *
# 9.5 Python标准库
# Python标准库 是一组模块,安装的Python都包含它。
# 9.6 类编码风格
# 类名应采用驼峰命名法 ,即将类名中的每个单词的首字母都大写
# 实例名和模块名都采用小写格式,并在单词之间加上下划线。
|
# Python 计算元素在列表中出现的次数
def countX(list, x):
count = 0
for ele in list:
if (ele == x):
count = count + 1
return count
list = [1, 2, 3, 4]
x = 2
print(countX(list, x))
|
# Python 判断奇数偶数
num = float(input("num"))
if (num % 2) == 0:
print("偶数")
else:
print("奇数")
|
# 第6章 字典 81
# 6.1 一个简单的字典 81
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# 每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典
# 键—值 对是两个相关联的值。
alien_0 = {'color': 'green'}
print(alien_0['color'])
# 6.2 使用字典 82
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
alien_0['color'] = 'yellow'
del alien_0['points']
print(alien_0)
favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
# 6.3 遍历字典 87
user_0 = {'username': 'efermi', 'first': 'enrico', 'last': 'fermi'}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
# 遍历字典中的所有键
for name in favorite_languages.keys():
print(name.title())
# 可使用函数sorted() 来获得按特定顺序排列的键列表的副本
for name in sorted(favorite_languages.keys()):
print(name.title())
# 遍历字典中的所有值
for language in favorite_languages.values():
print(language.title())
# 6.4 嵌套 93
# 将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
# 在字典中存储列表
pizza = {'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese']}
for topping in pizza['toppings']:
print("\t" + topping)
# 在字典中存储字典
users = {'aeinstein': {'first': 'albert', 'last': 'einstein', 'location': 'princeton', },
'mcurie': {'first': 'marie', 'last': 'curie', 'location': 'paris', }}
for username, user_info in users.items():
print("\nUsername: " + username)
|
# NumPy Ndarray 对象
# NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
#
# ndarray 对象是用于存放同类型元素的多维数组。
#
# ndarray 中的每个元素在内存中都有相同存储大小的区域。
#
# ndarray 内部由以下内容组成:
import numpy as np
a=np.array([1,2,3])
print(a)
a=np.array([[1,2],[3,4]])
print(a)
a=np.array([2,3,4,4,5],ndmin=2)
print(a)
a=np.array([1,2,3],dtype=complex)
print(a)
# ndarray 对象由计算机内存的连续一维部分组成,并结合索引模式,将每个元素映射到内存块中的一个位置。
# 内存块以行顺序(C样式)或列顺序(FORTRAN或MatLab风格,即前述的F样式)来保存元素。
|
# Python 日期和时间
# Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
# Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。
import time
# 获取当前的时间戳
ticks = time.time()
print(ticks)
# 什么是时间元组?
# 很多Python函数用一个元组装起来的9组数字处理时间:
# 上述也就是struct_time元组。这种结构具有如下属性:struct_time 具体的解释如下
localtime = time.localtime(ticks)
print(localtime)
# time.struct_time(tm_year=2020, tm_mon=2, tm_mday=12, tm_hour=11, tm_min=59, tm_sec=13, tm_wday=2, tm_yday=43, tm_isdst=0)
# 获取格式化的时间
# 最简单的获取可读的时间模式的函数是asctime():
localtime=time.asctime(time.localtime(ticks))
print(localtime)#Wed Feb 12 12:04:06 2020
# 格式化日期
# 我们可以使用 time 模块的 strftime 方法来格式化日期,:
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
a = "Sat Mar 28 22:24:24 2016"
print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
# 获取某月日历
# Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:
import calendar
cal = calendar.month(2020,1)
# 打印出一月份的日历
print(cal)
# Time 模块
# Time 模块包含了以下内置函数,既有时间处理的,也有转换时间格式的
# 日历(Calendar)模块
# 此模块的函数都是日历相关的,例如打印某月的字符月历。
# 返回格林威治西部的夏令时地区的偏移秒数
print(time.altzone)
# 接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"
print(time.asctime())
# 用以浮点数计算的秒数返回当前的CPU时间//
# print(time.clock())
# 作用相当于asctime(localtime(secs)),未给参数相当于asctime()
print(time.ctime())
# 返回格林威治天文时间下的时间元组t
print(time.gmtime())
# 接收时间戳
print(time.localtime())
# 接受时间元组并返回时间戳
t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
print(time.mktime(t))
# 推迟调用线程的运行
# time.sleep(1000)
# 接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。
print("----")
# print(time.strftime("%b %d %Y %H:%M:%S", time.gmtime(time.mktime(2009, 2, 17, 17, 3, 38, 1, 48, 0))))
#根据fmt的格式把一个时间字符串解析为时间元组。
print(time.strptime("30 Nov 00", "%d %b %y"))
# 返回当前时间的时间戳
print(time.time())
# 根据环境变量TZ重新初始化时间相关设置。 无返回值
# time.tzset()
# Time模块包含了以下2个非常重要的属性:
print(time.timezone)#当地时区 偏移量
print(time.tzname)#('中国标准时间', '中国夏令时')
# 日历(Calendar)模块
# 获取给定年份 月份 日的日历信息
print(calendar.calendar(2006))
# 返回当前每周起始日期的设置
print("*****")
print(calendar.firstweekday)
# 是否为闰年
print(calendar.isleap(2000))
# 返回在Y1,Y2两年之间的闰年总数。
print(calendar.leapdays(2000,2016))
# 返回一个多行字符串格式的year年month月日历
print(calendar.month(2000,1))
# 返回一个整数的单层嵌套列表
print(calendar.monthcalendar(2000,1))
# 返回两个整数
print(calendar.monthrange(2000,1))
# calendar.prcal() 相当于 print calendar.calendar()。
print(calendar.prcal(2000))
# calendar.prmonth()相当于 print calendar.month() 。
print("=======")
print(calendar.prmonth(2000,1))
# calendar.setfirstweekday(weekday)
# 设置每周的起始日期码。0(星期一)到6(星期日)。
print("*****")
print(calendar.setfirstweekday(0))
# calendar.timegm(tupletime)
# 和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间戳
import datetime
d = datetime.datetime(2010, 10, 10)
print(calendar.timegm(d.timetuple()))
# 返回给定日期的日期码 calendar.weekday(year,month,day)
print(calendar.weekday(2000,1,1))
# 其他相关模块和函数
# 在Python中,其他处理日期和时间的模块还有:
#
# datetime模块
# pytz模块
# dateutil模块
|
# Python GUI编程(Tkinter)
# Python 提供了多个图形开发界面的库,几个常用 Python GUI 库如下:
#
# Tkinter: Tkinter 模块(Tk 接口)是 Python 的标准 Tk GUI 工具包的接口 .
#
# wxPython:wxPython 是一款开源软件,是 Python 语言的一套优秀的 GUI 图形库,
#
# Jython:Jython 程序可以和 Java 无缝集成。除了一些标准模块,Jython 使用 Java 的模块。
# Python3.x 版本使用的库名为 tkinter,即首写字母 T 为小写。
import tkinter
top = tkinter.Tk()
top.mainloop()
from tkinter import *
root = Tk()
li = ["java", "python"]
movie = ["hadoop", "storm"]
listb = Listbox(root)
listb2 = Listbox(root)
for item in li:
listb.insert(0, item)
for item in li:
listb2.insert(0, item)
listb.pack()
listb2.pack()
root.mainloop()
# Tkinter 组件
# Tkinter的提供各种控件,如按钮,标签和文本框,一个GUI应用程序中使用。这些控件通常被称为控件或者部件。
#
# 目前有15种Tkinter的部件。我们提出这些部件以及一个简短的介绍,在下面的表:
#
# 控件 描述
# Button 按钮控件;在程序中显示按钮。
# Canvas 画布控件;显示图形元素如线条或文本
# Checkbutton 多选框控件;用于在程序中提供多项选择框
# Entry 输入控件;用于显示简单的文本内容
# Frame 框架控件;在屏幕上显示一个矩形区域,多用来作为容器
# Label 标签控件;可以显示文本和位图
# Listbox 列表框控件;在Listbox窗口小部件是用来显示一个字符串列表给用户
# Menubutton 菜单按钮控件,用于显示菜单项。
# Menu 菜单控件;显示菜单栏,下拉菜单和弹出菜单
# Message 消息控件;用来显示多行文本,与label比较类似
# Radiobutton 单选按钮控件;显示一个单选的按钮状态
# Scale 范围控件;显示一个数值刻度,为输出限定范围的数字区间
# Scrollbar 滚动条控件,当内容超过可视化区域时使用,如列表框。.
# Text 文本控件;用于显示多行文本
# Toplevel 容器控件;用来提供一个单独的对话框,和Frame比较类似
# Spinbox 输入控件;与Entry类似,但是可以指定输入范围值
# PanedWindow PanedWindow是一个窗口布局管理的插件,可以包含一个或者多个子控件。
# LabelFrame labelframe 是一个简单的容器控件。常用与复杂的窗口布局。
# tkMessageBox 用于显示你应用程序的消息框。
# 标准属性
# 标准属性也就是所有控件的共同属性,如大小,字体和颜色等等。
#
# 属性 描述
# Dimension 控件大小;
# Color 控件颜色;
# Font 控件字体;
# Anchor 锚点;
# Relief 控件样式;
# Bitmap 位图;
# Cursor 光标;
# 几何管理
# Tkinter控件有特定的几何状态管理方法,管理整个控件区域组织,一下是Tkinter公开的几何管理类:包、网格、位置
#
# 几何方法 描述
# pack() 包装;
# grid() 网格;
# place() 位置;
|
# Python list 常用操作
# list定义
li = ["java", "python", "scala", "php", "swift"]
print(li[0])
# list负数索引
print(li[-1])
print(li[-3])
print(li)
print(li[1:3])
print(li[1:-1])
print(li[0:3])
# 增加元素
li.append("cpp")
li.insert(2, "csharp")
li.extend(["c", "javascript"])
print(li)
# list搜索
print(li.index("python"))
print(li.index("c"))
print()
# list删除
li.remove("csharp")
li.pop()
# list运算符
li2 = ["a", "b"]
li = li + li2
print(li)
li += li
print(li)
li = [1, 2] * 3
print(li)
# 7.使用join链接list成为字符串
# 8.list 分割字符串
li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
s.split(";")
s.split(";", 1)
# split 与 join 正好相反, 它将一个字符串分割成多元素 list。
# 9.list 的映射解析
li = [1, 9, 8, 4]
li = [elem * 2 for elem in li]
# 10.dictionary 中的解析
params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}
params.keys()
params.values()
params.items()
# 11.list 过滤
li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
|
# Python 判断字符串长度
print(len("hello python"))
def findLen(str):
counter = 0
while str[counter:]:
counter += 1
return counter
print(findLen("hello python"))
def length(src):
count = 0
all_str = src[count:]
for x in all_str:
count += 1
print(count)
length("hello python")
|
# 题目:两个变量值互换。
def exchange(a,b):
a,b=b,a
return (a,b)
if __name__=="__main__":
x=10
y=20
print(x,y)
x,y=exchange(x,y)
print(x,y) |
# NumPy 创建数组
# ndarray 数组除了可以使用底层 ndarray 构造器来创建外,也可以通过以下几种方式来创建。
#
# numpy.empty
# numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组:
import numpy as np
x=np.empty([3,2],dtype=np.int)
print(x)
# numpy.zeros
# 创建指定大小的数组,数组元素以 0 来填充:
x=np.zeros(5)
print(x)
y=np.zeros((5,),dtype=np.int)
print(y)
z=np.zeros((2,2),dtype=np.int)
print(z)
# numpy.ones
# 创建指定形状的数组,数组元素以 1 来填充
x=np.ones([2,2],dtype=np.int)
print(x) |
# Python 翻转列表
def Reverse1(list):
return [ele for ele in reversed(list)]
def Reverse2(list):
list.reverse()
return list
def Reverse3(list):
new_list = list[::-1]
return new_list
list = [10, 11, 12, 13, 14, 15]
print(Reverse1(list))
print(Reverse2(list))
print(Reverse3(list))
|
# 时间函数举例4,一个猜数游戏,判断一个人反应快慢。
if __name__ == "__main__":
import time
import random
play_it = input("play")
while play_it != "y":
c = input("\n")
i = random.randint(0, 2 ** 32) % 100
start = time.clock()
a = time.time()
guess = int(input("\n"))
while guess != i:
if guess > i:
print("aaa")
guess = int(input("\n"))
else:
print("input\n")
guess = int(input())
end = time.time()
b = time.time()
var = (end - start) / 18.2
print(var)
if var < 15:
print("xxx")
elif var < 25:
print("xxx")
else:
print("")
print("")
print("")
play_it = input("")
|
# Python 字典(Dictionary)
# 字典是另一种可变容器模型,且可存储任意类型对象。
dict1 = {"a": 1, "b": 2, "c": 3}
print(dict1)
# 访问字典里的值
print(dict1["a"])
# 修改字典
dict1["a"] = 100
print(dict1)
# 删除字典元素
# 字典键的特性
# 1)不允许同一个键出现两次
# 2)键必须不可变,所以可以用数字,字符串或元组充当
# 字典内置函数&方法
# cmp python3移除
print(len(dict1))
print(str(dict1))
print(type(dict1))
dict2 = {"a": 100}
# clear
dict2.clear()
# 字典的浅复制
print(dict1.copy())
# 创建一个新字典
dict2 = dict.fromkeys((1, 2, 3), 10)
print(dict2)
# get
print(dict1.get("a", "123"))
# has_key== __contains__
print(dict1.__contains__("a"))
# items
# 遍历字典列表
for key, values in dict1.items():
print(key, values)
# keys
for key in dict1.keys():
print(key)
# values
for value in dict1.values():
print(value)
# update 追加一个字典进来
dict1.update({"d": 4})
print(dict1)
# pop 删除给定的key 返回value 无则返回默认值
print(dict1.pop("a", "123"))
# setdefault 设置默认的
dict1.setdefault("e", "123")
print(dict1)
# popitem 返回字典中最后一对key和value 并删除它
print(dict1.popitem())
print(dict1)
|
# (十一)多表单切换
# 遇到frame/iframe表单嵌套页面的应用,WebDriver只能在一个页面上对元素识别与定位,对于frame/iframe表单内嵌页面上的元素无法直接定位。
# 这时就需要通过switch_to.frame()方法将当前定位的主体切换为frame/iframe表单的内嵌页面中。
from selenium import webdriver
driver = webdriver.Chrome(executable_path='C:\driver\chromedriver.exe')
driver.get("http://www.126.com")
# switch_to.frame() 默认可以直接取表单的id 或name属性
driver.switch_to.frame('x-URS-iframe')
driver.find_element_by_name("email").clear()
driver.find_element_by_name("email").send_keys("username")
driver.find_element_by_name("password").clear()
driver.find_element_by_name("password").send_keys("password")
driver.find_element_by_id("dologin").click()
# 通过switch_to.default_content()跳回最外层的页面
driver.switch_to.default_content()
driver.quit()
|
# Python 字符串
# 字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。
# Python 访问字符串中的值
var1 = "hello world"
var2 = "hello python"
print(var1[0])
print(var2[2:5])
# Python 字符串连接
print("输出:", var2[0] + " python")
# Python 转义字符
# \t \n \\
# Python字符串运算符
a = "hello"
b = "python"
print(a + b)
print(a * 2)
print(a[1])
print(a[1:4])
if ("H" not in a):
print("not in", a)
else:
print("False")
if ("M" not in a):
print("M not in", a)
else:
print("M not in a")
# 移除转义 直接输出
print(r'\n')
print(R'\n')
# Python 字符串格式化
# %s 格式化字符串 %d 格式化整数 %f格式化浮点数
print("my name is %s and weight is %d kg,i have %f dollar" % ("zebra", 20, 1.5))
# Python 三引号
# 可以跨多行注释
# Unicode 字符串
print(u'Hello world')
# python的字符串内建函数
# 字符串的常用方法
# 首字母大写
print("str".capitalize())
# 以a为中心执行填充
print("a".center(9, "*")) # ****a****
# 统计单词的出现次数
print("hello".count("l"))
varStr = "中国"
print(varStr.encode("UTF-8", 'errorInfo'))
# 暂时没有发现decode方法
# print(varStr.de)
print("Hello".endswith("o"))
# 把\t转换为空格输出
print("this is\tstring example".expandtabs())
# find 查找
print("this".find("s"))
# 格式化字符串 可以指定位置 可以不指定
print("{} {}".format("hello", "world"))
print("{0} {1}".format("hello", "world"))
# 查找字符 不存在报错
print("str".index("s"))
# 都是数字或者都是字母 返回TRUE
print("str".isalnum())
print("%str".isalnum())
# 都是字母
print("str".isalpha())
# 都是数字
print("123".isdigit())
# 都是小写
print("Str".islower())
# 都是数字
print("12.01".isnumeric())
# 都是包含空格
print("123 123".isspace())
# 都是大写
print("Str".isupper())
# 把指定字符串加入到指定的序列当中
print("-".join(("a", "b", "c")))
# 左对齐 指定字符串长度 不够则填充
print("hello".ljust(20, "*"))
# 全部小写
print("HelloPython".lower())
# 截掉左边的空格
print(" str".lstrip())
# maketrans() 方法用于创建字符映射的转换表
# print("123".maketrans("abc"))
# python3 没有该方法
print(max("str"))
print(min("str"))
# 类似于split
print("123.123".partition("."))
# replace
print("123".replace("1", "8"))
# rfind 类似于find函数
print("str".rfind("s"))
# rindex 类似于index函数
print("str".rindex("s"))
# rpartition
print("str".rpartition("s"))
# rstrip
print("str123 ".rstrip())
# split
print("123@123".split("@"))
# splitlines 按照\n\r\t执行分割
print("ab c\n\nde fg\rkl\r\n".splitlines())
# startwith
print("123".startswith("1"))
# strip 执行左右的strip
print(" 123 ".strip())
# swapcase 翻转大小写
print("Hello".swapcase())
# 标题化
print("hello python, hello world".title())
# translate 按照指定table来执行翻译
# print("11111".translate("abc".maketrans("123")))
# upper 转为大写形式
print("str".upper())
# zfill 给定长度 然后填充0
print("hello".zfill(10)) # 00000hello
|
# Python 合并字典
# 实例 1 : 使用 update() 方法,第二个参数合并第一个参数
def Merge(dict1, dict2):
return dict2.update(dict1)
def Merge2(dict1, dict2):
result = {**dict1, **dict2}
return result
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
print(Merge(dict1, dict2))
print(Merge2(dict1, dict2))
# 实例 2 : 使用 **,函数将参数以字典的形式导入
|
# NumPy 切片和索引
# ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操作一样。
import numpy as np
a = np.arange(10)
s = slice(2, 7, 2)
print(a[s])
# 我们也可以通过冒号分隔切片参数 start:stop:step 来进行切片操作:
a = np.arange(10)
b = a[2:7:2]
print(b)
a = np.arange(10)
b = a[5]
print(b)
print(a[2:])
print(a[2:5])
# 多维数组同样适用上述索引提取方法:
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a)
print(a[1:])
# 切片还可以包括省略号 …,来使选择元组的长度与数组的维度相同。
# 如果在行位置使用省略号,它将返回包含行中元素的 ndarray。
print("numpy009")
print(a[..., 1]) # 第2列元素
print(a[1, ...]) # 第2行元素
print(a[..., 1:]) # 第2列及剩下的所有元素
|
# Python 将列表中的指定位置的两个元素对调
def swapPositions1(list,pos1,pos2):
list[pos1],list[pos2]=list[pos1],list[pos2]
return list
def swapPositions2(list,pos1,pos2):
first_ele=list.pop(pos1)
second_ele=list.pop(pos2)
list.insert(pos1,second_ele)
list.insert(pos2,first_ele)
return list
def swapPositions3(list,pos1,pos2):
get=list[pos1],list[pos2]
list[pos2],list[pos1]=get
return list
def reversal(list,n1,n2):
temp=list[n1]
list[n1]=list[n2]
list[n2]=temp
print(list)
List=[1,2,3,4]
pos1=1
pos2=3
print(swapPositions1(List,pos1-1,pos2-2))
print(swapPositions2(List,pos1-1,pos2-2))
print(swapPositions3(List,pos1-1,pos2-2))
print(reversal(List,pos1-1,pos2-2))
|
#Noa P Prada Schnor, 2018-02-19, modified 2018-03-03
#Project Euler Problem 5 (https://projecteuler.net/problem=5)
i = 2 #number starts from 2
f = 2 #number that I need to find out
while i < 21: #while the number is 20
if f % i == 0: #f must be an even number
i = i + 1 #add 1 to the number
else: #otherwise
f=f+1 #add a number to the number I need to find out
i=2
print('The smallest positive number that is evenly divisible by all of the numbers from 1 to 20 is:',f)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.