text stringlengths 37 1.41M |
|---|
import init
def afisare(): # this function displays the participants and their grades
n=len(init.students)
for i in range(0,n):
print("Participant "+ str(i) + ": " + str(init.students[i][0]) + " , " + str(init.students[i][1]) + " , " + str(init.students[i][2]))
return |
from init import students
from init import histudents
import init
def add():#this function adds a new participant to the list
print("Type in the scores of the new participant: ")
while(True):
try:
ele=[int(input()),int(input()),int(input())]
assert 0<=ele[0]... |
#this module exists so that the list can be globally used
from Classes import Expense
import copy
global expenses
E1=Expense(1,10,"ham")
E2=Expense(2,20,"cigars")
E3=Expense(3,30,"Pepsi Twist")
E4=Expense(4,40,"toothpaste")
E5=Expense(5,50,"chocolate")
E6=Expense(6,60,"dentist")
E7=Expense(7,7... |
import random
from time import sleep, time
from typing import Callable, Dict, List
THROTTLE_QUEUE: Dict[Callable[[], None], List[float]] = {}
def throttle(*, period: int, call_per_period: int):
"""
Wrapper to throttle the number of time a function can be called
:param period: time in seconds
:param ... |
class TokenType():
ID=3
INT=2
TOKENTYPE_NAMES={ 2:"INT", 3:"ID"}
class Token():
def __init__(self, type, lexeme):
self.type=type
self.lexeme=lexeme
def __str__(self):
#return self.lexeme
return "[" + TOKENTYPE_NAMES[self.type] + ": " + self.lexeme + ... |
# Importing tkinter module
from tkinter import *
from exampleLib import *
#A simple function to draw circles in a canvas
def _create_circle(self, x, y, r, **kwargs):
return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
Canvas.create_circle = _create_circle
#initializes the main menu. you have to pass the mai... |
#Basics
#Assignacio
variable = 0;
variable = "zero";
variable = False;
variable = '0';
variable = 0.0;
variable = bytes;
#Operacions:
#Enters i Decimals (int / float o double) :
a = 5;
b = 10;
c = a*b; print (">>>" , c);
c = a + b; print(">>>" , c);
a+= b; print(">>>",a);
b*=a; print(">>>",b);
#OJO D... |
from youtube_search import YoutubeSearch
import json
import requests
import sys
def urlFromQuery(query):
try:
results = YoutubeSearch(query, max_results=4).to_json()
except requests.exceptions.ConnectionError:
print("There was an error connecting to YouTube. Check Proxy/Internet settings.")
... |
n0 ,n1 = 0 ,1
n=int(input("enter the number of terms "))
if n == 0:
print("enter the valid terms")
else:
print("fibonacci series is")
print(n0)
print(n1)
for i in range(n):
n2=n0+n1
print(n2)
n0=n1
n1=n2
|
lst=[
[10,20,30],
[10,20,30],
[50,60,70]
]
lst2=[]
for num in lst:
print(num)
for val in num:
lst2.append(val)
print(lst2)
|
num1=int(input("enter number 1"))
num2=int(input("enter number 2"))
if (num1+num2==100)|(num1==100)|(num2==100):
print("true")
else:
print("false") |
def add(num1,num2):
res=num1+num2
print(res)
add(100,200)
def multi(num3,num4):
res=num3+num4
print(res)
multi(2,2)
def sub(num1,num2):
res=num1-num2
print(res)
sub(300,200)
def division(num1,num2):
res=num1/num2
print(res)
division(2000,200)
def modular(num1,num2):
res=num1%num2
... |
# num1=int(input())
# num2=int(input())
# num3=int(input())
# if(num1>num2) & (num1>num3):
# print("num1 is larger")
# elif(num2>num1) & (num2>num3):
# print("num2 is largest")
# else:
# print("num3 is largest")
#
num1=int(input())
num2=int(input())
num3=int(input())
if(num1>num2)&(num1>num3):
print("... |
num1=int(input("enter num1"))
num2=int(input("enter num2"))
if(num1>num2):
print("num1 is larger",num1)
else:
print("nun2 is larger",num2) |
limit=int(input("enter the number"))
for i in range (1,(limit+1)):
print(i**2)
|
from os import system
system("cls")
numero = int (input ("Dame un número y te diré todos sus divisores : "))
for i in range (numero + 1):
if ((i!=0) and (numero % i==0)):
print(i , end = " ") |
#数据参数化,一个函数代替多个函数
import unittest
from parameterized import parameterized
def mul(x,y): #定义乘法
z = x*y
return z
class TestAddDemo(unittest.TestCase):
# @classmethod
# def setUpClass(cls) -> None:
# print("=====执行setUpClass方法=====")
# @classmethod
# def tearDownClass(cls) -> None:
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 10:44:01 2021
@author: abilash
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 08:28:28 2021
@author: abilash
"""
'''
from IPython import get_ipython
get_ipython().magic('reset -sf')
get_ipython().magic('clear')
'''
class semester:
def assign_s... |
import csv, sys, string, math
path = None
slashes = None
# usage: python generate_ddl.py csv_file_to_be_converted
if len(sys.argv) != 2:
print('Invalid number of parameters')
print('Usage: python generate_ddl.py <path_to_csv_file>')
print('Example: python generate_ddl.py discog_subset/releases.csv')
sys.exit()
... |
from typing import List
def shuffle(nums: List[int], n: int) -> List[int]:
list = []
for i in range(n):
list.append(nums[i])
list.append(nums[i + n])
return list
if __name__ == '__main__':
# nums = [2, 5, 1, 3, 4, 7]
# n = 3
# nums = [1,2,3,4,4,3,2,1]
# n = 4
nums =... |
a= [2,4,10,16]
def multiply(arr, x):
for i in range(0, len(a)):
arr[i]= arr[i]*x
return arr
b = multiply(a,5)
print b |
def grade(x,y):
x=input("What is the score: ")
if x>=60 and x<70:
y="D"
elif x>=70 and x<80:
y="C"
elif x>=60 and x<90:
y="B"
elif x>=90 and x<=100:
y="A"
else:
y="not a valid grade entry"
print "Score "+str(x)+"; Your grade is "+y
for count in range(0,10):
score=0
output=""
grade(score,output)
pri... |
def first_function(name):
print name
print 'outside of function'
first_function('cody')
arr = [1,2,3]
def first_function(arr):
for i in range(0, len (arr)):
print arr[i]
#for (var i =0, i < arr.length; i++):
arr = [1,2,3,4,5,6,7,8,9,10]
def first_function(arr):
for i in range(0, len (arr)):
if arr[i]%2 ==... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 22 22:57:45 2019
@author: David G
"""
import random
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Defining a class which will create our linked list and also defining other utility methods
class LinkedList:... |
# -*- coding: utf-8 -*-
def max_sum(nums):
if not nums:
return 0
elif len(nums) <= 2:
return sum(nums)
return max(max_sum_helper(nums[0],nums[2:]), max_sum_helper(nums[1], nums[3:]), max_sum_helper(nums[0], nums[3:]))
def max_sum_helper(curr, nums):
if not nums:
... |
#fizzbuzz
#if number divisible by 3 print fizz
#if number divisible by 5 print buzz
#if both print both
#Madison Chen and Narsima Donuk
def fizzbuzz(max_value):
count=0
while count <= max_value:
if count % 15 == 0 :
print ("FizzBuzz")
elif count % 3 == 0:
print ("Fizz")
... |
def calcPercentage(obMarks,mxMarks):
'''
objective : To calculate the percentage from the marks entered.
input parameters :
obmarks : Marks obtained.
mxmarks : Maximum Marks.
appraoch : Divide the marks obtained by the maximum marks and then
multiply by 100. The result is the perce... |
#coloca os numeros em ordem decrescente
# numeros_sorteados.sort(reverse = True)
#Adicionar numero no final da fila
#numeros_sorteados.append()
#Pacote para numeros aleatorios
import random
def gerarNumeros(quant_numeros, minimo, maximo):
numeros_sorteados = []
while len(numeros_sorteados) < quant_n... |
import math
def isPrime(n):
if(n<0):
return False
for i in range(3, math.ceil(math.sqrt(n)), 2):
if n%i == 0:
return False
return True
def primeCycle(f):
count = 0
while isPrime(f(count)):
count+=1
return (count-2)
maximum = 0
mprod = 0
for i in range(-1000... |
def countSundays(days, year):
first = []
Sundays = 0
if year%4 != 0 or year%400 == 0:
first = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
elif year%4 == 0:
first = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]
for i in first:
if days[i] == 0:
... |
# -*- coding:utf-8 -*-
# User: liaochenchen
# Date: 2020/3/16
# Python2
from tkinter import *
import tkinter.messagebox as messagebox
class A:
"""
使用StringVar() 和 textvariable
对Button进行绑定
实现Button对数据进行操作
解决Button传参问题
StringVar()的数需要使用.get()获取值
"""
def __init__(self, master):
self.root = Frame(master)
s... |
# -*- coding:utf-8 -*-
# User: liaochenchen
# Date: 2019/12/16
import Tkinter as tk # py2
# import tkinter as tk # py379
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
f1 = GradientFrame(self, borderwidth=1, relief="sunken")
f2 = GradientFrame(self, "#ffc851", "lig... |
import csv
#***** THE function *****
# returns delimiter or error
def cleverSniffFile(file) :
reader = file.read()
# saved data (is stocked if next round of cleverSniffIn is sufficiant)
lines = []
dictList = []
# first try with first 10 rows
lines = getLinesFrom(reader, 0, 9)
dictList = mak... |
#program prints sequences and the number of bases in each sequenc
import question2 #used for input and counting base sequence
#changes the format of sequence and prints sequence and base count
def printSeq(seq,base_counts,seqno=0,gcratio=-1):
format_seq = seq[:]
format_seq= format_seq.replace('g',... |
# -*- coding: utf-8 -*-
import numpy as np
def CompPermY(age,ed,experience,unemployment,sex,Y,RetirementAge):
"""
Takes age, years of education, years of job experience, months of
unemployment, sex and Fulltime income to compute a matrix of possible
values for permanent income in each remaining year in... |
def factorial(n):
if n > 0:
return n * factorial(n-1)
elif n == 0:
return 1
else:
return "Error"
def combination(n,r):
if 0 <= r <= n:
return factorial(n) // (factorial(r) * factorial(n-r))
else:
return "Error"
while True:
n = int(input("Enter n:"))
if... |
import time
def fibo(n):
if n <= 1:
return n
return fibo(n-1) + fibo(n-2)
def iterfibo(n):
if n <= 1:
return n
fibolist=[0,1]
for i in range(2,n+1):
fibolist.append(fibolist[i-2] + fibolist[i-1])
return fibolist[-1]
while True:
n = int(input("Enter a number:"))
... |
# Name: Write Your Name Here
# Email: Your Email
# SUID: Your Student ID
#
# By submitting this file as my own work, I declare that this
# code has been written on my own with no unauthorized help. I agree to the
# CU Honor Code. I am also aware that plagiarizing code may result in
# a failing grade for this class.
fro... |
def binary_array_to_number(arr):
result = 0
for i, num in enumerate(arr[::-1]):
if num:
result += 2 ** i
return result
binary_array_to_number([0, 0, 1, 0])
|
print("안녕하세요?")
name=input("이름을 입력하세요: ")
print("입력한 이름은 {s}입니다" .format(s=name))
print("입력한 이름은 {}입니다" .format(name))
print("입력한 이름은 %s입니다" %(name))
#--------------------------------------#
print("123")
print("Hello!")
print("")
print("a")
print(" ")
print("I'm a good boy.")
print('저 "반달곰"은 어디에서 왔을까?') |
# Задача-1: Запросите у пользователя его возраст.
# Если ему есть 18 лет, выведите: "Доступ разрешен",
# иначе "Извините, пользоваться данным ресурсом можно только с 18 лет"
vzrst = int(input())
vzrst = vzrst - 18
if vzrst > 0:
print("Василий на " + str(vzrst) + " года/лет больше 18")
elif vzrst < 0:
print("Васили... |
from queue import Queue
class Node:
def __init__(self, val):
self.value = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def is_empty(self):
return self.root is None
def add(self, value):
if not self.ro... |
import random
greetingOptions = ["hello", "yo", "hola", "namaste"]
def mccurdyChat(text):
text = text.replace(",", "")
text = text.replace(".", "")
text = text.replace("!", "")
words = text.split(" ")
for word in words:
if word.lower() in greetingOptions:
return random.choice(greetingOptions).c... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
array = []
for list in lists:
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
re... |
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if m == n:
return head
n = n - m
node = head
left_tail = None
for _ in range(m - 1):
... |
class Solution:
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if k == 0:
return [[]]
if k == n:
return [[i for i in range(1, n + 1)]]
ans1 = self.combine(n - 1, k)
ans2 = self.combine... |
#!/usr/bin/python
# -*- coding: utf-8 -*
"""
Exemplo tirado do site:
http://recologia.com.br/2015/07/programacao-multi-thread-em-python/
Autor original: Augusto Ribas
Modificado por: Koheleth(Aurélio)
Esse exemplo me chamou atenção por usar classes com thread
Fiz a adaptação e correções de python 2.7 para python 3.6
... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 16:06:05 2020
@author: damaniayash
"""
#Fractal Generation using Chaos Game
import turtle
import argparse
#from turtle import Screen
import random
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--Animation",type = bool,default = False, h... |
#https://leetcode.com/problems/ugly-number/
'''
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
Input: 6
Output: true
Explanation: 6 = 2 × 3
'''
def ugly(num):
ugly = 0
if num < 1:
return False
while num > 1 and ugly == 0:
if num % 2 == 0:
... |
class Subsets:
def __init__(self):
pass
def subsets(self,s):
n = len(s)
subs = [None for i in range(n)]
self.helper(s, subs, n)
print(self.count)
def helper(self,s,subs,k):
if k == 0:
print(subs)
# self.print_subsets(subs)
... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, val):
new_node = Node(val)
if self.head == None:
self.head = new_node
else:
temp = self.head
... |
#https://leetcode.com/problems/two-sum/
'''
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
'''
class Solution:
def twoSum(self,nums,target):
hash = {}
for i in ... |
class Substrings:
def __init__(self):
pass
def substring(self,s):
self.helper(s,[0,0,0],len(s))
def helper(self,s,sub,k):
if k == 0:
print(s)
else:
for i in range(k):
sub[i] = s[i]
self.helper(s,sub,k-1)
if __name__... |
import random
# red = range(1, 36)
# blue = range(1, 13)
# print(red[1], "\n", blue)
redChoice = []
blueChoice = []
lotteryNums = []
i, j, k =0, 0, 0
# print(j)
# while k<5:
# while i<5:
# chooseRed = random.randint(1, 35)
# redChoice.append(chooseRed)
# i+=1
# while j<2:
# chooseBlue =... |
import string
import pygame
#Custom exceptions
class Overflow(Exception):
"""Integer is greater than 999,999,999,999"""
#this function return a string of how-to-read a nber in range 0-999
def basic_read_3_members(s, region = 'north'):
ns = ['Không', 'Một', 'Hai', 'Ba', 'Bốn', 'Năm', 'Sáu', 'Bảy', 'Tám', 'Chín']
o... |
import itertools
# part 1
with open("01_input.txt") as input_file:
input_ = '0' + ''.join(line.strip() for line in input_file.readlines())
print(eval(input_))
# part 2
with open("01_input.txt") as input_file:
input_lines = (int(line.strip()) for line in input_file.readlines())
input_cycle = itertools.... |
lista = range(1,100)
for num in lista:
if num % 2 == 0:
print(f"Num par: {num}")
else:
print(f"Num impar: {num}") |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def PrintTree(self):
print(self.data)
root = Node(10)
root.PrintTree()
Traversing a Linked List
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
... |
def findMinSum(num):
sum = 0
# Find factors of number
# and add to the sum
i = 2
while(i * i <= num):
while(num % i == 0):
sum += i
num /= i
i += 1
sum += num
# Return sum of numbers
# having minimum product
return sum
... |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
result = []
for i in range(len(matrix)):
result.append([])
for j in range(len(matrix[i])):
result[i].append(matrix[i][j]**2)
return result
|
'''
Шахматный конь ходит буквой “Г” — на две клетки по вертикали в любом направлении и на одну клетку по горизонтали,
или наоборот. Даны две различные клетки шахматной доски, определите, может ли конь попасть с первой клетки на вторую
одним ходом.
'''
msg = ('положение коня по горизонтали:', 'положение коня по вертикал... |
# Дан текст. Выведите слово, которое в этом тексте встречается чаще всего. Если таких слов несколько, выведите все,
# которые подходять по условию задачи.
# Задачу необходимо решить с использованием словаря.
s = 'антошка антошка идем копать картошку \nантошка антошка идем копать картошку'
print(s, '\n')
sp = s.split(... |
'''4. В первый день спортсмен пробежал `x` километров, а затем он каждый день увеличивал пробег на 10% от предыдущего
значения. По данному числу `y` определите номер дня, на который пробег спортсмена составит не менее `y` километров.
Программа получает на вход числа `x` и `y` и должна вывести одно число - номер дня.'''... |
# В единственной строке записан текст. Для каждого слова из данного текста подсчитайте, сколько раз оно встречалось в
# этом тексте ранее.
# Словом считается последовательность непробельных символов идущих подряд, слова разделены одним или большим числом
# пробелов или символами конца строки.
s = 'антошка антошка иде... |
# В текстовом файле посчитать количество строк, а также для каждой отдельной строки определить количество в ней символов и слов
file = open('grade.txt', encoding='utf-8')
lst = file.readlines()
print("Количество строк:", len(lst))
count = 0
for s in lst:
count += 1
slova = s.split()
print('Строка', count,... |
# 9. Дан список целых чисел, индекс k и значение C. Необходимо вставить в список на позицию с индексом k значение
# C, сдвинув все элементы, имевшие индекс не менее k, вправо. Поскольку при этом количество элементов в списке
# увеличивается, необходимо, перед сдвигом, увеличить список на один элемент, используя метод a... |
# Написать функцию `is_prime`, принимающую 1 аргумент — число от 0 до 1000, и возвращающую `True`, если оно простое, и
# `False` - иначе.
def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
x = int(input('Введите число (2-1000): '))
print('is_prime: ', is_prime(x... |
# Написать класс, описывающий группу студентов - `Group`. Данный класс хранит студентов в виде списка объектов типа
# класса `Student` также реализуется с помощью соответствующего класса.
# В классах реализовать необходимай набор атрибутов (Например класс `Student` должен иметь атрибуты `name`, `age`,
# `grades`), а т... |
#Note, Do not inherit Image class. Image class is not made to be inherited!
#you can just save the new image in self.img
from PIL import Image, ImageDraw, ImageFont
from weather import Weather
class Combine:
def __init__(self,bg,weather):
#save backgroud image in the class
self.img=Image.ope... |
#Write a function that will reverse a integer number using a stack and return the reversed number as an integer.
# For example, if your input number is 3479 the function will return 9743.
def size(stack):
return len(stack)
def isEmpty(stack):
if size(stack) == 0:
return true
def push(stack... |
'''
Given a non-negative integer num,
return the number of steps to reduce it to zero.
If the current number is even, you have to divide it by 2,
otherwise, you have to subtract 1 from it.
'''
def numberOfSteps(num):
count = 0
while (num != 0):
if (num % 2 == 0):
num /= 2
... |
# First, I removed the split... it is already an array
str1 = 'ab cdefg sh'
str2 = 'abcdefg b sh'
#then creating a new variable to store the result after
#comparing the strings. You note that I added result2 because
#if string 2 is longer than string 1 then you have extra characters
#in result 2, if string 1 is... |
#introduction to the game
print('Hello! What is your name?')
myName = input("")
print('Well, ' + myName + 'And this is the music guessing game')
print("Choose rap, pop, or rock")
catergory=input(" ")
print("The game is about to start!")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 17:29:12 2019
@author: peterawest
"""
import random
def get_split(X,T,Y, train_frac = 0.8, val_frac = None, shuffle_inds = None):
'''
This function takes data lists X, T, Y and splits them
into train, validation, and optional te... |
"""
AUTHOR: jorgeluisrocha
LAST UPDATED: 10-22-2016
This file in its current conception is to create a Perceptron object and
has two functions which allows it to learn how to behave like an OR gate and
an AND gate.
"""
from random import choice
from numpy import array, dot, random
from pylab import plot, ylim
class ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import csv
import pandas as pd
# In[2]:
pybank_path = 'C:/Users/bassa/projects/PyBank/Resources/'
pybank_csv_file = 'budget_data.csv'
pybank_csv_filepath = os.path.join( pybank_path, pybank_csv_file)
print(pybank_csv_filepath)
# In[4]:
pybank_df = pd.r... |
def Fibo(x):
a = [0,1]
#while i < x:
for n in range(2,x):
# if n == 0:
# #print('%d' %(1),)
# quit
# elif n == 1:
# #print('%d' %(1))
# quit
# else:
# a.append(a[n-2]+a[n-1])
a.append(a[n-2] + a[n-1])
return a
#... |
#序列总结
#序列:字符串str、列表list、元组tuple
#它们共有的特性:
#1.序列中的每个元素都被分配一个序号,有序特性。
#2.切片:
print('hello python'[6:12])
print('hello python'[0:8:2])
#3.序列中是否包含某个元素?
print(3 in [1,2,3,4])
print(3 not in [1,2,3,4])
#4.序列中元素个数
print(len('hello python'))
print(len([1,2,3,4,5,6]))
#5.序列中最大max、最小元素,max(),min() |
# 1.必须参数,定义了多少个形参,就需要传递多少个实参
# 2.关键字参数
# 是指在函数调用时,通过形参关键字与实参关联起来,即:指定实参传递给哪个形参。
def add(x,y):
result = x + y
return result
c = add(2,3) #需考虑顺序,位置参数
d = add(y=3,x=2) #关键字参数,通过形参关键字将实参传递给哪个形参,意义在于代码的可读性
print(c)
print(d)
# 3.默认参数,函数定义时,给形参指定默认值,调用时可以不再传递该形参的实参。
# 4.可变参数 |
#集合set
#{}定义,各元素用逗号分隔
#如何定义空的集合?
print(type({})) #{}这是空的字典
print(type(set())) #set()才是空的集合定义方法
#特性:
#1.无序,不支持索引(序号)indexing、切片subscriptable操作;
#2.不重复
#支持哪些操作:
#len()、in、max()、min()
#特殊操作
#1.求两个集合的差集
a = {1,2,3,4,5,6}
b = {3,4,7}
print(a-b)
#2.求两个集合的交集
print(a&b)
#3.求连个集合的并集
print(a | b)
|
import time
#方法二:定义一个新函数,调用原来函数,新函数里编写新增功能代码。
#本示例不正确
import time
def func(a):
print('hello')
time.sleep(1)
print(a)
def deco(func):
startTime = time.time()
# func() #注销后可执行,但逻辑不对
endTime = time.time()
usecs = (endTime - startTime)*1000000
print('Time is %d us'%usecs)
deco(func('Py... |
#类属性变量和实例属性变量
#类变量是什么,有什么作用?和类相关联在一起的,
#实例变量是什么,有什么作用?和对象相关联在一起的;使用self.name来保存对象的特征值;
#
class Student():
name = '' #类变量,这里的类变量name和age对于抽象的类来说没有意义。
age = 0
def __init__(self,name,age):
self.name = name
#实例属性变量,使用self关键字(其实是可以随意起个名字,并不是关键字)来定义实例变量,
# 与其他语言有所不同
#self... |
##将字符串各个字符作为列表的元素
strings = 'abcd1234'
L = []
for i in strings:
L.append(i)
print(L)
##计算X的N次幂值
import time
def power(x,n):
s = 1
startTime = time.time()
while n > 0:
n = n -1
s = s * x
print(s)
endTime = time.time()
msecs = (endTime - startTime)*1000
print(msecs)
power(... |
#字典
#多个key和value组成,与集合set很像,与序列不同。不允许有相同的key。
print(type({}))
#字典最重要和常用的操作:通过key得到/访问value
a ={'Q':'新月打击','W':'苍白之瀑','E':'月之降临','R':'月神冲刺'}
print(a['Q'])
b ={1:'新月打击','1':'苍白之瀑','E':'月之降临','R':'月神冲刺'}
print(b)
##value可以是python任意一种数据类型。
##key需是不可变的数据类型,如:int、‘str’、元组tuple;列表和字典不能作为key,它们是可变数据类型。
#可变数据类型: |
#高阶函数-map/reduce
#python内建了map()、reduce()函数
#1.map()函数接收两个参数:一个是函数,一个是iterable对象。map将传入的函数
#依次作用于序列的每个元素,并将结果作为新的iterator对象返回。
def f(x):
return x*x
L = [1,2,3,4,5,6,7,8,9,10]
r = map(f,L)
print(list(r))
r2 = map(str,L)
print(list(r2))
#2.reduce()函数。
#reduce()函数接收两个参数:一个是函数,一个是iterable对象。这个函数作用于
#这个序列上,这个函数每次必须... |
#逻辑运算符:对布尔类型进行运算,返回布尔值;运算可以是非布尔类型,结果也可以是非布尔类型;‘
# 1.not,and,or;
#and,且(与);
#or,或;
#not,非;
# 2.顺序:not,and,or
#int,float:0被认为是False,非0被认为是True;
#str,tuple,list,dic:空被认为是False,否则被认为是True;
# >>> 1 and 1
# 1
# >>> 1 and 2
# 2
# >>> 2 and 1
# 1
# >>> 2 or 1
# 2
# >>> 1 or 2
# 1
# >>> not 2
# False
# >>> 'a' and 'b'
# 'b... |
n = 10000
numbers = list(range(2, n + 1))
i = 2
while i < 10001:
for m in numbers:
if i < m and m % i == 0:
numbers.remove(m)
i = i + 1
print(numbers)
print("\nThere were", len(numbers), "prime numbers up to", n)
import math
def isPrime(n):
if n <= 1:
return Fa... |
#列表生成式
# 1. 生成自然数2次幂序列,使用for循环:
L = []
for x in range(1,11):
L.append(x*x)
print(L)
#2.使用列表生成式(list exprehensions)
L = [x*x for x in range(1,11)]
print(L)
#3.列表生成式可以在for后面加if判断,比如生成仅偶数、奇数的序列
L1 = [x*x for x in range(1,11) if x % 2 == 0]
L2 = [x*x for x in range(1,11) if x % 2 == 1]
print(L1)
print(L2)
#4.for循环... |
a = [1,2,3]
b = a
print(id(a),id(b),id([1,2,3]))
print(a is b)
print(a == b)
[1,2,3].append(4)
print(id(a),id(b),id([1,2,3,4]))
print(a is b)
print(a == b)
[1,2,3].insert(0,0)
print(id(a),id(b),id([0,1,2,3,4]))
print(a is b)
print(a == b)
a.append(5)
print(id(a),id(b),id([1,2,3,4,5]))
print(a is b)
print(a == b)
#... |
def anagram(str1,str2):
str1 = str1.replace(' ', '').lower()
str2 = str2.replace(' ', '').lower()
if len(str1) != len(str2):
return False
dictionary = {}
for char in str1:
if char in dictionary:
dictionary[char] += 1
else:
dictionary[char] = ... |
#import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#import data set
dataset = pd.read_csv("./Data.csv")
#feature extraction
x = dataset.iloc[:, :-1].values
#vector of depentend variable
y = dataset.iloc[:,-1].values
#take care of missing data
from sklearn.impute import Sim... |
def create_matrix(input_file, start, end):
matrix = dict()
with open(input_file) as file:
for i, line in enumerate(file):
line = line.strip().split()
if i == start:
(rows, columns) = int(line[0]), int(line[1])
if start < i <= end:
... |
#!/usr/bin/python3
import sys
import numpy as np
def main():
if len(sys.argv) is not 2:
print("Usage: ./01.py input")
return
code = [int(i) for i in np.genfromtxt(sys.argv[1], delimiter=',')]
code[1] = 12
code[2] = 2
length = len(code)
i = 0
while i < length and code[i] is ... |
#---------------------------------------------------Loading Image and the corner Detection test-------------------------------------------------
#Importing Modules
import numpy as np
import os
import matplotlib.pyplot as plt
import cv2
#Loading mage in Opencv Memory for Processing
img=cv2.imread('Image Location',cv... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 22:29:23 2020
@author: andy6
"""
a = {"Sunday":"星期日",
"Monday":"星期一",
"Tuesday":"星期二",
"Wednesday" :"星期三",
"Thursday":"星期四",
"Friday":"星期五",
"Saturday":"星期六"}
b = input("輸入星期英文")
if b in a:
print(a[b])
else:
pr... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 21:10:34 2020
@author: andy6
"""
'''
x = int(input("輸入數字"))
while x % 3 == 0:
print(x,(x/3))
break
while x % 3 == 1:
print(x,(x+2)/3)
break
while x % 3 == 2:
print(x,(x+1)/3)
break
'''
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 22:03:10 2020
@author: andy6
"""
import math
n = int(input("請輸入座號"))
for y in range(1,n+1,3):
continue
print(math.ceil(y/3))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 10:03:05 2020
@author: andy6
"""
print(str.lower("ABC")) #將字串轉成小寫字
print(str.upper("abc")) #將字串轉成大寫字
print(str.title("abc")) #將字串轉成第一個字母大寫
print(str.swapcase("abcABC")) #將字串大寫改小寫,小寫改大寫
print("abc cccccccccc") #尚未刪除
str =("abc cccccc... |
# Script Name : Euler_Problem_2.py
# Author : Shivakumar Mahakali
#
# Description : Solution to Problem 2 from Project Euler.
#
# Problem 2 : Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.