text
stringlengths
37
1.41M
import pymysql from pymysql.cursors import DictCursor # 导入DictCursor类 def select_id(): mysqlcon = pymysql.connect(host='172.16.102.150', user='aironm', password='aironm', database='school', cursorclass=DictCursor) try: # pymsysql.connect的__enter__方法返回的就是cursor; # 问题:如果不想使用默认的Cursor类,则必须再connec...
# 问题:给函数参数增加元信息 # 解决:使用参数注解 # Python解释器不会对这些注解添加任何的语义;它们不会被类型检查,运行时跟没有加注解之前的效果也没有任何差距 def add(x:int, y:int) -> int: return x + y print(help(add)) # 函数注解存储在函数的__annotations__属性中 print(add.__annotations__)
from data_structures.linkedlists.node import Node class Queue(): def __init__(self): self.head = None self.tail = None self.size = 0 def enqueue(self, value): node = Node(value) if self.is_empty(): self.head = self.tail = node else: se...
n = int(input()) a = n cycle_length = 0 while a != n or cycle_length == 0: units = a % 10 ten = a // 10 value = (units + ten) % 10 a = units * 10 + value cycle_length += 1 print(cycle_length)
n = int(input()) low = 1 high = n while 1: mid = (low + high) // 2 if mid ** 2 == n: print(mid) break elif mid ** 2 > n: high = mid - 1 elif mid ** 2 < n: low = mid + 1 ''' import math print(f"{int(math.sqrt(int(input())))}") '''
# Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). # Example # to_camel_case("the-stealth-warrior") # r...
import numpy as np import matplotlib.pyplot as plt def plotDecisionBoundary(X, y, predictor, nPoints=100): ''' Takes in a set of 2-d observations X with labels y, and an instance machine learning algorithm class that has a predict() method. Creates a grid of points and uses the given m...
# write your code here def fill_table_from_input(table_state): table = [] k = 0 for i in range(3): table.append([]) for j in range(3): if table_state[k + j] == '_': table[i].append(' ') else: table[i].append(table_state[k + j]) ...
""" Curses-based User Interface for CursMon. """ import curses WHITE = 1 RED = 2 BLUE = 3 YELLOW = 4 CYAN = 5 GREEN = 6 MAGENTA = 7 class UI(object): """ The Curses-based User Interface class. """ def __init__(self, scr): self.lines = curses.LINES self.cols = curses.COLS sel...
import matplotlib.pyplot as plt import random months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] averageMoney = [] explode = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(12): averageMoney.append(random.randint(1, 101)) pr...
from random import randint MyList = list() i = 0 while i < 50: Number = randint(1, 10) print(Number) MyList.append(Number) #add an item to the end of a list i += 1 print(MyList) MyList.remove(3) # remove item from list print(MyList) MyList.sort() # sort list accending print(MyList) print(min(MyLis...
def DNA_string(dna): """ Takes in a DNA string and returns its complementary value """ DNA = list(dna) complementaryStrandList = [] for char in DNA: if char == 'A': complementaryStrandList.append('T') elif char == 'T': complementaryStrandList.append('A') e...
from sympy import * #Question1 #part A #f(x)={3 0<=x<=1} #f(x)={4 1<x<=3} #f(x)={5 3<x<=10} def f(a): if(0<=a<=1): return 3 elif(1<a<=3): return 4 elif(3<a<=10): return 5 #solution #As f(x) is mixture of constant functions it will be continuous at every point except poi...
price = int(input("Please enter price of goods : ")) pay = int(input("Please enter money to pay : ")) exchange = pay - price #คำนวนเงินทอน #array เก็บชนิดของเงินทอน แบ่งเป็น 500,100,50,20,10,5,2,1 money_type = [500, 100, 50, 20, 10, 5, 2, 1] #ลูบ หาเงินทอนโดยการหารเอาเศษ โดยไปลูปใน array ว่า #ถ้าต้องทอนเงิน 768 บาท...
""" row_data = int(input("pls enter row:")) print(str(row_data)) for row in range(row_data): for star in range(row+1): print('*', end = " ") print() from matplotlib import pyplot as plt plt.bar([1,3,5,7,9],[6,3,4,8,2],label = "One") plt.bar([2,4,6,8,10],[3,1,2,4,1],label = "Two") plt.title("data...
romans = [ ["I", 1], ["IV", 4], ["V", 5], ["IX", 9], ["X", 10], ["XL", 40], ["L", 50], ["XC", 90], ["C", 100], ["CD", 400], ["D", 500], ["CM", 900], ["M", 1000], ] def number_to_roman(n): # change integer to roman result = '' i = len(romans) - 1 whil...
# 5. Запросите у пользователя значения выручки и издержек фирмы. # Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). # Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение пр...
import time, os, datetime # Could be irrelevant def get_leap_years(starting_year): current_year = time.gmtime(time.time()).tm_year total = 0 for i in range(starting_year, current_year+1): if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0): total += 1 return total # Calculates time passed since given r...
s = 's = %r;print(s%%s)';print(s%s) # I, did not think semicolons were allowed in python. # also %r is useful for printing with the quotation marks # %% means after substitution you get a single %
#!/usr/bin/env python # coding: utf-8 # # 1. 로또 추첨기 # In[53]: import random r = random.sample(range(1,46),6) print(sorted(r)) # # 2. 구구단 # - 3단, 6단 제외한 구구단 # - 반복문, 조건문사용 # - 문자열 포맷팅을 활용해 2 X 2 = 4 형식으로 출력 # # In[58]: count = 2 for j in range(0,8): if(count != 3 and count != 6): ...
#CTI-110 # P3HW1 - Color Mixer # Freddy Ojeda # June 26 2019 # Prompt the user to enter the first name of the first primary color # Prompt the user to enter the second name of the second primary color # Assign the codes of each name of colors # red equals red, blue equals blue, yellow equals yellow # Using B...
from random import randrange import random print( ''' ____ _______ _______ _ ______ _____ _ _ _____ _____ _____ | _ \ /\|__ __|__ __| | | ____|/ ____| | | |_ _| __ \ / ____| | |_) | / \ | | | | | | | |__ | (___ | |__| | | | | |__) | (___ | _ < / /\ \ | | | | | | ...
import sys class PVPC(object): def __init__(self, day, hour, pcb, cym): """ Initialize a PVPC object. Parameters: day - str - The day of the PVPC [DD/MM/YYYY] hour - str - The hour of this item [HH:MM] pcb - float - The €/kWh of the default fare Peninsula, Canarias, Balear...
# Construct Binary Tree from Inorder and Postorder Traversal ''' preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Output: 3 / \ 9 20 / \ 15 7 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.ri...
# The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. # Find the sum of the only eleven primes that are both truncatable fro...
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? primes = [2, 3, 5, 7, 11, 13, 17, 19] num = 1 for i in primes: p = i while p * i < 20: ...
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? primes = [2, 3, 5, 7, 11, 13] p = 14 while len(primes) != 10001: f = 1 j = 0 n = len(primes) while (j < n) * f: if p % primes[j] == 0: ...
# Take the number 192 and multiply it by each of 1, 2, and 3: # 192 × 1 = 192 # 192 × 2 = 384 # 192 × 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) # The same can be achieved by starting with 9 and multiply...
# Structure this script entirely on your own. # See Chapter 8: Strings Exercise 12 for guidance # Please do provide function calls that test/demonstrate your function # import here import string # body here def shift_letter(letter, shift): inAlphabet = 26 if letter.isupper(): start = ord('A') # Rank starts at ...
class Node: def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def get_length(self): length = 0 # We don't want to change head, so we take a ptr # variable to point to same location as he...
class Node: def __init__(self, key, data=""): self.key = key self.data = data self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, key, data=""): node = Node(key, data) if not self.root: ...
from tkinter import * from PIL import ImageTk,Image root = Tk() root.iconbitmap("D:/Icon Photo/Itzikgur-My-Seven-Pictures-Canon.ico") root.geometry("400x400") my_image = ImageTk.PhotoImage(Image.open("D:/Icon Photo/download (2).png")) my_image1 = ImageTk.PhotoImage(Image.open("D:/Icon Photo/download2.jfif")) def n...
from typing import List, Dict, Tuple class Example(object): def __init__(self, label: int, weight: int): self.weight = weight self.label = label self.features = [] class SentimentExample(Example): def __init__(self, words: Dict[str, int], label: int, weight: int = 1): ...
import roman from datetime import datetime def get_base_filename(experiment_info): """ get_dat_filename: converts string in dd-mm-yy format with the month stored as roman numerals into yy_mm_dd format with all integer values """ date_raw = experiment_info['Recording Date'].values[0] # conver...
# Loop over keys # user = { # 'fname': 'Foo', # 'lname': 'Bar', # } # # for k in user.keys(): # print(k) # # # lname # # fname # # for k in user.keys(): # print("{} -> {}".format(k, user[k])) # # # lname -> Bar # # fname -> Foo ########################## # Loop using items people = { "foo" ...
# Write a script that will ask for the sides of a rectangular and print out the area. # Provide error messages if either of the sides is negative. # 编写脚本,询问矩形的边并打印出该区域。 如果任何一方为负,则提供错误消息。 def print_rectangular(x, y): for i in range(x): print("+", end=" ") print() width = y - 2 lenth = x - 2 ...
# create the grid of points # for i in range(30,0, -1): # print("P{} = (10, 10)".format(i)) # create a number to count every element # for i in range(1,31): # print("F{} = 0".format(i)) # print("SP{} = 0".format(i)) # print("H{} = 0".format(i)) # print("PS{} = 0".format(i)) # print("S{} = 0"....
# -*- coding: utf-8 -*- """ Created on Wed Mar 18 09:43:50 2020 @author: 10139 """ #Input a list of 10 values gene_lengths=[int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input())] #Sort values gene_lengths.sort() print ('The list of sorted val...
lt# -*- coding: utf-8 -*- """ Created on Wed May 13 08:46:13 2020 @author: 10139 """ # Import some necessary libraries import numpy as np import matplotlib.pyplot as plt from matplotlib import cm def vaccination(r): N = 10000 # The variable N holds the total number of people in the population. IP = 1 # The v...
#!/usr/bin/env python2.7 import psycopg2 def popular_articles(): ''' Prints the titles of the top 3 articles that have been viewed the most and how many views they each had. ''' db = psycopg2.connect("dbname=news") cursor = db.cursor() cursor.execute(''' select title, count(*) as num from...
#def findFactors(n, factors): # for f in xrange(2, n+1): # if isPrime(f) and n % f == 0: # factors.append(f) # return findFactors((n/f), factors) # return factors def isPrime(n): for i in xrange(2, ((n+1)/2)+1): if n%i == 0: return False else: ret...
menor = 0 maior = 0 a = int(input("Informe o primeiro numero: ")) menor = a maior = a b = int(input("Informe o segundo numero: ")) if b < menor: menor = b if b > maior: maior = b c = int(input("Informe o terceiro numero: ")) if c < menor: menor = c if c > maior: maior = c print("\nMaior: ", maior) p...
#Exemplo 7: print("Exercicio 7 (inicio, parada, passo):") for item in range(9, -1, -1): print(item)
a = 0 b = 0 c = 0 while a<=0: a = int(input("Informe o valor do lado A: ")) if a<=0: print("A medida de um lado não pode ser menor ou igual a zero!\n") while b<=0: b = int(input("Informe o valor do lado B: ")) if b<=0: print("A medida de um lado não pode ser menor ou igual a zero!\n") ...
def CreateElementaryRuleSet(Num = 110): """ Creates a two-state cellular automata based on an input number between 0 and 255. Numbers such as 30,110,126,150 and 182 produce intresting automata. """ Num = Num % 256 class ElementaryRuleSet: RuleTable = None """ Table of...
# Charles Buyas cjb8qf output = "" total = 0 count = 0 name = input("Please enter a name, -1 to exit the loop: ") # priming input while name != "-1": # -1 is sentinel value (can be anything) try: score = int(input("Please enter " + name + "'s score between 0 and 10...
# Charles Buyas cjb8qf # I conferred with Jason Lin when I got stuck trying to figure out how to include " ", "!", and other # punctuation without changing to another character. He gave me the idea of trying out a range function line = input("Enter your cipher text: ") line = line.lower() caesar_list = list(line) cip...
#!/usr/bin/env python ''' https://leetcode-cn.com/problems/maximum-subarray/ 53. 最大子序和 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 ''' def subMaxArray(nums): temp = max_ = nums[0] for i in...
""" >>> quick_sort([]) [] >>> quick_sort([1]) [1] >>> quick_sort([2, 1]) [1, 2] >>> quick_sort([3, 5, 4, 1, 2]) [1, 2, 3, 4, 5] """ from typing import List def quick_sort(nums: List[int]) -> List[int]: def _quick_sort(nums, low, high): if low >= high: return p = _partition(nums, low, ...
from collections import defaultdict as dd class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: word_len = len(beginWord) if not endWord in wordList or not wordList or not beginWord: return 0 queue = [] queue.append((beginWord,1...
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- import requests import sys demande = 'LIST' while demande == 'LIST': req = requests.get('https://www.cryptocompare.com/api/data/coinlist/').json() print('La liste des crypto est dispo en tappant LIST') print('La valeur d une crypto est dispo en tappant son nom (se...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Anthony Long" """assertlib is a library of standalone assertion methods. Examples: >>> import assertlib >>> assertlib.assertEither("a", "y", "a") """ import itertools from types import StringType def assertEqual(x, y): """Asserts that an objec...
#!/usr/bin/python # python spec/11_sieve_of_eratosthenes/theory/factorization_test.py def arrayF(n): F = [0] * (n + 1) i = 2 while (i * i <= n): if (F[i] == 0): k = i * i while (k <= n): if (F[k] == 0): F[k] = i k += i ...
from pulp import LpVariable, LpStatus, LpProblem, LpMaximize, value if __name__ == "main": """exemple number1""" #create the decision variables x1 = LpVariable('x1', lowBound=0, cat='Continous') x2 = LpVariable('x2', lowBound=0, cat='Continous') x3 = LpVariable('x3', lowBound=0, cat='Continous') #create the pr...
def read_line_by_line(): # read the alice file line by line f = open('alice.txt', 'r') #print(f.read) for line in f: ## iterates over the lines of the file print(line, end = '') ## trailing , so print does not add an end-of-line char ## since 'line' already includes th...
import items import walls import enemy from random import randint class MapTile: description = "Do not create raw MapTiles! Create a subclass instead!" walls = [] enemy = [] items = [] def __init__(self, x=0, y=0, walls = [], items = [], enemy = []): self.x = x self.y = y for walls in walls: self.add_...
from Tetris import Tetris import screen import pygame pygame.init() game = Tetris() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False move = 'D' if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: ...
print ('Balanço de despesas domésticas') print() gasto1 = float(input('Quanto você gastou Diógenes? ')) gasto2 = float(input('Quanto você gastou Gracinha? ')) total = gasto1 + gasto2 print ('Total de gastos foi = R$ %.2f' % total) media = total/2 print ('Gastos por pessoa foi = R$ %.2f' % media) if gasto1 < media: ...
def isValid(s): result = False if len(s) == 0 or s[0] == "": result = True return result if s.count("(") == s.count(")") and s.count("[") == s.count("]") and s.count("{") == s.count("}"): for i in range(0, len(s)): if s[i] == "(": for i2 in ran...
class TreeNode: def __init__(self,val): self.val = val self.left = None self.right = None def zigzag(A): res = [] pre = [A] next_lev = [] itr = 0 t = [] while pre: for i in range(len(pre)): t.append(pre[i].val) if pre[i].left is not No...
## The below code takes input as string of small brackets. ## and returns the number of brackets to add to make it correctly matched. ## ## Input: ## ## "()))(" ## ## Output: ## ## 3 def bracketMatch(A): st = 0 end = 0 for a in A: if a == '(': st +=1 elif a == ')' and st ==0: ...
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def construct(A,B): if not B: return None root_pos = B.index(A[0]) new_Node = TreeNode(A[0]) new_Node.left = construct(A[1:root_pos+1],B[:root_pos]) new_Node.right = constr...
# The Below code calculates the length of the longest Palindrome string in a given STring # # Input: # # 'forpracticeecitcarpfor' # # Output: # # 16 # Because the size of the longest palindrome string 'practiceecitcarp' is 16. def longestPalindrome(A): maxlength = 1 low = 0 high = 0 l = len(A) ...
## The below code reverses the order of the words in the array. ## ## Input: ## ## ['p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't'] ## ## Output: ## ## ['p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'r', 'a', 'c', 't', 'i', 'c', ...
## Given an array of integers arr where each element is at most k places ## away from its sorted position, the below code sorts the given array. ## ## Input: ## ## [1,4,3,2,5,7,6,10,8,9], 2 ## ## Output: ## ## [1, 2, 3, 4, 5, 6, 7, 8, 9] def sort_k_messed_array(arr, k): for i in range(len(arr)): start =...
num = int(input('Digite um número: ')) print(f'O antecessor de {num} é {num - 1} e o sucessor é {num + 1}.')
soma = 0 cont = 0 for c in range(1, 501, 2): if c % 3 == 0: cont += 1 soma += c print(f'A soma dos {cont} números ímpares que são múltiplos de três entre 1 e 500 é: {soma}')
print('10 termos de uma PA') print('*-*' * 7) termo = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) dec = termo + (10 - 1) * razao for c in range(termo, dec + razao, razao): print(f'{c}', end=' -> ') print('FIM')
n1 = float(input('Informe a primeira nota: ')) n2 = float(input('Informe a segunda nota: ')) media = (n1 + n2) / 2 if media >= 7: print(f'Média: {media:.1f}. Aluno APROVADO!') elif 5 <= media < 7: print(f'Média: {media:.1f}. Aluno de RECUPERAÇÃO.') elif media < 5: print(f'Média: {media:.1f}. Aluno REPROVAD...
from random import choice aluno1 = str(input('Informe o primeiro aluno: ')) aluno2 = str(input('Informe o segundo aluno: ')) aluno3 = str(input('Informe o terceiro aluno: ')) aluno4 = str(input('Informe o quarto aluno: ')) lista = [aluno1, aluno2, aluno3, aluno4] sorteado = choice(lista) print(f'O aluno sorteado foi: ...
# -*- coding: utf-8 -*- """ A Ng Machine Learning Week3 exercise. Run logistic regression with regularization. Created on Sat Sep 26 15:13:12 2020 @author: yooji """ import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fmin_bfgs from sklearn.linear_model import LogisticRegression import util ...
# -*- coding: utf-8 -*- """ A Ng Machine Learning Week4 exercise. Use logistic regression to classify MNIST. Created on Sat Sep 26 12:20:13 2020 @author: yooji """ import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from myLogReg import onevsAll, predictOnevsAll, displayData from sklearn.l...
"""Sum of digits""" number=int(input("Enter number?")) sum_of_digits=0 while(number!=0): digit=number%10 sum_of_digits+=digit number=number//10 print("Sum ",sum_of_digits)
"""Package arithmetic function""" from Arithmetics import * i=0 while i!=6: print("\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Remainder\n6.Exit") i=int(input("Enter Option")) num1=int(input("Enter number1?")) num2=int(input("Enter number2?")) if i==1: print(add(num1,num2)) if i==2: print(s...
def main(): word_storage = [] content_list = [] print("Enter rows of text for word counting. Empty row to quit.") while True: black_word = input("") if black_word == "": break word_storage.append(black_word) content = " ".join(word for word in word_storage)....
def encrypt(alphabet): REGULAR_CHARS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] ENCRYPTED_CHARS = ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", ...
# Introduction to Programming # Named parameters # Default value of function arguments will be used if some of arguments is not appear in the function call def print_box(width, height, border_mark="#", inner_mark=" "): for i in range(height): if i==0 or i==height-1: print(width*border_mark) else: ...
def read_message(prompt): result = [] result.append(input(prompt)) return result def main(): print("Enter text rows to the message. Quit by entering an empty row.") #in_string = "" while True: result = read_message("") if result[len(result)-1] == "": break pri...
# Johdatus ohjelmointiin # Area from math import sqrt def area(s1, s2, s3): s_half = (s1 + s2 + s3) / 2 area_tri = sqrt(s_half * (s_half - s1) * (s_half - s2) * (s_half - s3)) return area_tri def main(): rivi1 = float(input("Enter the length of the first side: ")) rivi2 = float(input("Enter the le...
# Intro to programming # Polynome # Phan Viet Anh # 256296 class Operand: def __init__(self, number, co_efficent): self.__number = number self.__co_efficent = co_efficent def get_number(self): return self.__number def get_coefficent(self): return self.__co_efficent ...
def are_all_members_same(my_list): index = 0 T=True while index < len(my_list): if my_list[index] == my_list[index - 1]: T=True else: T= False break index += 1 # if index>=len(my_list): break return T def main(): print(are_all_mem...
num_in = int(input("Choose a number: ")) i = 1 while 1: print(i, "*", num_in, "= ", num_in * i) i += 1 if num_in * i > 100: print(i, "*", num_in, "= ", num_in * i) break
import time start_time = time.time() curr_time = start_time count = 0 while curr_time - start_time < 1: curr_time = time.time() count += 1 print(count) time1 = time.time() for _ in range(count): time2 = time.time() print(time2 - time1) if time2 - time1 < 1: print('for is faster') else: print('...
#!/usr/bin/python # coding=utf-8 """ ######################################################################################### > File Name: recursive.py > Author: Ywl > Descripsion: > Created Time: Tue 24 Apr 2018 01:45:22 AM PDT > Modify Time: #################################...
#!/usr/bin/python # coding=utf-8 #循环:while()用于条件语句循环执行某条语句,for常用于序列化变量的编列 lists1 = [10, 20, 30, 40] event = [] print "while循环" while len(lists1) > 0: #注意出栈入栈顺序 list1 = lists1.pop() event.append(list1) print event lists2 = [10, 30, 50, 70] print "for 遍历" for index in lists2: print index i = 2 whil...
""" ================================ Gaussian Mixture Model Selection ================================ Source: http://docs.w3cub.com/scikit_learn/auto_examples/mixture/plot_gmm_selection/ with appropriate modifications by Dario H. Romero - Dataset from Kaggle This example shows that model selection ca...
# Classification template # use tf.data-preprocessing-template to adjust parameters # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') # get only age and EstimatedSalary X = dataset.iloc[:, [2, 3]].v...
user_number = input('Please enter some number: ') user_number_len = len(user_number) if int(user_number) % 2 == 0: print('number is even') else: print('Number is odd') print(int(user_number) ** 2) if user_number_len == 1: print('There is ' + str(user_number_len) + ' digits in number ' + user_number) elif u...
""" =================== TASK 2 ==================== * Name: Roll The Dice * * Write a script that will simulate rolling the * dice. The script should fetch the number of times * the dice should be "rolled" as user input. * At the end, the script should print how many times * each number appeared (1 - 6). * * Note: ...
class Parent1 (): clas_var = 10 def __init__(self): print ("Inside Parent_one Init Method") def add(self , a ,b): print ("Inside Parent_one Add Method") return a+b def mul(self , a ,b,c): print ("Inside Parent_one mul Method") return a*b*c def common(self):...
# Split camel case letters into invidual letters # Python3 program Split camel case # string to individual strings def camel_case_split(str): words = [[str[0]]] print ('Words are ',words) for c in str[1:]: if words[-1][-1].islower() and c.isupper(): words.append(list(c)) ...
""" Python Scope follows LEGB Rule: 1. Locals 2. Enclosing Function Locals 3. Global 4. Built In """ name = "This is Global Name" def greet(): name = "New Name" def hello(): print ("Hello "+name) #Local Name hello() greet() print(name)#Global Name #-------------------...
#Strings are creed by using quotes str_1 = "double quoted" str_2= 'single quoted' print (str_1,str_2) why_1 = 'to use double quote in the string "Hello" then use single quote for string representation ' why_2 = "to use single quote inside the string say reddem's use double quotes in string declaration" print (why_1) p...
""" Say suppose we have a Car class and we need to replace speed with string variable after instance created It is possible to overide So when we give our data to others --then encapulation plays a big role Q. How to make attribute Private in you class? We can use double underscore before an attribute, then it becom...
#------------------------------------------------------------------------------------------ """ NameSpaces are collection of names, It is a mapping of every name with an object. 1.Built in Name space -available before we start a program.Ex :id(),print(),type() ...etc 2.Global Name Space - Every module can crea...
# -*- coding: utf-8 -*- """ Created on Mon Jun 24 02:27:22 2019 @author: Sanvi """ a=10 print(bin(a)) print(oct(a)) print(hex(a)) c= 0b01010 print(type(c)) print(c)#still it prints a decimal number to user """ 0b -binary 0o -octal 0x -Hex decimal """
#----------------------------------------------------------------------------------------- # Your previous Plain Text content is preserved below: # # Belzabar is 18 years old. On this occasion, we formulated the Belzabar Number. A positive integer is a Belzabar number if it can be represented either as (n (n + 18)) ...
#---------------------------------------------------------------------------------- """" This File explains about input an doutput patterns Input : 1. To read the data from user , we are using input function 2. By default it is a string data To allow flexibility we might want to take the input from the user...
import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape ...
from scipy.stats import norm import time, numpy as np import statistics import matplotlib.pyplot as plt def ph_histogram(plant_list, year): '''Creates a histogram of plant pH values''' x = [plant.soil_ph for plant in plant_list] n, bins, patches = plt.hist(x, bins = 50, range = (0,100), facecolor='g') ...