text
stringlengths
37
1.41M
#ecoding=utf-8 """ pythons study time create by 9:58 2016-7-22 M.simple """ import time import calendar class MyTimer: def timeMethod(self): print "当前时间的时间戳:", time.time() print "time local:", time.localtime(time.time()) print "time default format:", time.asctime...
'''You are given a string in the camel case format. Your task is to convert this string into the snake case format. Examples of the camel case strings are as follows: ComputerHope FedEx WordPerfect Note: In the camel case string, the first character may or may not be capitalized. Examples of the snake case strings ...
'''Gary likes to solve problems of array, but he doesn't like problems that involve queries. His school teacher gave him an assignment full of problems but one of them involve queries. Can you help Gary in solving that problem so that he can go and play with his friends? The problem is : Given an Array A consisting of...
#Bubble sort in python for Avtivity 02 def bubbleSort(xlist): for passnum in range(len(xlist)-1,0,-1): for i in range(passnum): if xlist[i]>xlist[i+1]: temp = xlist[i] xlist[i] = xlist[i+1] xlist[i+1] = temp xlist = [14,45,21,70,46,43,27,57,41] bu...
# 33. 搜索旋转排序数组 # https://leetcode-cn.com/problems/search-in-rotated-sorted-array/ class Solution: def search(self, nums: List[int], target: int) -> int: N = len(nums) left = 0 right = N-1 # mid = (left+right)//2 while left<=right: mid = (left +right)//2 ...
count = 0 def findMinStep(start, end, bank): if end not in bank: return -1 def distance(s1, s2): dis = 0 for i in range(len(s1)): if s1[i] != s2[i]: dis += 1 return dis def dfs(start, end, bank): global count if start == end: ...
# 合并2个升序数组 def merge(nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ k = m+n-1 j = n-1 i = m-1 while j>=0 and i >=0: # print(j) if nums2[j]>= nums1[i]: nums1[k] = nums2[j] k -= 1 j -= 1 else: ...
import sys, re # Returns the first index after a newline character in the file. Used to count the lines in the text. def newlines_index(text): newlines_list = [0] index = 1 for char in text: if char == '\n': newlines_list.append(index) index += 1 return newlines_list #...
lst=eval(input('enter elements of list separated by commas')) l1=list(lst) print(l1) for x in range(len(l1)): m=l1[x] if (m>0): print(m,end=' ,')
check1=int(input()) if(check1>1 and check1<10): print('yes') else: print('no')
from os import system, name import string import sqlite3 import random import re conn = sqlite3.connect('database.db') c = conn.cursor() def clearscreen(): if name == 'nt': _ = system('cls') else: _ = system('clear') def pass_gen(size = 12, chars = string.ascii_letters + stri...
# Clases en python """ Las clases nos proveen un medio para la construccion de datos y funcionalidad en un mismo lugar. Creando nuevas clases podemos crear nuevos tipos de datos. - El mecanismo de clases de python agrega clases con un minimo de nueva sintaxis y semantica. Es muy facil la curva de aprendizaje ...
import numpy as np A = np.array([1, 2, 3, 4]) B = np.array([1, 2, 3, 4]) print(A) print(A.shape) A = A[np.newaxis, :] print(A) print(A.shape) print(B) print(B.shape) B = B[:, np.newaxis] print(B) print(B.shape)
class my_decorator_class: def __init__(self, my_decorator_function): self.my_decorator_function = my_decorator_function def __call__(self): print("inside of __call__", self.my_decorator_function.__name__) self.my_decorator_function() @my_decorator_class def my_function(): print("...
""" SCRIPT 3: This script's main task is to search for movies with missing metadata and delete them (Comment out the methods you don't need in the main-method) Another task was to recognize TV-Series with the "title.episode.tsv.gz" file from "https://datasets.imdbws.com/" (file has to be named "imdb_episode_metadata.t...
# coding: utf-8 #5) Crie um algoritmo que pergunte ao usuário seu nome e sua idade. Em seguida verifique se a idade é maior ou menor de 18 #Solução bem simples, auto explicativa nome = input("Qual é o seu nome? ") idade = int(input("Qual é a sua idade? ")) if(idade < 18): print(nome, 'você é menor de idade e tem,...
# coding: utf-8 #2) Leia um caractere e informe na tela se ele é um número ou letra. caractere = input("Informe o caractere que deseja verificar: ") caracteresNumerais = "0123456789" #Primeiro reservei os caracteres que tem a menor quantidade na comparação, são os números paraLooping = False #Criei tamém uma variável ...
""" search.py: Search algorithms on grid. """ import operator import heapq from collections import deque def heuristic(a, b): """ Calculate the heuristic distance between two points. For a grid with only up/down/left/right movements, a good heuristic is manhattan distance. """ # BEGIN HERE # ...
#!/usr/bin/python # -*- coding=utf-8 -*- values = input("Input some comma sepreated numbers: ") list = str(values).split(',') tuple = tuple(list) print('list:'+str(list)) print('tuple:'+ str(tuple))
#####----- Mass Calculator start ----##### def massCalc(): print("\n\nPlease have the following ready:") print(" - Mass that you were given") print(" - Molar mass of the chemical that you know the mass of") print(" - Amount of moles of each chemical") print(" - Molar mass of the chemical that you need to know...
"""Kata: Sum of all the multiples of 3 or 5 Best practice by daddepledge & nickmariner def find(n): return sum(e for e in range(1, n+1) if e % 3 == 0 or e % 5 == 0) """ def find(n): sum = 0 for i in range(n + 1): if i % 3 == 0 or i % 5 == 0: sum += i# Code here return sum
from collections import deque # Size of a tile, in pixels TILE_SIZE = 32 # Screen dimensions, in tiles SCREEN_WIDTH = 20 SCREEN_HEIGHT = 15 # If set to True, each draw call will do one step of the algorithm. # If set to False, the algorithm will be solved in one draw call. SHOW_STEPS = True GROUND = 0 WALL = 1 wor...
#Faça um Programa que peça um número inteiro e determine se ele é par ou impar. Dica: utilize o operador módulo (resto da divisão). numero = int(input('Informe um número: ')) resultado = numero % 2 if resultado == 0: print('O número {} é PAR'.format(numero)) else: print('O número {} é IMPAR'.format(numero))
#def listsfun(): #list1=[5, 10, 15, 20, 25] #list2=[list1[0]] + [list1[-1]] #print(list2) #listsfun() #a=[1,1,2,3,5,8,13,21,34,55,89] #for i in range(len(a)): #if a[i]<5: #print(a[i]) def listsfun1(): a=[1,1,2,3,5,8,13,21,34,55,89] b=[1,2,3,4,5,6,7,8,9,10,11,12,13] for i in a: for ...
# Brain Schweikart # M2HW2 - World Series Winners # 11/01/18 # Read text file then allow the user to select a team # After selecting a team dispaly the total wins winner_list = [] try: f=open('WorldSeriesWinners.txt', 'r') for names in f.readlines(): names = names.strip('\n') winner_list.append(names) f.clo...
# Brain Schweikart # M6HW1 - Employee & Production Class # 12/09/18 # Create Employee and Production worker Classes # Inheritance from emp to production class then display class Employee: def __init__(self, name, number): self.__name = name self.__number = number def set_emp_name(self, name): self.__name = n...
#!/usr/bin/env python # coding: utf-8 # In[1]: from tensorflow.keras.datasets import mnist import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense, Conv2D, MaxPooling2D from random import randint # ...
#User Input Section firstName=input("What is your first name? ") lastName=input("%s ,What is your last name? "%firstName) #Output Section print(f"Name: {firstName} {lastName}")
#! /usr/bin/env python3 """ Allow the user to track where they went to lunch. """ import shelve import os from operator import itemgetter print(" Starting lunch traker") """ Opening Save File """ print(" Opening storage") days = {0:"Monday", 1:"Tuesday", 2:"Wednesday", 3:"Thursday", 4:"Friday"} storage = shelve.open("...
def extractString(stringInput, delimiter1, delimiter2): """Takes in a string, and delimiters and outputs the string with the text in between the delimiters remove and added to a list. Both the new string and the list are given in a tuple.""" replacementPhrases = [] finalString = "" mode = ...
#!/usr/bin/env python3 # Copyright 2018-2020 GCN http://www.0101solutions.consulting/ # We begin by defining the class, and then defining the methods, and class variables. class Duck: # The 'self' arguement, is a refrence to the object. # And we use this to reference the object itself. sound = 'Quaack!' ...
user=int(input("Enter the Number-")) if user%7==0 and user%11==0: print("It is divisible by both 11 and 7") elif user%7!=0 or user%11==0: print("It is not divisible by 7 but it is divisible by 11") elif user%7==0 or user%11!=0: print("It is divisible by 7 but it is not divisible by 11") else: print("It ...
# Programmers: Grace Armstrong & James Broderick # Course: CS151, Prof. Mehri # Date: 10.3.21 # Lab Number: 3 # Program Inputs: weight, distance # Program Outputs: cost # Do not accept values of 0 or less for the weight of the package. # Do not accept weights of more than 20 kg (this is the maximum weight the company ...
import xlsxwriter #count the frequency number of character def countFrequeceNumber(text): result = [0] * 26 text = text.lower() for ch in text: if (isCharacter(ch)): result[ord(ch) - 97] = result[ord(ch) - 97] + 1 return result #count the frequency of character def countFrequency(t...
import pandas as pd import numpy as np import matplotlib.pyplot as plt X_train=pd.read_csv('Linear_X_Train.csv') X_test=pd.read_csv('Linear_X_Test.csv') y_train=pd.read_csv('Linear_Y_Train.csv') #linear regression from sklearn.linear_model import LinearRegression regressor=LinearRegression() regressor.fit(X_train, y_...
def main(): CountDict = {} with open("rosalind_ini6.txt", "r", encoding="utf-8") as file: data = file.read() word_list = data.split() # ------ key_count(CountDict, word_list) result(CountDict) def key_count(dict, list): for word in list: if word in dict: ...
import pygame import time import numpy as np class MouseTracker: ''' Mouse tracker Class: 1. Track the coordinates of mouse point when the mouse button is held. Used to record the trajectory of the mouse. 2. Track the coordinates of mouse points when the mouse button is clicke...
import email.utils import string def f(): lower=string.ascii_lowercase upper=string.ascii_uppercase a=input('enter ') val=0 i=a[val] leng=len(a)-1 #This will check it till the first USERNAME while i!='@': try: if i in lower or i in upper or type(int(i))==int or i=='_' or i=='-': if val==leng: pri...
def printit(): global board for i in range(1,12): for j in range(1,12): if i==2 and j==2: print(board[2][2],end='') elif i==2 and j==6: print(board[2][6],end='') elif i==2 and j==10: print(board[2][10],end='') ...
def fib(n=1000, a=0, b=1) -> list: res =[] while (a < n): #print (a, end=' ') res.append(a) a, b = b, a+b return res
a = int(input('a=')) b = int(input('b=')) a = a+b print('a= %d' % (a)) a *= a+2 print('a= %d' % (a)) print('b=%d' % (b))
import sys ## This program counts the number of vowels in a string and reports the frequency of each vowel. ## Declare and Define Global variables ## Counts the number of vowels and gives frequency def count(string): global counter_a counter_a = 0 global counter_e counter_e = 0 global counter_i counter_i = 0...
filename = 'learning_python.txt' print("Just printing the whole thing.\n") with open(filename) as file_object: contents = file_object.read() print(contents) print("====") print("Just printing teach line.\n") with open(filename) as file_object: for line in file_object: print(line) print("====") print("Making ...
# Storing User info that they enter: # import json # username = input("What is your username? ") # file = 'username.json' # with open(file, 'w') as f: # json.dump(username, f) # print(f"Your username hsa been stored, {username}!") # With this stored, we can call it back in another program: # import json # file...
filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() print(pi_string[:52] + "...") print(len(pi_string)) # This just demonstrates how you can output a bunch of stuff. # Let's look for my birthday: 122882...
aa = ['star', 'nebula', 'black hole', 'planet', 'asteroid', 'comet'] for a in aa: print(a) for a in aa: print("A " + a.title() + " is an object in space!") print("That's all objects in space.") for value in range(1,5): print(value) # outputs: 1, 2, 3, 4 nums = list(range(1,6)) print(nums) even_nums = list(ran...
# Basic loop where if the item in the array 'cars' == 'honda', make it all caps cars = ['accord', 'civic', 'honda', 'camry'] for car in cars: if car == 'honda': print(car.upper()) else: print(car.title()) # Can do things to set the case or something in case it doesn't amtter: a = 'AAA' a.lower() == 'aaa' # retu...
#!/usr/bin/env python """ Routing table class. """ import numpy as np import pandas as pd class RoutingTable(object): """ Routing table class. Simple class that stores pairs of strings that can signify one-hop routes between entities in a graph. Assigning a value to a pair that isn't in the cla...
import numpy as np def Sigmoid(z): G_of_z = float(1.0/float(1.0+np.exp(-1.0*z))) return G_of_z def Hypothesis(X, Theta): ''' This function gives the h_theta(X) or the hypothesis function. Here X should be an numpy array of dimensions (n,m) where all n = 0 elements are equal to 1. Theta is the 1-D parameters v...
#File Name: ps4.py #Author: Chaitra Kothari #Date: Oct 30th, 2015 #Description: This problem set will introduce you to using successive approximation, as well as data structures such as tuples and lists. #==============================================Problem1============================= def nestEggFixed(salary, save...
#!/usr/bin/env python3 """ __author__ = "Tanghaoyi" __pkuid__ = "1800011775" __email__ = "1800011775@pku.edu.cn" """ import turtle def brick(h,c,d,a,wall): #对于被铺上砖的区域,将其状态记为0 alist = [] x = (h+1)%a #将单位区域的标记数转换为二维坐标 y = (h+1)//a for i in range(x,x+c): #将从标记数为h的单位区域的右上角铺上砖 for j in...
#!/usr/bin/env python # coding: utf-8 # # Best First Search # - [The board](#The-board) # - [Utils](#Utils) # - [Main logic](#Main-logic) # - [Example #1](#Example-#1) # - [Example #2](#Example-#2) # - [Example #3](#Example-#3) # ## The board # In[1]: target_board = [ 1, 2, 3, 4, 5, 6, 7, 8, 0 ] allow...
#!/user/bin/env python3 # Created by: Jaeyoon # Created on: Sept 2019 # This program shows local and global variables work #global variable variable_X = 25 def local_wariable(): # this show what happens with local variables variable_X = 10 variable_Y = 30 variable_Z = variable_Y + variable_X pr...
#simple if and else #ssquarefeet,pincode square_feet=float(input("tell us the squqre_feet : ")) pincode=int(input("tell us pincode of city : ")) if square_feet<=4 or square_feet<=1 and pincode==574240: print("registration charges is:2400") elif square_feet<=8 or square_feet<=4 and pincode==584219: pr...
#Bus chart chart="" for row in range(1,8): for seat in range(1,5): amount=int(input("tell us total amount u have:")) if amount>=500: print("ur seat number:",row,seat) chart+="$" else: chart+="%" chart+="\n" print(chart)
# # @lc app=leetcode id=234 lang=python3 # # [234] Palindrome Linked List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: ...
# # @lc app=leetcode id=206 lang=python3 # # [206] Reverse Linked List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: ...
class TreeNode: def __init__(self, node_name, value): self.node_name = node_name self.value = value self.count = 1 self.leaves = {} def add_child(self, child_node): self.leaves[child_node.node_name] = child_node def get_value(self): return self.value def update_value(self, new_value): self.value =...
def ejercicio11(): #definimos las varibles print("Consulte su bono") bonoX=0 #introduscamos los valores antiguedadZ=int(input("Introdusca sus años de antiguedad:")) #procedimiento if antiguedadZ==1: bonoX="100" if antiguedadZ==2: bonoX="200" if antiguedadZ==3: bonoX="300" if antiguedadZ=...
def ejercicio09(): #Definir variables y otros print("Escoja entra las dos polizas que le brindamos A cobertura amplia y B daños a terceros ") enuciadoA=0 enuciadoB=0 enuciadoC=0 enuciadoD=0 enuciadoE=0 #Datos de entrada tipoX=input("Elija la poliza A o B :") alcoholX=input("¿Tiene por habito beber ...
class BoardValidator(): # Validates 2d array string boards def __init__(self, board_state): self.board_state = board_state def transpose_board(self): return [[self.board_state[j][i] for j in range(3)] for i in range(3)] def validate_non_diagonals(self): # if True then game over...
import numpy as np #initialise random inputs #500 input values #1000 whats? D = np.random.randn(1000, 500) #this array has one element for each layer (10) and contains the numner of neurons #at each layer. hidden_layer_sizes = [500] * 10 #this allows us to say which function to use at each layer #use tanh non-linia...
class Solution: # @return a tuple, (index1, index2) # using a hash table to solve the problem # and make time complexity stay in O(n) def twoSum(self, num, target): length = len(num) # dict in python is a hash table # key is the number # value is the index # remem...
# coding=utf-8 class Stack(object): def __init__(self): self._items = [] def is_empty(self): return not bool(self.size()) def peek(self): return self._items[self.size()-1] def size(self): return len(self._items) def push(self, item): self._items.append(i...
# if > si # elif > sinon si # else > sinon age = 15 if age < 10 : print ("trop jeune") elif age < 20: print ("OK") elif age > 20: print ("trop vieux") else: print ("égale à 20") mots = "Bonjour" if "y" in mots : print("il est dedans") else: print("pas dedans")
#PART 1 Data preprocessing #importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing DataSet dataset = pd.read_csv('Churn_Modelling.csv') #creating the matrix of dataset X = dataset.iloc[:, 3:13].values #x axis with the independent variable Y = dataset.iloc...
class TickTackToe() : def __init__(self, x, o) : self.board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] self.move = 1 self.p1 = x self.p2 = o # def makeBoard(self) : # self.board = def printBoard(self, ) : for y in range(3) : for x in range(3) : print self.board[y][x], print ...
text=input("Введите текст:") for letter in text: print(letter)
try: age = int(input("Please enter your age: ")) except ValueError: print("Hey, that wasn't a number!") else: print("I see that you are %d years old." % age) # try: # dividend = int(input("Please enter the dividend: ")) # divisor = int(input("Please enter the divisor: ")) # print("%d / %d = %f"...
# -*- coding: utf-8 -*- """ Created on Tue May 10 16:06:40 2016 @author: ylim Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) """ str_in = list(raw_input("Enter a string: ")) #str_list.append([a for a in st...
import random import math import ctypes as c import os ''' getPrime() returns probably prime 64-bit length number ''' def getPrime(): random.seed() prime = 0 while not primeTest(prime, 100): odd = 0 while odd % 2 == 0: prime = random.getrandbits(64) odd = int(str(pr...
#! /usr/bin/python class DictFilter(object): """ DictFilter creates a filter to check that a dict has the properties you specify. """ def __init__(self, _fil=True): if isinstance(_fil, DictFilter): self.__filter = _fil.check elif isinstance(_fil, bool): self.__fi...
from abc import ABCMeta, abstractclassmethod class Conta(metaclass=ABCMeta): def __init__(self, codigo): self._codigo = codigo self._saldo = 0 def deposita(self, valor): self._saldo += valor @abstractclassmethod def passa_o_mes(self): pass def __str__(self): ...
#!/usr/bin/env python """Support for enumerated values. Sometimes your really want something closer to an enumerated type. This is my take on supplying something to do this. Usage is along the lines of:: Colours = Enum("Colours") RED = Colours("Red") BLUE = Colours("Blue") GREEN = Colours("Green") T...
var1 = input("Enter a num greater than 10 or less than 20") var1 = int(var1) if(var1>10 or var1<20): print("entered value is in the range") else: print("please try again")
nums = [1, 2, 3, 4, 5] nums[3] = nums[1] print(nums[3]) num = [1,2,3] num.append(4) print(num) words = ["hello"] words.append("world") print(words[1]) print(len(words)) letters = ['a', 'b', 'c', 'd', 'e'] print(letters.index('d')) print(max(letters)) print(letters.count('a')) letters.remove('d') letters.reverse() ...
EMPTY_INPUT_FILENAME = "Must specify input filename" EMPTY_OUTPUT_FILENAME = "Must specify output filename" INCORRECT_NUM_BOXES = "Invalid number of boxes" NONEMPTY_FOLDER_ERROR = "Output folder must be empty" INCORRECT_INPUT_FILE_FORMAT = "Input file has incorrect format" def validate_inputs(filename1, filename2, num...
def bubble_Sort(bslist): for numbers in range(len(bslist)-1,0,-1): for x in range(numbers): if bslist[x] > bslist[x+1]: imple = bslist[x] bslist[x] = bslist[x+1] bslist [x+1] = imple bslist = [ 30, 1, 35, 11, 13, 23, 41, 34, 24, 9, 77, 7, 99] bubb...
from tkinter import * window = Tk() window.title("Welcome to First City Providential College") lbl = Label(window, text = "Hello") lbl.grid(column = 0, row = 0) window.mainloop()
import random import numpy def generate_dense_matrix(n): """Function generates a dense matrix""" matrix=[] for i in range(n): row=[] for j in range(n): row.append(random.randint(0,2**12)) matrix.append(row) return matrix def generate_sparse_matrix(n): """Function generates a sparse matrix""" matrix=gen...
def CommaCode(lst): commaCode = '' lst.insert(-1,'and') for i in range(len(lst)): if i == len(lst) - 1: commaCode += str(lst[i]) elif i == len(lst) - 2: commaCode += str(lst[i]) + ' ' else: commaCode += str(lst[i]) + ', ' return commaCode spam...
"""Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function w...
#Este archivo contiene las funciones de visualización (pandas, matplolib y seaborn) que elaboramos en el proyecto. import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import os import matplotlib.image as mpimg import random def sns_gstyle(): """Esta función cambia los gráfi...
n=input() list1=[] for i in range(n): list1.append(raw_input()) for j in range(len(list1[0])): for i in range(n): if list1[i][j]!="?":
n,k = [int(x) for x in raw_input().split(" ")] str=raw_input() if n-k<k: for i in range(n-k): print "RIGHT" for i in range(n): print "PRINT "+ str[-1-i] if i!=n-1: print "LEFT" else: for i in range(k-1): print "LEFT" for i in range(n): print "PRINT "+ str[i] if i!=n-1: print "RIGHT"
import math dictex = {'age':35,'height':5.5} dictex['weight']=165 print dictex print "%.15f" %(math.pi) print "%.5d" %(34) list1=[3,6] str="random string" print 'R' in str
from string import Template # 1 #saves time typing and reduces code length #2 # like if u wbant to use the delimeter $ in the template # declaration then u can use double $$ #3 '''to attach a string at the end od the $item u'll have to use {} like "the ${place}yard is far away from here" its output will be "the shipy...
import sqlite3 def create_table(db_name,table_name,sql): with sqlite3.connect(db_name) as db: cursor = db.cursor() cursor.execute("""SELECT name FROM sqlite_master WHERE name=?""",(table_name,)) result = cursor.fetchall() keep_table = True if len(result) == 1: re...
import sqlite3 from create_product_table import * from delete_existing_product import * from insert_product_data import * from select_existing_products import * from update_product_data import * from product_management_window import * def product_search_menu(): print() print('~ ~ ~ Search Products SubMenu ~ ...
from urllib.request import urlopen from bs4 import BeautifulSoup import pandas as pd def get_team_stats(year): # URL page we will scraping (see image above) url = "https://www.basketball-reference.com/" \ "leagues/NBA_{}_ratings.html".format(year) # this is the HTML from the given URL html =...
def quick_sort1(lyst): '''快速排序方法1''' if len(lyst) < 2: return lyst # 当列表元素少于两个默认有序,返回该列表 pivot = lyst[0] # 基准值 left = [x for x in lyst[1:] if x <= pivot] # 将小于基准值的放在left列表 right = [x for x in lyst[1:] if x > pivot] # 将大于基准值的放在right列表...
#!/usr/bin/env python # coding: utf-8 # ## 1. Import and process data # # - In this section, I import the data from files and normalize it, then I split the data to training and test sets # # ### 1.1. Import necessary packages # In[82]: import numpy as np import pandas as pd import matplotlib.pyplot as plt fro...
str = "foo" lst = ["abra", 2038, "cadabra"] for char in str: print(char) for elem in lst: print(elem)
import numpy as np from matplotlib import pyplot as plt if __name__ == '__main__': x = np.arange(0, np.pi*2, step=0.01) y = np.cos(x) plt.xlim(x.min(), x.max()) plt.xlabel("X") plt.ylim(y.min(), y.max()) plt.ylabel("Y") plt.plot(x, y,) plt.show() print x
# XO game ls = [1, 2, 3, 4, 5, 6, 7, 8, 9] win = "" lsp = [] pl = 1 print("Enter the two player name") # loop for getting player name while pl <= 2: pl1 = input() lsp.append(pl1) pl = pl + 1 print(lsp[0], "your character is X") print(lsp[1], "your character is O") j = 0 c = "" while True: ...
#/usr/bin/python3 def main(): with open('aoc01_input.txt') as f: inp = f.read() raw_fuel = 0 total_fuel = 0 for line in inp.splitlines(): mass = int(line)//3 -2 raw_fuel += mass while mass > 0: total_fuel += mass mass = mass//3 - 2 print(f"P...
# Find the Lonely Integer in given set import collections def lonelyinteger(a): counts = collections.defaultdict(int) for num in a: counts[num] += 1 print counts for num, count in counts.items(): if count % 2 == 1: return num if __name__ == '__main__': ...
__author__ = 'sridhar' # Service Lane Problem N, T = map(int,raw_input().rstrip().split(" ")) Array = map(int, raw_input().rstrip().split(" ")) def find_min(start,end): min=Array[start] for i in range(start,end+1): # print start, end,"this" if(Array[i]<min): min = Array[i] retur...
# overloading using @ decortors # using default parameters in method # and calling method with less arguemts class Student: def sum(self,a = 0 ,b = 0, c = 0): s = (a + b + c) return s s1 = Student() print(s1.sum(5,78)) # method overrriding # class Student1: # # def cal_marks(self,m1,m2,m3): ...
from math import sqrt n = 43 for i in range(2, int(sqrt(n) + 1)): if n % i == 0: print(n, ' is not prime, can be divisible by :', i) break else: print(n, ' is prime number')