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 i... |
# -*- 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... |
##################################################################
# 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 an... |
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 ValueErr... |
# 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_s... |
#!/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. ... |
#!/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(), t... |
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... |
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'},
{'br... |
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:... |
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 us... |
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 ... |
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 ... |
#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 ... |
# 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 fracti... |
"""
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 se... |
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:'))
... |
# 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 ... |
#####################
#
# 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.
#
# Usag... |
# 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,"f... |
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 i... |
'''
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 la... |
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")
... |
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('... |
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ív... |
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:
... |
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: C... |
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 ... |
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, studen... |
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])
... |
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_... |
## 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
co... |
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:
... |
# ----------------------------------------------------------------------
# Title : Class Example
# Author : Jagannath Banerjee
# Date : 12/15/2017
# ----------------------------------------------------------------------
#Import Library Block
import os
#class definition
cl... |
# -*- 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 ... |
# -*- 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... |
#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(p... |
# -*- 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... |
#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]
... |
#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):
... |
#!/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/... |
"""
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
... |
"""
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)
... |
"""
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
... |
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 sor... |
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 t... |
# 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 Esp... |
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 ran... |
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_ne... |
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
imp... |
# 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" ... |
# 第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__() 是... |
# 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)
... |
# 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... |
# Python 日期和时间
# Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
# Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。
import time
# 获取当前的时间戳
ticks = time.time()
print(ticks)
# 什么是时间元组?
# 很多Python函数用一个元组装起来的9组数字处理时间:
# 上述也就是struct_time元组。这种结构具有如下属性:struct_time 具体的解释如下
localtime = time.localtime(ticks)
print(localtime)... |
# 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
... |
# 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("p... |
# 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)
l... |
# 题目:两个变量值互换。
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... |
# 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"))
w... |
# 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))
p... |
# (十一)多表单切换
# 遇到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.fra... |
# 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)
p... |
# 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])
# 多维数组同样适用上述索引... |
# 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 ... |
#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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.