text
stringlengths
37
1.41M
a=input("enter first string:") b=input("enter second string:") c=list(a) d=list(b) for i in range(2): c[i]=b[i] d[i]=a[i] e=''.join(c) f=''.join(d) g=e+' '+f print(g)
key=int(input("Enter the key (int) to be added:")) value=int(input("Enter the value for the key to be added:")) a={0:2,1:3} a.update({key:value}) print("Updated dictionary is:") print(a)
# 2019/09/30 n=int(input()) def is_prime(n): if n==1:return False for i in range(2,int(pow(n,0.5)+1)): if n%i:continue return False return True def is_poi(n): if n==1:return False if n%2 and n%5 and n%3: return True else: return False i...
# 2019/08/31 n=int(input()) s=[] for i in range(n): s.append(input()[::-1]) s.sort() for e in s: print(e[::-1]) #きれいな解答 n = int(input()) s = sorted([input()[::-1] for _ in range(n)]) print("\n".join(map(lambda x: x[::-1], s))) #←ここいいよね
# https://atcoder.jp/contests/abc043/tasks/abc043_b s=input() res=[] for e in s: if e=='B': if res: res.pop() else:continue else: res.append(e) print(*res,sep='')
# 2019/08/14 s=set(input()) if ('N' in s and 'S' not in s) or ('S' in s and 'N' not in s)\ or ('W' in s and 'E' not in s) or ('E' in s and 'W' not in s): print('No') else: print('Yes') # きれいな書き方 s=set(input()) if ('N' in s)^('S' in s) or ('W' in s)^('E' in s): print('No') else: print...
# 2019/07/29 # Union-Find input=open(0).readline class unionfind(): def __init__(self,n): self.par=list(range(n+1)) self.rank=[0]*(n+1) def find(self,x): if self.par[x]==x: return x else: self.par[x]=self.find(self.par[x]) ...
# 素数定理 import math def get_num(x): return x / (math.log(x, math.e)) # x = 10**216 # print(get_num(10**216) - get_num(10**215)) # print(get_num(10**215))
from collections import Counter n=int(input()) s=[input() for _ in range(n)] c=Counter(s) mx=c.most_common()[0][1] ans=[] for e in c.most_common(): if mx==e[1]: ans.append(e[0]) ans.sort() print(*ans,sep='\n')
s=list(input()) odd=['R','U','D'] even=['L','U','D'] for i in range(len(s)): if (i+1)%2: if s[i] not in odd: print('No') exit() else: if s[i] not in even: print('No') exit() print('Yes')
import numpy as np import math import heapq class Navigation: def __init__(self): self.n = -1 self.edges = -1 self.node = dict() self.graph = [] self.start = -1 self.goal = -1 self.takeInput() def takeInput(self): #Take input from file fi...
class Environment : def __init__(self, xd, yd, xs, ys) : self.xd = xd self.yd = yd self.xr = xs self.yr = ys def updateState(self, direction) : if(direction == "left") : self.xr -= 1 elif(direction == "right") : self.xr += 1 elif(direction == "up") : self.yr += 1 elif(direction == "down") :...
#这个=是赋值运算符 a = 1 b = 2 #加法 c = a+b print(c) #减法 d = a-b print(d) #乘法 f = a*b print(f) #除法 g = a/b print(g) #取商 h = a//b print(h) #取余数 k = a%b print(k) #幂 l = a**b print(l)
''' 把手机号验证的功能是不是拆除来了 ''' def register(account,pwd): a = isPhone(account) if a: print("呵呵呵") def login(account,pwd): result = isPhone(account) if result: print("哈哈哈") def isPhone(account):#判断手机号合法不合法 if len(account) == 11 and account.startswith("1"): return True else: ...
d = {"name":"xiaoyuan","age":28,"sex":"男"} for i in d.items(): for j in i: print(j) for k,v in d.items(): print(k,v)
import random number = random.randint(1,100) count = 0 for i in range(10): user = int(input("请输入数字")) if user > number: print("猜大了") elif user < number: print("猜小了") else: print("猜对了") break count+=1#猜的次数 if count == 1: print("大神") elif count > 1 and count < 5: print("半仙") elif count >=5 and count < 9...
list = []#存放名字 print("名片管理系统".center(50,"*")) while True: print("1:添加名片".center(50," ")) print("2:查找名片".center(50," ")) print("3:修改名片".center(50," ")) print("4:删除名片".center(50," ")) print("5:退出".center(50," ")) num = int(input("请选择功能")) if num == 1: d = {}#空字典 name = input...
age = int(input("请输入年龄")) sex = input("请输入性别") #假如是女孩并且大于15岁 才能玩游戏 #假如是男孩 # 17岁 男 if age > 15 and sex =="女": print("可以玩游戏") elif age > 18 or sex == "男": print("回家种地") else: print("哈哈哈哈哈哈哈哈哈")
account = input("请输入账号") pwd = input("请输入密码") print("欢迎光临您的个人银行\n祝你花钱愉快") money = 100000 #如果计算128天的利息 other_money = 0.04/365*128*money print("你的个人资产:%d,昨天收益大概是%d"%(money,other_money)) need_money = int(input("请输入取款金额")) #判断钱够不够 f_money = money+other_money-need_money print("剩余金额:%d"%f_money)
a = "hello world, my name is python" print(a.upper()) #모든 소문자를 대문자로 변경 b = "LOST ARK" print(b.lower()) #모든 대문자를 소문자로 변경 a1 = """ hello guys haha """ print("------") print(a1) print("------") print(a1.strip()) #앞뒤 공백 제거 print("안녕" in "안녕하세요") #앞의 문자열이 뒤에 포함이 되어있나 검사 ex = "10 20 30 40 50 70 9 0".split() print(ex)
a = 0 b = 2 print(a) a+=10 print(a) a+=10 print(a) print(b) b**=2 print(b) b**=2 print(b) b**=2 print(b) say = "Hello" print(say) say+="!" print(say) say+="!" print(say) say+="!" print(say)
class Entry: def __init__(self, address, available, last_used): """ Constructor for Entry data structure. self.address -> str self.available -> bool self.last_used -> datetime """ self.address = address self.available = available self.last_us...
import streamlit as st import pandas as pd Year_List = [2, 3, 4, 5, 6, 7, 8, 9, 10] st.write(""" # Compound Interest Calculator! """) st.sidebar.header('User Input Values') def user_input_features(): Int_Rate = st.sidebar.slider('Interest Rate in %', 6.0, 42.0, 10.0) Principal = st.sidebar.text_input('Pl...
import math from functools import total_ordering @total_ordering class Polygon: """ Regular strictly convex polygon whose angles are less then 180 deg and sides have equal length """ def __init__(self, edges, circumradius): edges = int(edges) if edges < 3: raise ValueError(...
# A palindromic number reads the same both ways. The largest palindrome made from # the product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palindrome made from the product of two 3-digit numbers. #def is_palindromic(num): # num_str = str(num) # i, j = 0, len(num_str) - 1 # while i <= j: # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from math import sqrt from util import is_prime ''' Problem 179 Find the number of integers 1 < n < 107, for which n and n + 1 have the same number of positive divisors. For example, 14 has the positive divisors 1, 2, 7, 14 while 15 has 1, 3, 5, 15. ''' def factor_cnt(n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Problem 131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n3 + n2p is a perfect cube. For example, when p = 19, 83 + 82×19 = 123. What is perhaps most surprising is that for each prime with this property the val...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Problem 303 For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only digits ≤ 2. Thus f(2)=2, f(3)=12, f(7)=21, f(42)=210, f(89)=1121222. Also, . n = 1 ~ 100, f(n)/n = 11363107 Find . n = 1 ~ 10000, f(n)/n = ? ''...
"""Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка. Подсказка: использовать функцию reduce().""" from functools import reduce def...
from tank import Tank from pump import Pump from valve import Valve from stirrer import Stirrer from heater import Heater import time tanks = [Tank(500, False, False, Valve(10, 2)), # coffee Tank(1000, False, Heater(300), False), # water Tank(1000, Stirrer(10), False, Valve(50, 4)), # main tank ...
#!/usr/bin/python3 def fizzbuzz(): for c in range(1, 101): if c % 3 == 0 and c % 5 == 0: print("FizzBuzz", end=' ') elif c % 3 == 0: print("Fizz", end=' ') elif c % 5 == 0: print("Buzz", end=' ') else: print(c, end=' ')
#!/usr/bin/python3 ''' 1. Write to a file ''' def write_file(filename="", text=""): ''' writes a string to a text file (UTF8) and returns the number of characters written''' with open(filename, mode="w", encoding="utf-8") as f: r = f.write(text) return r
car = 100 space_in_a_car = 4.0 drivers = 30 passenger = 90 cars_not_drivers = car - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car averge_passenger_per_car = passenger / cars_driven print("There are", car, "can available.") print("There are only", drivers, "drivers available") ...
import sqlite3 with sqlite3.connect("cars.db") as connection: c = connection.cursor() c.execute("UPDATE cars SET Quantity=6 WHERE MAKE='Honda'") c.execute("SELECT * FROM cars") rows = c.fetchall() for r in rows: print r[0], r[1], r[2]
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # # Using Pyndamics to Simulate Dynamical Systems # # Pyndamics provides a way to describe a dynamical system in terms of the differential equations, or the stock-flow formalism. It is a wrapper around the Scipy odeint function, with further functio...
""" (C) Ivan Chanke 2020 Contains classes: Node - > Layer -> Network The three constantly refer to one another and aren't supposed to work separately For details on math model visit GitHub directory corresponding to the project """ import numpy as np import pickle bias_signal = 1 def load_model(file...
# Exercise 30: http://www.ling.gu.se/~lager/python_exercises.html def translate(words): '''A function that takes a list of English words and returns a list of Swedish words.''' dictionary = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"} ...
# Exercise 10: http://www.ling.gu.se/~lager/python_exercises.html def overlapping(list1, list2): '''A function that takes two lists and returns True if they have at least one member in common, False otherwise.''' boo = False for j in list1: for z in list2: if j == z: ...
# Exercise 6: http://www.ling.gu.se/~lager/python_exercises.html def sum(nums): '''A function that sums all the values in a list.''' a = 0 for i in nums: a += i return a def multiply(nums): '''A function that multiplies all the values in a list.''' m = 1 for i in nums: m = ...
#!/usr/bin/env python """ Description : Change colours on an RGB LED Author : Russell E-mail : russellshome@gmail.com Date : 2020/08/26 Circuit : https://crcit.net/c/8bc8330a72874a9d97dc4b0c0dcb0748 My RGB LED has a common anode In this case 0 means on full and 1 is off Other RGB LEDs have a commo...
#!/usr/bin/env python #code to compare files #print first line in which there is difference from sys import argv,exit import os if(len(argv) != 3): print('require 3 arguments') exit() if(not os.path.exists(argv[1])): print('no file of name '+argv[1]) exit() if(not os.path.exists(argv[2])): print(...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import time from datetime import datetime, timezone, timedelta def cur_time(): """ 返回当前时间 :return: 当前时间,如:2021-05-27 02:29:12.096762+08:00 """ dt = datetime.utcnow().replace(tzinfo = timezone.utc) diff_8 = timezone(timedelta(hours = 8)) return dt....
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 19:52:41 2021 @author: HP """ N=int(input()) for i in range(N): num=list(map(int,input().split(" "))) num.sort() print(num[-2])
#! /usr/bin/env python from random import * num = randint(0, 800); for i in range(num): print(randint(-2**31, 2**31)) print(0)
def hs(a): n = len(a) for i in range(n // 2 - 1, -1, -1): heapiy(a, n, i) for i in range(n-1, 0, -1): a[i], a[0] = a[0], a[i] heapiy(a, i, 0) def heapiy(a, n, i): larger = i left = 2 * i + 1 right = 2 * i + 2 if left < n and a[i] < a[left]: larger = left if right < n and a[l...
class Textil: def __init__(self, width, height): self.width = width self.height = height def get_square_coat(self): return self.width / 6.5 + 0.5 def get_square_jacket(self): return self.height * 2 + 0.3 @property def get_square_full(self): return str(f'Пло...
class Worker: def __init__(self, name, surname, position, wage, bonus): self.name = name self.surname = surname self.position = position self._income = {"wage" : wage, "bonus" : bonus} class Position(Worker): def __init__(self, name, surname, position, wage, bonus): sup...
my_list = [7, 5, 3, 3, 2] print(my_list) digit = int(input("Введите число (или 000 для выхода): ")) while digit != 000: for elem in range(len(my_list)): if my_list[elem] == digit: my_list.insert(elem + 1, digit) break elif my_list[0] < digit: my_list.insert(0, ...
class ComplexNumber: def __init__(self, a, b, *args): self.a = a self.b = b #числа вида a+b*i, где a,b — вещественные числа, i — мнимая единица self.z = 'a + b * i' def __add__(self, other_numb): print(f'Сумма z1 и z2 равна') return f'z = {self.a + other_numb.a}...
def reverse_number(number): rest_number, numeral = divmod(number, 10) if rest_number == 0: return str(numeral) else: return str(numeral) + str(reverse_number(rest_number)) number = int(input("Введите число: ")) print(f'Перевернутое число = {reverse_number(number)}')
class Test(): '''This is a test for making a class.''' def InitializeMethoc(self, one, two, three): '''Initializing the Test class.''' # The self argument is passed AUTOMATICALLY # These three attributes will be passed when we create a class instance. # This is because they have the SELF prefix. They are the...
# using a function to retrn a dictionary def build_person(firstname, lastname, age=''): '''Return a dictionary of information about a person.''' person = {'first': firstname, 'last': lastname} if age: person['age'] = age return person musician = build_person('jimi', 'hendrix', age=27) print(musician)
class Car(): '''A simple attempt to represent a car.''' def __init__(self, make, model, year): '''Initialize attributes to describe a car.''' self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): '''Return a neatly formatted descriptive name.''' ...
num=int(input("enter a no=")) i=1 a=[ ] while i<=num: j=1 b=[ ] if i==1 and j==1: a.append(b) else: while j<=i: b.append(j) j=j+1 a.append(b) i=i+1 print(a)
import numpy as np import matplotlib.pyplot as plt def random_walk(walk_length): list_of_sums = [] x = np.random.choice([-1, 1], size = walk_length, replace = True, p = [0.5, 0.5]) for step in range(len(x)): value = np.sum(x[0:(step+1)]) list_of_sums.append(value) return x, list_of_su...
def check_positive(v): import argparse num = int(v) if num <= 0: raise argparse.ArgumentTypeError( f"{v} is an invalid number. Please use only positive") return num
def input_float(msg): result = None while result is None: try: result = float(input('Введите ' + msg + ' :')) except ValueError: pass return result x = input_float('делимое') y = input_float('делитель') try: print("Результат деления", x, 'на', y, 'равен', x / y) ...
#位1的个数 class Solution: def hammingWeight(self, n: int) -> int: res=0 while n: res+=n&1 n>>=1 return res #2的幂 class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and n & (n - 1) == 0 #1122数组的相对排序 class Solution: def relativeSortArray(...
import requests from bs4 import BeautifulSoup """This script uses BeautifulSoup to scrape the links for all of the studies currently on clinicaltrials.gov off of a clinicaltrials.gov page for webcrawlers.""" def ClinicalCrawl(): data = requests.get("http://clinicaltrials.gov/ct2/about-site/crawling").text cr...
# Resolução referente 3 - Funções """ 3 - Crie uma função que receba 2 números. O primeiro é um valor e o segundo um percentual (ex. 10%). Retorne (return) o valor do primeiro número somado do aumento do percentual do mesmo. """ def aumento(valor, porct): return (valor*(porct/100)) + valor valor = float(input(...
# Exercício de List Comprehension ''' Desafio - Manipular o valor de string separando tendo resultado um conjunto de 0 a 9 e depois adicionar um ponto entre cada grupo. ''' string = '01234567890123456789012345678901234567890123456789012345678901234567890123456789' lista_separado = [string[i:i + 10] for i in r...
import json class JsonManager: """ It will loads data and dumps data into json. Written By Saurav Paul""" @staticmethod def json_read(json_file): try: with open(json_file, "r") as read_file: data = json.load(read_file) return data except Exception a...
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): if k % 2 == 0: extension = 1 window_range = k // 2 else: extension = 0 window_range = 1 + k // 2 # Your code ...
#! python3 # mail_lists.py - assign a name with more than 3 letters email_list = { 'lsit_a': 'abcd@website1.com,bcd@website2.com', 'list_b':'aaab@website2.com, aaaabc@website3.com', 'list_c':'new123@website4.com, new222@website5.com', } import sys, pyperclip if len(sys.argv) < 2: print('Usage of the p...
# Returns a new string where for every char in the original string, there are two chars. def double_char(string): new_str = "" for i in range(len(string)): new_str += 2*string[i:i+1] return new_str print(double_char("The")) print(double_char("AAABB")) print(double_char("Hi-There")) pr...
""" This program calculates the sum of the array elemets The approach i used was i started from the last element and came to the first element and calculated the result """ def sumArray(arr,leng): if(leng == 0): #Base case if we dont have any element in the array return 0 return arr[leng-1] + sumA...
#loops in python resolve to two: while and for loops for simplicity def main(): x = 0 while(x<=10): print(x) x+=1 for x in range(5,10): print(x) daysOfWeek = ["Mon","Tue","Wed","Thur","Fri","Sat","Sun"] for x in daysOfWeek: print(x) for x in range(0,10): ...
""" This is a "nester.py" module, and it provides one function called print_lol() which prints list that may or maynot include nested list """ def print_lol(the_list): """ This function takes positional argument called "the_list", whcih is any python list (of possibly nested list). Each data item in the provided li...
# 逻辑运算符:构造复杂条件 # 逻辑与 and 并且同时 import random # a = random.randint(1,5) # if a > 1 and a < 3: # print("true") # else: # print("false") # 可以转换为假: '' 0 0.0 False None # 如果第一个操作数是真,结果就是第二个操作数的值 print(11 and "ok") # 如果第一个操作数是假,结果就是第一个操作数的值 print(0 and 15) # 如果第一个操作数为假,逻辑与不计算第二个操作数的值,这个叫逻辑短路 a = 3 a...
# 7.计算从1到1000以内所有能同时被3,5和7整除的数的和并输出 a = 1 b = [] c = 0 while a < 1000: if a % 3 == 0 and a % 5 == 0 and a % 7 == 0: b.append(a) a += 1 print(b) for i in range(len(b)): c += b[i] print(c)
# 函数不返回值,系统默认返回None # def add(a,b): # print(a + b) # res = add(2,3) # print(res) # def add(a,b): # # 返回值,只能有一个返回值 # # 结束函数调用 # return a + b # print("hello") # res = add(3,2) # print(res) # def add(a,b): # if a < 0: # return -a + b # else: # print("hello") ...
# map 内置函数 # 遍历一个可迭代对象,用传入函数处理可迭代对象的每一个元素 # a = [10,23,90,83] # def mul(x): # return 2*x # 得到一个迭代器 # res = map(mul,a) # print(res) # print(list(map(mul,a))) # map 函数的内部实现 # def tmp(mul,a): # for i in range(len(a)): # yield mul(a[i]) # res = tmp(mul,a) # print(res,list(res)) # res = ...
# 模拟骰子 # 第一生成一个[1,6]的随机数 # 根据随机数判断吃啥 import random suiji = random.randint(1,6) # if-elif方法 # if suiji == 1: # print("吃1") # elif suiji == 2: # print("吃2") # elif suiji == 3: # print("吃3") # elif suiji == 4: # print("吃4") # elif suiji == 5: # print("吃5") # elif suiji == 6: # prin...
# 类属性和类方法 class Student: # 类属性 stu_num = 0 __num = 5 def __init__(self,name,age): # 对象属性,实例属性 self.name = name self.age = age # self.__class__获取对象所属的类 self.__class__.stu_num += 1 def __del__(self): self.__class__.stu_num -= 1 # def cha...
# 元组元素赋值给变量,这就是所谓的解包 # t1 = (10,20,30) # t1 = 10,20,30 # 定义了一个(10,20,30) # a,b,c = t1 # a, b = 2, 3 # a, b = b, a # print(a,b,c) # 元组元素多于变量个数 # a, b, *last = 10, 20, 30, 40 # # _变量接受其余所有元素,组成一个列表 # print(a,b,last) # print(type(last)) # a, *_, b = 10, 20, 30, 40 # print(a,_,b) # 列表解包 # a,b = [10...
# 韩信点兵:报数5,余2,报数7,余4,报数10,余7,最少多少人 # count = 0 # while 1: # count += 1 # if count % 5 == 2 and count % 7 == 4 and count % 10 == 7: # print(count) # break # 不定方程求解 # 2x + 3y = 100 # x>=0, y>=0 x = 0 while x <= 50: y = 0 while y < 34: if 2 * x + 3 * y == 100: ...
# str1 = 'a fox jumped over the fence' # count 子串出现的次数 # count(sub, start=0, end=len(str)) # print(str1.count('e',10,16)) # find(sub, start=0, end=len(star)) # 从左向右查找给定子串,如果找到返回子串第一个字符的下标,找不到返回-1 # print(str1.find("fox")) # 2 # print(str1.find('1fox')) # -1 # print(str1.find("fox", 3)) # # rfind str1 = '...
# 用列表生成式完成,l1 = ['Java' , 'C' , 'Swift' , 'Python' , True,12.4],请将l1中字符串全部转换为小写,其他项不动 l1 = ['Java' , 'C' , 'Swift' , 'Python' , True,12.4] l2 = [i.lower() if type(i) == str else i for i in l1 ] print(l2)
class Animal(object): def __init__(self,name,age): self.name = name self.__age = age self._a = 10 # 保护属性直接使用 def eat(self): print("吃") def get_age(self): return self.__age class Dog(Animal): def __init__(self,name,age,kind): # 继承自父类的属性可以调用父类的...
# 深复制和浅复制 import copy # 不可变对象:int float boolean str tuple # 不可变对象不存在深浅复制 # a = 10 # b = a # # copy是浅拷贝 # c = copy.copy(a) # print(id(a),id(b),id(c)) # s1 = "ok" # s2 = copy.copy(s1) # print(id(s1),id(s2)) # 可变对象,list,dict,set 容器 a = [1,[5,6],3] # 浅拷贝 只拷贝容器,不拷贝元素 b = copy.copy(a) # print(id(a),id(b))...
import csv # # 读文件 # with open("csv/bank.csv") as fp: # # 获取csv操作对象 # # 参数:fp 文件指针 # # dalimiter 分隔符,如果是逗号,可以省略 # reader = csv.reader(fp,delimiter=':') # for line in reader: # print([int(x) if x.isdigit() else x for x in line]) # 写csv文件 a = {'a':10,'b':[1,2,3]} # newline 换行符,默...
# 6.给定一个句子(只包含字母和空格),将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。例如: # “hello xiao mi”-> “mi xiao hello” str1 = "hello xiao mi" list1 = str1.split(" ") a = list1[::-1] print(" ".join(a))
# year = int(input("请输入年份:")) # month = int(input("请输入月份:")) # day = int(input("请输入日期:")) # days = 0 # month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # if year > 0 and 0 < month < 13 and 0 < day < 32: # if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: # month_day[1] = 29 # ...
# 读文件 # 1 打开文件 fp = open("f2.txt") # 2 读内容 # data = fp.read() # 读取文件所有内容 # data = fp.read(5) # print(data) # 读取一行 # data = fp.readline() # while 1: # data = fp.readline().strip() # print(data) # if not data: # break # 参数是字符数,如果字符数小于这一行的总字符数,则读入指定字符数,否则读取一行 # data = fp.readlin...
class Girl: def __init__(self,name,age): # 公有属性 self.name = name # 私有属性,不能通过对象.__age调用 self.__age = age # getter方法 def get_age(self): return self.__age # 类内方法里不区分公有和私有 # setter def set_age(self,age): self.__age = age xiaohong = Girl('...
# 传入函数 def add(a,b): return a + b def opperate(a,b,func): """ :param a: 第一个数 :param b: 第二个数 :param func: 运算,需要传入一个函数:传入函数 :return: """ return func(a,b) res = opperate(2,5,add) print(res)
str1 = 'a fox jumped over fox the fence' # split(seperator) 用指定分隔符分割字符串,返回一个列表 # res = str1.split(" ") # s2 = "a1b1c" # print(res, len(res)) # print(s2.split('1')) # list 可以将字符串转成列表 # a = list(str1) # print(a) # partion # res = str1.partition("over") # print(res) # # s2 = """agc # bchg # cih # dbn ...
# try: # fp = open('f2.txt') # fp.write("*********************") # except FileNotFoundError as e: # print(e) # except Exception as e: # print(e) # finally: # print("finally") # fp.close() # 上下文管理 只要文件打开了,系统就一定会关闭它 # with open('f2.txt') as fp: # fp.write("11111") # 上下文管理在类中的实现 ...
# 2. 写函数,传入一个参数n,返回n的阶乘 def jiecheng(n): a = 1 for i in range(1,n+1): a *= i return a res = jiecheng(3) print(res)
#连续求和 def add(num): sum1 = num while True: x = yield sum1 if isinstance(x,str): break sum1 += x t1 = add(2) # 创建协程对象,代码没有执行 next(t1) # next启动代码执行到第一个yield print(t1.send(10))
""" ML Model that plays tic tac toe. """ from copy import deepcopy import random from board import Board class Model: """ ML Model that plays tic tac toe. """ def __init__(self, piece): """ Initialize an unlearned model. Arguments: piece : the model's piece, either an 'X' or an 'O' """ self.piece...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 11 15:35:03 2020 @author: akashkumar """ n = ones_digit = { 0:'', 1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine" } te...
import random print('''********************************************************* Welcome to Aaron's Guessing Game **********************************************************''') best_score = 10 def start_game(): global best_score solution = random.randint(1,10) number_of_trys = 0 while Tru...
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict import pprint def build_graph(n, cities): isolated_cities = set() for i in range(1, n + 1): isolated_cities.add(i) graph = defaultdict(set) for edge in cities: frm, to ...
import os import csv # Specify the file to write to csvpath=os.path.join('..', '..', 'gt-atl-data-pt-06-2020-u-c', 'DataViz-Content', '03-Python', 'Homework', 'Instructions', 'PyPoll', 'Resources', 'election_data.csv') with open(csvpath, 'r') as file: poll = csv.reader(file) next(poll) # intitial val...
# coding: utf-8 # **References** # # https://andhint.github.io/machine-learning/nlp/Feature-Extraction-From-Text/ # # # Tweet Sentiment Classification # ## Objective # Determine whether the sentiment on the Tweets related to a product or company is positive, negative or neutral. # ## Classification Techniques ...
def strEncrypt(first,second,key,result): result = [] for x in range(4): m=(ord(second[x])+ord(key[x]))%26+97 temp = ord(first[x]) ^ m temp=temp%26+97 result += chr(temp) return result def Encrypt(word,key,cipher): #对要加密的内容进行分组,8个字节一组 n = int(len(word) ...
#加密 def encrypt(): word=input("请输入要加密的文字:") first=[] second=[] for x in word: if word.index(x)%2==0: first.append(x) else: second.append(x) print("加密后的文字为:",''.join(first)+''.join(second)) #解密 def decrypt(): word=input("请输入要解密的文字:") l=len...
import numpy as np from layers import * class FullyConnectedNet(object): """ A fully-connected neural network with an arbitrary number of hidden layers, ReLU nonlinearities, and a softmax loss function. This will also implement dropout and batch normalization as options. For a network with L layers, ...
print('Running...') #get data csv_file = 'auto_insurance_sweden.csv' x=[] with open(csv_file, 'r') as f: for row in f: x.append(row.split(',')[0]) x = [float(i) for i in x] y=[] with open(csv_file, 'r') as f: for row in f: y.append(row.split(',')[1]) y = [float(i) for i in y] ################...