text
stringlengths
37
1.41M
import json import urllib url = raw_input('Insert URL: ') f = urllib.urlopen(url) data = f.read() data = json.loads(data) comments = data['comments'] count = 0 for item in comments: count += item['count'] print count
from lab04 import * ## Extra Lists, Dictionaries Questions ## ######### # Lists # ######### # Q12 def merge(lst1, lst2): """Merges two sorted lists. >>> merge([1, 3, 5], [2, 4, 6]) [1, 2, 3, 4, 5, 6] >>> merge([], [2, 4, 6]) [2, 4, 6] >>> merge([1, 2, 3], []) [1, 2, 3] >>> merge([5, ...
def isPhoneNumber(txt) : if len(txt) !=12 : return False for i in range(0,3): if not txt[i].isdecimal() : return False if txt[3]!='-': return False for i in range(4,7): if not txt[i].isdecimal(): return False if txt[7]!='-': return Fals...
def tree_max(t): """Return the max of a tree >>> t = tree(1, ... [tree(3, ... [tree(4), ... tree(5), ... tree(6)]), ... tree(2)]) >>> tree_max(t) 6 >>> s = tree(11, ... [tree(32, ... ...
import csv def f1(predictions, gold): """ Calculates F1 score(a.k.a. DICE) Args: predictions: a list of predicted offsets gold: a list of offsets serving as the ground truth Returns: a float score between 0 and 1 """ if len(gold) == 0: return 1 if ...
import random, string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" password = "" password_size = int(input("Enter the size of you're password : ")) for i in range(password_size): num = random.randint(0, len(characters)-1) password = password + characters[num] print(...
from threading import RLock class PortLock(object): """ A class used to provide separate read and write access in multithread environment. Provides properties readLock and writeLock returning separate RLocks to allow specific access. In addition provides same interface as threading.RLock. Using this inte...
from random import random def word2vec(vecmodel, word): try: return vecmodel[word] except: # if the word is not in the word2vec database ''' words are vectors? nice, so exploit the operations defined on vector spaces: sum of vectors and multipication by a scalar...
__author__ = 'student' from socket import socket import logging def server_port(): return 12345 encoding = 'UTF-8' def binom(n,m): b = 1 for i in range(0,m): b = b * (n-i) // (i+1) return b if __name__ == "__main__": logging.basicConfig(filename='example.log',level=logging.INFO) ...
__author__ = 'student' from socket import socket def server_port(): return 12345 encoding = 'UTF-8' def binom(n,m): b = 1 for i in range(0,m): b = b * (n-i) // (i+1) return b if __name__ == "__main__": # setting up a listener socket sock = socket() # this is how you create a ne...
import random def say(x): n=[] x=x.upper() x=x.lstrip('!') Xplode=False nox=0 reroll=0 thrownout=[] replaced=[] if x.find('D') != -1 and x.find('X') == -1: values=x.split('D') elif x.find('D') != -1 and x.find('X') != -1: x=x.rstrip('X') values=x.split('...
#!/usr/bin/env python3 while True: a = input('Print a:\n') b = input('Print b:\n') try: result = int(a)/int(b) except ValueError: print('Wrong type of variables') except ZeroDivisionError: print('Division by zero is prohibited') else: print(result) brea...
import pygame from random import randrange # pygame initialisation pygame.init() clock = pygame.time.Clock() # create game window, set resolution and window caption resolution = 800 window = pygame.display.set_mode((resolution, resolution)) pygame.display.set_caption("Snake") # game elements variables size = 50 snak...
# db1.py import sqlite3 #연결객체 리턴받기(임시로 메모리 작업) #con = sqlite3.connect(":memory:") #영구적으로 파일에 남기기 con = sqlite3.connect("c:\\work\\sample2.db") #실제 구문을 실행한 커서 객체 cur = con.cursor() #테이블 구조(스키마) 생성 cur.execute("create table PhoneBook (Name text, PhonNumber text);") #1건을 입력 cur.execute("insert into PhoneBook values ('de...
from rdflib import Graph, URIRef from rdflib.namespace import RDF, RDFS, Namespace def question_a(): uni = Namespace("http://www.mydomain.org/uni/") # import rdf from g = Graph() g.parse("2\KRWEB3.rdf") # locate and load Department dep_name = URIRef("http://www.mydomain.org/uni/d...
import numpy as np Forward_Backward = [(1,0),(0,1),(-1,0),(0,-1)] Diagonals = [(1,1),(-1,1),(1,-1),(-1,-1)] class Piece: def __init__(self, x, y): self.x = None self.y = None def Check(x,y): if x >= 0 and x < 8 and y >= 0 and y < 8: return True ...
class Solution: @staticmethod def intersect(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1_map = {} res = [] for ele in nums1: if ele in nums1_map: nums1_map[ele] += 1 ...
class Solution: res = [] used_flag = [] def generatePermutation(self, nums, index, p): if index == len(nums): Solution.res.append(list(p)) return for i in range(len(nums)): if not Solution.used_flag[i]: Solution.used_flag[i] = True...
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # 采用计数排序的思想 count = [0, 0, 0] # 存放0,1,2这三个元素的频率 for ele in nums: assert 0 <= ele <= 2 count[el...
import pandas as pd import numpy as np class A: def __init__(self, n): self.n = n class B(A): def __init__(self, k): self.k = k def printing(self, a): print(self.n) l = B(4) l.printing(3)
import tensorflow as tf # Retrieving MNIST dataset from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) session = tf.InteractiveSession() # Each input has 784 pixels distributed by a 28 width x 28 height matrix # The 'shape' argument defines the te...
from ENCRYPTION import ENCRYPTION for i in range(2): Encrypter = ENCRYPTION() print(Encrypter) raw_msg = input("Enter a message to encrypt: ") encrypted_msg = Encrypter.encrypt(raw_msg) print("Encrypted message: " + encrypted_msg) decrypted_msg = Encrypter.decrypt(encrypted_...
# This A E-Mail Slicer # Taking E-Mail Address From User print("What Is Your E-Mail Address ?") E_mail=input("Enter ").strip() # Distancing User Name From E_Mail user_name=E_mail[:E_mail.index("@")] # Distancing Domain Name From E_Mail domain_name=E_mail[E_mail.index("@")+1:] output = "Your User Name Is " + user_nam...
import heapq class Edge: def __init__(self, dst, weight): self.dst, self.weight = dst, weight def __lt__(self, e): return self.weight > e.weight class Graph: def __init__(self, V): self.V = V self.E = [[] for _ in range(V)] def add_edge(self, src, dst, weight): ...
from copy import deepcopy from functools import reduce class Divisor: def __init__(self, n): """ make divisors list and prime factorization list of n complexity: O(n^(1/2)) used in ProjectEuler No.12, yukicoder No.36 """ assert n >= 1 number = n if n...
def calc_largest_rect_in_hist(heights): heights.append(0) stack = [] left = [0] * len(heights) ans = 0 for i, height in enumerate(heights): while stack and heights[stack[-1]] >= height: idx = stack.pop() ans = max(ans, (i - left[idx] - 1) * heights[idx]) left[...
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 13:36:34 2018 @author: ellie.cai """ #fibonacci solution 1 a=[0,1] for i in range(2,20): a.append(a[i-1]+a[i-2]) print(a) def fab1(n): a=[0,1] for i in range(2,n+1): a.append(a[i-1]+a[i-2]) return a[n] print(fab1(20)) ...
#Sort the list using operator.itemgetter function #mylist = [["john", 1, "a"], ["larry", 0, "b"]]. #Sort the list by second item 1 and 0. from operator import itemgetter mylist = [["john", 1, "a"], ["larry", 0, "b"],["jack", 4, "d"], ["murs", 3, "c"]] print(sorted(mylist, key = itemgetter(1)))
#Python program to find sum of elements in list def sumofelelments(a): sum = 0 for i in a: if type(i) == int: sum = sum + i print(sum) l = [10,30,20,'a',10] sumofelelments(l)
#Write a recursive function to compute x raised to the power of n. def recursiveFunc(x,n): if n!=0: return x*recursiveFunc(x,n-1) else: return 1 while(1): number = int(input('Enter the number ')) exponent = int(input('Enter exponential number ')) result = recursiveFunc(n...
class Fila(object): def __init__(self): self.dados = [] def insere(self, elemento): self.dados.append(elemento) def retira(self): return self.dados.pop(0) def vazia(self): return len(self.dados) == 0 class Pilha(object): def __init__(self): self.dados = []...
class UCType(object): ''' Class that represents a type in the uC language. Types are declared as singleton instances of this type. ''' def __init__(self, typename, binary_ops=set(), unary_ops=set(), rel_ops=set(), assign_ops=set()): ''' You must implement yourself and figure out wh...
import tkinter import inspect import Pieces from Piece import Piece class Board(object): "the chessboard (principal class)" def __init__(self): """super().__init__(win, width = width, height = height) self.width = width self.height = height""" self.clear() """d...
from Conta import Conta class ContaBancaria(Conta): def __init__(self, numero, agencia, saldo, tipoConta): Conta.__init__(self, numero, agencia, saldo, tipoConta) def mostrarSaldo(self): print("Saldo conta bancaria: ", self.saldo) def depositar(self, valor): self.saldo += valor ...
class Empregado: def __init__(self, nome, sobrenome, salarioMensal): self._nome = nome self._sobrenome = sobrenome self._salarioMensal = salarioMensal self.aumentoSalario = 0 @property def nome(self): return self._nome @nome.setter def nome(self, nome): ...
# import random # # print("Who will pay for this meal? ") # names = input("Put all the names seperated by a comma and space: ") # list_names = names.split(", ") # #print(list_names) # number_of_people = len(list_names) - 1 # #print(number_of_people) # random_number = random.randint(0, number_of_people) # # print(f"{lis...
import os from art import auction_logo_hammer continue_bidding = True highest_value = 0 highest_name = '' silent_auction_dict = {} def clear(): return os.system('clear') def find_highest_bidder(dict_auction): for key in silent_auction_dict: if silent_auction_dict[key] >= highest_value: ...
'''A guessing game. Who has the most followers on Social media. The user should guess between two people. If the user guessed correctly, continue game and add to score. If input is wrong, stop game. Show score so far.''' from art import higher_lower_logo, higher_lower_vs from game_data import data import random import...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import linear_model from sklearn.metrics import r2_score if __name__ == '__main__': df = pd.read_csv("../resources/FuelConsumptionCo2.csv") # Lets select some features to explore more. cdf = df[['ENGINESIZE', 'CYLINDERS', ...
from math import sqrt from scipy.stats import kurtosis, skew def average(lst): return sum(lst) / len(lst) def stdDev(lst): sum1 = 0 mean = average(lst) for a in lst: sum1 += (a - mean) * (a - mean) return sqrt(sum1 / len(lst)) def cov(lst1, lst2): sumCov = 0 mean2 = average(lst...
#!/usr/bin/env python from sklearn.cluster import KMeans from sklearn.decomposition import PCA import numpy as np from .._shared.helpers import * def cluster(x, n_clusters=8, ndims=None): """ Aligns a list of arrays This function takes a list of high dimensional arrays and 'hyperaligns' them to a 'co...
from pyspark.sql import SparkSession import pandas as pd spark = SparkSession \ .builder \ .appName("Twitter Data Analysis") \ .getOrCreate() df = spark.read.json("importedtweetsdata.json") df.createOrReplaceTempView("SmartPhones") # 10 states with their Total Tweets Count in the United States...
# -*- coding: utf-8 -*- from sklearn.model_selection import train_test_split import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression df = pd.read_csv("dat.csv") df X= df.X.values.reshape(-1,1) Y = df.Y.values X_train, X_test, Y_train, Y_test = tra...
#Topic:Correlation, Covariance, #----------------------------- #libraries #The difference between variance, covariance, and correlation is: #Variance is a measure of variability from the mean #Covariance is a measure of relationship between the variability of 2 variables - covariance is scale dependent because it is ...
#Topic: Statistics - Covariance #----------------------------- #Covariance provides the a measure of strength of #correlation between two variable or more set of variables. # The covariance matrix element Cij is the covariance of xi and xj. #The element Cii is the variance of xi. #If COV(xi, xj) = 0 then variables a...
# -*- coding: utf-8 -*- # Copyright (c) ©2019, Cardinal Operations and/or its affiliates. All rights reserved. # CARDINAL OPERATIONS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. # @author: songjie@shanshu.ai # @date: 2019/10/28 import re def is_number(str_number: str): """ 判断字符串是否是数字(数字、小数、负...
import random def partition(a, left, right): x = a[left] j = left for i in range(left + 1, right + 1): if a[i] <= x: j += 1 a[i], a[j] = a[j], a[i] a[left], a[j] = a[j], a[left] return j def randomized_quick_sort(a, left, right): if left >= right: retur...
import csv from statistics import mean # ------------------CONSTANTS length = "length" ProdCost = "ProdCost" AlbumSales = "AlbumSales" bandCol = 2 prod_cost_col = 3 album_sales_col = 4 # fileName = 'C:\\Users\\venkat\\Desktop\\ufa\\coursework\\week12\\Albums.csv' # ------------------global variables d = ...
import numpy def arclen(points): """Takes points is a list with vectors of the points in every dimension e.g. [xs, ys, zs]""" p1 = numpy.array([x[:-1] for x in points]) p2 = numpy.array([x[1:] for x in points]) dist = numpy.sqrt(numpy.sum(numpy.power((p2 - p1), 2), axis=0)) arclen = [0] * len(dis...
# Funções de validação de dados from time import sleep import os from .drawMenu import * # Validation lists numbers = ['0','1','2','3','4','5','6','7','8','9'] specialCharacters = ['!','@','#','$','%','&','*','(',')','-','_','+','=',';','.','<','>',':','/','?','~','^',']','[','{','}','´','`','"','|','\\','\'','\"'] ...
class rect: def __init__(self,leng,bre): self.l=leng self.b=bre def area(self): a=(self.l*self.b) return a def perimeter(self): p=2*(self.l+self.b) return p a=int(input("Enter the length of rectangle 1:")) b=int(input("Enter the breadth of rectangle 1:")) c=int(input("Enter the length of rectangle...
n=int(input("Enter the number of imputs:")) l=[] for i in range(0,n): ele=int(input()) l.append(ele) for i in range(0,n): if l[i]>100: l[i]="over" print(l)
s="Melon" t="Water" print("The original strings are:",s,'',t) test=t[:1]+s[1:] temp=s[:1]+t[1:] new= test+' '+temp print("New string is:",new )
from Numberjack import * # N-Queens # The N-Queens problem is the probelm of placing N queens on an N x N chess # board such that no two queens are attacking each other. A queen is attacking # another if it they are on the same row, same column, or same diagonal. def get_model(N): queens = [Variable(N) for i in...
from Numberjack import * # Job Shop Scheduling # Given a set of N job of various sizes, the job shop scheduling problem is to # schedule these on M machies such that the overall makespan is minimized. The # makespan is the total length of the schedule. ############################################### ####### Clas...
from Numberjack import * # Magic Square Water Retention # The goal of the Magic Square Water Retention problem is to retain the maximum # amount of water in a N x N magic square. def model_magic_square(N): sum_val = N * (N * N + 1) / 2 # The magic number square = Matrix(N, N, 1, N * N) water = Matrix(...
import psycopg2 print("\n Ingrese fecha de nacimiento\n") dia=int(input("Día de nacimiento: ")) mes=int(input("Mes de nacimiento: ")) a=int(input("Año de nacimiento: ")) print("\n") if 2021>a>1900: edad=2021-a if 12>=mes>=1: if mes==1 or mes==3 or mes==3 or mes==5 or mes==7 or mes==8 or mes==10 or mes==...
# Para mostrar un texto en la terminal: print("_____________________________________________\n") nom= input("Ingresa tu nombre: ") edad=int(input("Ingresa tu edad: ")) money= float(input("Ingresa la cantidad de dinero que poseés en tu billetera, tranquilo, esto no es un asalto: ")) print(f"\n Que onda {nom}, tenés {e...
# Operadores de asignación """ Primero crear la variable o variables con las que se van a trabajar. a += b, Suma en asignació b -= c, resta en asignación c *= d, multiplicación en asignación d /= e, divisi0243n en asignación e **= f, potencia en asignación f %= g, módulo en asignación "...
class Node: def __init__(self, item): self.item = item self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def insert(self, item): # Insert into linked list without sorting (Each new element at end): # new_node = Node(item) # if self.head is None: ...
# Code adapted from Corey Shafer # Keep track of how many times a function was called # Decorators most often used in logging # Decorators are used a lot for working with third class libraries, routing # Most confusing thing is keep track of all wrappers and whatnot import time from functools import wraps def my_logg...
""" Methods - function that is associated with a class, rather than fxns Object is an instance of a class Classes are blueprints for objects to use Tutorial adapted from: Corey Schafer """ import datetime class Employee: # Class variables are shared among all instances raise_amount = 1.04 num_of_emps = 0 def __in...
board=[' ' for i in range(10)] #Board is a list to hols the position from 1 to 9 #i.e all the positions in the board #We are usinf 10 indices and avoiding the 0th index to identify the #positions easily , also used to empty th...
#!/usr/bin/env python s = raw_input() i = 0 while i < len(s) and (s[i] < "0" or "9" < s[i]): i = i + 1 j = i while j < len(s) and ("0" <= s[i] and s[i] <= "9"): j = j + 1 if i < len(s): print s[i], i
#!/usr/bin/env python i = 0 while i < len(a) - 1 and a[i][:len(s)] != s: i += 1 if i < len(a) - 1: print a[i]
#!/usr/bin/env python n = input() a = '*' + (n * '*') + '*' b = '*' + ((n / 2) * ' ') + '*' + ((n / 2) * ' ') + '*' + '\n' p = (n / 2) * b print a print (n / 2) * b print a print (n / 2) * b - 1 print b print a
#!/usr/bin/env python import sys hv = sys.argv[1] s = raw_input() a = [] start = 0 end = 0 i = 0 while i < len(s): end = start + 1 while end < len(s) and s[end] != ',': end += 1 if start < len(s): a.append(s[start:end]) start = end + 1 i += 1 i = 0 while i < len(hv) and hv[i] != '=': i += 1 h = hv[:i] v = h...
#!/usr/bin/env python import sys n = 20 corner_x = int(sys.argv[1]) corner_y = int(sys.argv[2]) size = int(sys.argv[3]) plot = {} i = 0 while i < size: #Bottom side key1 = str(corner_x + i) + "-" + str(corner_y) plot[key1] = True #Top side key2 = str(corner_x + i) + "-" + str(corner_y + (size - 1)) ...
import math def area(a,b,c): s=(a+b+c)/2 return math.sqrt(s*(s-a)*(s-b)*(s-c)) def is_heronian(a,b,c): if a != int(a): return False if b != int(b): return False if c != int(c): return False if area(a,b,c) != int(area(a,b,c)): return False else:...
st = 'ACGT‘ len(st) # getting the length of a string import random random.choice('ACGT') # generating a random nucleotide # now I'll make a random nucleotide string by concatenating random nucleotides st = ''.join([random.choice('ACGT') for _ in xrange(40)]) st st[1:3] # substring, starting at position 1 and extendi...
import csv person_tag = lambda fullname: fullname.split()[0].lower() movie_tag = lambda title: "".join(title.split()).lower() def movie_formatter(row): title = row[0] return f'CREATE ({movie_tag(title)}:Movie {{title: "{title}"}})' def person_formatter(row): fullname = row[0] return f'CREATE ({pers...
# most code gathered from https://wiki.python.org/moin/SimplePrograms import random import re from time import localtime from math import sqrt, exp class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance ...
input_file_names = ["a_example.txt", "b_read_on.txt", "c_incunabula.txt", "d_tough_choices.txt", "e_so_many_books.txt", "f_libraries_of_the_world.txt"] #for file_selector in range(0, 6): for file_selector in range(len(input_file_names)): #reading input file f_in = open(input_file_names[file_selector], "r"...
import unittest from search import TypeAheadRadixTrie class TestRadixTrie(unittest.TestCase): def setUp(self): self.trie = TypeAheadRadixTrie() self.ids = ('u1', 't1') def test_contains(self): """Stored words are `in` the Trie.""" self.trie.add('car', self.ids[0]) self...
###################################################### ## THIS FILE CONTAINS FUNCTION THAT ## ## CALCULATES STREAMING MEDIAN ## ###################################################### # MAX/MIN HEAP ALGO def MaxMin_Heap_ALGO(max_heap, min_heap, num): # step 1: add next item to on...
''' collections namedtuple ''' from collections import namedtuple Subscriber = namedtuple('Subscriber', ['addr', 'joined']) sub = Subscriber('rulaimiao@163.com', '2018-01-09') print(type(sub)) print(sub.addr) print(sub.joined) class Example(): def __init__(self, addr): self.addr = addr example1 ...
def dedupe(items): seen = set() for item in items: if item not in seen: yield item seen.add(item) for i in dedupe([1,2,3,1,2,1,3,45,6,61,23,2,5,]): print(i) # key 可以威一个方法,可以制定前面items中的重复策略, # 当item为一个对象,或者一个字典的时候, # 可以指定一个lamda来操作去重策略,并保持去重后数据的排序的稳定 def dedupe(items, key=...
import numpy as np import matplotlib.pyplot as plt class Beetle(object): def __init__(self, beetlename, betak=3.0, betatheta=1, alphak=0.0001, alphatheta=1, container=0): self.beetlename = beetlename self.sex = np.random.binomial(1,femalefreq) #0=male, 1=female self.container = container ...
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. T...
uah = int(input('Enter the amount of hryvnia (uah): ')) rate_usd = float(input('Enter the current dollar (usd) rate: ')) if rate_usd > 0: usd = uah / rate_usd print(round(usd, 2), 'dollars at the rate of', rate_usd, 'can be bought for', uah, 'hryvnas') else: print(rate_usd, 'Not valid usd rate')
my_list = ['Red', 'Green', 'Blue', 'Black'] my_reverse_list = [] for i in my_list: my_reverse_list.append(i[::-1]) print(my_reverse_list)
#Какое самое маленькое число делится нацело на все числа от 1 до 20? x = 1 status = True while status: z = [] z = [i for i in range(1, 21) if x%i == 0] if len(z) == 20: print(x) status = False x+=1
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] l = [] for i in a: if i <= 5: l.append(i) print(l) print([elem for elem in a if elem <= 5])
""" Daily alarm Format used: H:M e.g. 10:12 24H format """ from datetime import datetime import re def return_time(): date_and_time = datetime.now().strftime('%H:%M') return date_and_time def start_clock(): i = 1 wake_up_time = raw_input("Enter time format \"H:M\": ") if not (re...
""" variable length arguments An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. """ def printinfo(arg1, *varargs): print arg1 for var in varargs: ...
import unittest from user import User class TestUser(unittest.TestCase): """ Test class that defines test cases for the user class behaviours. Args: unittest.TestCase: TestCase class that helps in creating test cases """ def setUp(self): """ set_up method to run before each test case """ ...
""" Before any of the great ML and AI tools can be used, you must first have complete command and control of the data you are expecting to derive information from. As the adage goes "Garbage in, garbage out", so the first step in learning how to truly utilize all the advances in computing and AI, is learning how to t...
# return the second to last element in a list def secondLastElement(list): # if there are not enough elements, then there is no second to last index if (len(list) < 2): return None # return the second to last value return list[len(list) - 2] # tester code a = [] assert(secondLastElement(a) == N...
''' 为了解决内存突然增大问题,python引入了生成器 通过在函数中使用yield关键字 特性: - 可以使用next获取数据,一次一个,结束时会报错 - 只能遍历一遍 - 可以转换为列表 - 可以使用for-in遍历 ''' l = [i for i in range(10)] #列表生成式 l2 = (i for i in range(1,1000000)) #生成器 print(type(l)) print(type(l2)) #通过next获取 print(next(l2)) print(next(l2)) #使用 for in 遍历 for j in l2: pass print('-------...
# This code helps users visualize proof-of-work # algorithm difficulty levels using LEDs # # Author: Josh McIntyre # from adafruit_circuitplayground.express import cpx import time import random # This class defines functions for visualizing # proof-of-work algorithms and how the difficulty # effects the amount of time...
# def tenodd(): nnum = [0,0,0,0,0,0,0,0,0,0] for i in range(10): nnum[i] = input('Enter integer ' + str(i+1) + ': ') alls = sorted(nnum, reverse=True) for i in range(10): isodd = int(alls[i]) if isodd % 2 != 0: show = 'largest odd is ' + str(isodd...
# Finds the first factorial(n) that has 1000 digits. strlen = 0 now = 1 last = 1 iterator = 2 while strlen < 1000: now += last last = now - last iterator += 1 strlen = len(str(now)) print "%d is %d long." % (iterator, strlen)
# Steps are an index value, so start at one or increment returned value def step(at, steps): # print "%d on hop %d" % (at, steps) while not at == 1: if at % 2 == 0: at, steps = step(at / 2, steps + 1) else: at, steps = step(((at * 3) + 1), steps + 1) break r...
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data ###---关闭警告---### import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' ###---关闭警告---### mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.placeholder("float", [None, 784]) W = tf.Variable(tf.zeros([...
import numpy as np from testCases_v3 import linear_activation_backward_test_case from myhomework_PART1_period_6_1 import linear_backward from dnn_utils_v2 import relu_backward,sigmoid_backward def linear_activation_backward(dA, cache, activation): """ Implement the backward propagation for the LINEAR->ACTIVATI...
# To work on the advanced problems, set to True ADVANCED = True def count_unique(input_string): """Count unique words in a string. This function should take a single string and return a dictionary that has all of the distinct words as keys, and the number of times that word appears in the string as values. Fo...
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text c...
import random # 2 # names = ('Kathy', 'Benji', 'Ian', 'Alejandro') # # for n in names: # print(n, ':', len(n), 'letters') # 3 Random names first_names = ('Frances', 'Perry', 'Kerry', 'Omar', 'Carmen', 'Sonia', 'Eloise', 'Trevor', 'Ricardo', 'Tyler') last_names = ('Doyle', 'Floyd', 'Reid', 'Webb', ...
import random wordlist = ('happy',) word = random.choice(wordlist) correct_guesses = () # empty tuple to hold correct guesses num_turns = 0 all_letters = () # empty tuple to hold guesses print(word) for letter in word: print("_", end=' ') print() player_letter = input("\nGuess a letter") player_letter = pla...
import random lightbright = ['.', '.', '.', '.', '.', '.', '.', '.', '.','.'] # one row board = [] # full board (it starts empty) # add 10 lightbright rows for x in range(10): board.append(lightbright.copy()) # make a copy (don't just use same row over and over) # print board nicely for row in board: for ...