text
stringlengths
37
1.41M
# open twain.txt, "copy" the data into 'text', then close the file. def words_counted(): text ='' f = open('twain.txt') for line in f: newline = line.strip() text += ' '+ newline f.close() text = text.split(' ') # define 'text' as the file 'text' split by spaces word_count = {} # make a dict named 'word_coun...
def operacion(s) -> str: if s in ['1', '4', '78']: return '+' elif s[-2:] == '35': return '-' elif s[0] == '9' and s[-1] == '4': return '*' elif s[:3] == '190': return '?' def main(): n = int(input()) for _ in range(n): s = input() print(operacio...
def main(): n = int(input()) while n > 0: str = input() ans = [] flag = True for c in str: if c == '(' or c == '[': ans.append(c) else: if len(ans) == 0: flag = False continue ...
inicio = True while True: try: s = input() for c in s: if c == '"': if inicio: print("``", end='') else: print("''", end='') inicio = not inicio else: print(c, end='') ...
#!/usr/bin/env python3 import itertools inputFile = input("Enter the File:") inputFile = open(inputFile,"r") firstLine = inputFile.readline() pizza_list = [] if firstLine: pizzaTotal, grpOne, grpTwo, grpThree = firstLine.split(" ") for line in itertools.islice(inputFile, 0, int(firstLine[0])): pizza_list.a...
from extraClasses import LimitedList class Board: """ A class that stores the information and functions for the game board. Parameters ---------- piecesPerHole: int, optional Number of starting pieces in each of the positions on the board, default 4 rowLength: int, optional ...
# Tic Tac Toe Game # Import function to clear output from IPython.display import clear_output # Print board function board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' '] def display_board(board): clear_output() print(board[1] + '|' + board[2] + '|' + board[3]) print(board[4] + '|' + board[...
import os import speech import recog lvm_part=""" Check storage devices is attached to the OS Create Physical Volume Display Physical Volume Manage Volume Group Display Volume Groups Manage Logical Volume Display Logical Volumes Exit to go back to main menu """ def logical_vol(): while True: os.system("cl...
""" .. module:: SeededKMeans SeededKmeans ************* :Description: SeededKmeans is the implementation of the Seeded-KMeans algorithm described in the paper Semi-supervised Clustering by Seeding It uses labelled data to perform an initialization of the clusters in the k-means clustering """ import numpy as np ...
from typing import List # Given an array nums and a value val, remove all instances of that value in-place and return the new length. # # Do not allocate extra space for another array, you must do this by modifying the input array in-place # with O(1) extra memory. # # The order of elements can be changed. It doesn't...
from typing import List # Given an array of integers arr, return true if and only if it is a valid mountain array. # # Recall that arr is a mountain array if and only if: # arr.length >= 3 # There exists some i with 0 < i < arr.length - 1 such that: # arr[0] < arr[1] < ... < arr[i - 1] < A[i] # arr[i] > arr[i + 1...
""" This script prompts a user to enter what this app will next. """ from todo_cli.todo_app import TodoApp def display_current_todo_tasks(current_app: TodoApp) -> None: """ Display todo tasks that `current_app` has """ print( "These are the TODO tasks you have: ", [ f"{todo...
# -*- coding: utf-8 -*- """ Created on Thu Oct 28 09:20:08 2021 @author: Noman """ from tkinter import* window=Tk() window.title("welcome to tic_tac_toe.0.1") window.geometry("500x500") lb1=Label(window,text="the game begins",font=("arial","15")) lb1.grid(row=0,column=0) lb1=Label(window,text="player1=x:...
Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the la...
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. Example 1: Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The...
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There ar...
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a bi...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # recursive: def preorderTraversal(self, root: TreeNode) -> List[int]: res=[] self...
''' Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, return the number of the beautiful arran...
Given a list of non negative integers, arrange them such that they form the largest number. Example 1: Input: [10,2] Output: "210" Example 2: Input: [3,30,34,5,9] Output: "9534330" Note: The result may be very large, so you need to return a string instead of an integer. class Solution: def largestNumber(self...
''' [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[Optional[ListNo...
''' You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any...
Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace". from collections import defaultdict class Solu...
''' There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the m x n maze, the ball's start p...
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order. Input: s = "barfoothefoobarman", words ...
Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. 思路: ''' -1 1 -> 2 -> 3 -> 4 dummy head ...
class Node: def __init__(self,data): self.data=data self.next=None class LinkList: def __init__(self): self.head=None def push(self,newdata): new_node=Node(newdata) new_node.next=self.head self.head=new_node def delete(self,target): temp=self.hea...
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum does...
Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpos...
Refer to https://leetcode.com/discuss/interview-question/492652/ def plane_seat_reservation(n,s): res = 0 h=dict() for i in range(1,n+1): h[i] = set() for v in s.split(): h[int(v[0:-1])].add(v[-1]) case1={'D','E','F','G'} case2={'B','C','D','E'} case3={'F','G','H','J'} c...
class Solution: def simplifyPath(self, path: str) -> str: stack = [] absolute_path = '' char_list = path.split('/') for char in char_list: # Do nothing if char == '' or char == '.': continue # When stack is empty, ...
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies, as if caused by under-popul...
# Numbers can be regarded as the product of their factors. # For example, 8 = 2 x 2 x 2 = 2 x 4. # Given an integer n, return all possible combinations of its factors. You may return the answer in any order. # Note that the factors should be in the range [2, n - 1]. # Example 1: # Input: n = 1 # Output: [] # Exam...
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Outp...
Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Exampl...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': stack = [root] parent = {ro...
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string "dir\n\ts...
def dayOfWeek(S, K): days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] return days[(days.index(S) + K) % 7] S, K = 'Saturday', 23 print(dayOfWeek(S, K))
''' Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list. ''' Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" Output: 3 Input: wor...
#1.给一个string,可能是一个单词,可能是一段话, 要求返回最长的重复的substring。例如: #Input:"I like apple, I like banana." Output: "I like" #Input: "banana" Output: "ana" class solution(): def Max_Repeat_Substring(self,str): max=0 # 相同字符连续出现的最大长度 k=0 # 记录了相同字符连续出现的个数 # i: 字符间距从1开始递增 for i in range(1,len(str)):...
''' You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to ...
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not con...
Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string. In one operation, you can choose any character of the string and change it to any other uppercase English character. Find the length of the longest sub-string containing all repeating letters you can...
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ low,high=1,n whi...
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return leng...
Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any or...
# question default rows=3,columns=3, 9 is the target, so you will get 3 as result because (0,0)->(1,0)->(2,0)->(2,1) three times """ 1 0 0 1 0 0 1 9 1 """ class solution(): def minimumDistance(self,area): nRows=len(area) nColumns=len(area[0]) if len(area)==0 or len(area[0])==0 o...
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] ...
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,8,2,3,1] Output: [2,3] """ 遍历nums,记当前数字为n(取绝对值),将数字n视为下标(因为a[i]...
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that h...
# Sum of Numbers # 6/23/2017 #CTI-110 M4HW1 - Sum of Numbers # Eric Hadley total = 0 number = 0 # Explain what we are doing. print('This program calculates the sum of') print('numbers you will enter.') print('enter negative number to end.') # Get the numbers and accumulate them. while number >= 0 : ...
#First Tier (Super class) class Task: task_count = 0 #to access taskcount just, Task.taskcount tabu_freq = 0 def __init__(self, resource_reqd, tabu_tenure): self.resource_reqd = resource_reqd self.tabu_tenure = tabu_tenure Task.task_count += 1 def get_resource_reqd(self):...
def Find_substring_and_return_index(self, haystack: str, needle: str) -> int: # If the needle is an empty string -> return 0 if needle == "": return 0 # We are now finding the needle in the haystack # Algorithm: traverse the haystack for i in range(len(haysta...
def Recursive(n): if n==0: return 1 else: return n*Recursive(n-1) num=int(input("Enter a number:")) print("The factorial is:",Recursive(num))
class Base: def k1(self,a): return a class Derived1(Base): def k2(self,a,b): return a+b class Derived2(Derived1): def k3(self,a,b): return a*b k=Derived2() print(k.k1(5)) print(k.k2(5,6)) print(k.k3(5,6))
def fact(): a=int(input("Enter a number ")) fact=1 if a<0: print("factorial is does not exist") elif a==0: print(a," factorial is 0") else: for i in range(1,a+1): fact=fact*i print(f"{a} factorial is {fact}") fact()
import turtle import random class Ball(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.color(random.choice(colors)) self.shape(random.choice(shapes)) self.penup() self.speed(0) self.goto(random.randint(-290, 290), random.randint(200, 450)) ...
# -*- coding: utf-8 -*- """ CCT MSc DA -- Programming Python (Amilcar Aponte amilcar@cct.ie) @author: Lajos Reisenleitner sba-21-727 Calculator v1.3 """ import numpy # for round(complex) only class Calculator: '''Basic Arithmetic Calculator A - Addition S - Subtraction P - Product D - Divisio...
#!/usr/bin/python def fasta_parser(fasta_file): with open(fasta_file, mode='r') as fasta_file: fasta_dict = {} seq_name = '' for fasta_line in fasta_file: if fasta_line.startswith('>'): seq_name = fasta_line[1:-1] fasta_dict[seq_name] = '' ...
def isMatch(target, pattern): string_stack = [] str_lst = list(target) pattern_lst = list(pattern) [pattern_lst.append(None) for i in range(len(str_lst))] for i in range(len(str_lst)): if len(str_lst) == 0: string_stack.append(0) elif str_lst[i] == pattern_lst[i] or pattern_lst[i+1]=="*": string_stack.a...
# -*- coding: utf-8 -*- """ Created on Thu Mar 26 15:41:19 2015 @author: Richard """ def reverse_complement(DNA): ''' (str) -> str Return the reverse complement of string sequence DNA Precondition: DNA only include valid nucleotides 'A', 'T', 'C', 'G' ''' seq = DNA.upper() comple...
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 21:24:17 2015 @author: Richard """ def rev_complement(dna): ''' (str) -> str Return the reverse complement of string dna Precondition: there are only valid nucleotides in dna >>> rev_complement('atcg') 'cgat' >>> rev_complement('TTCGAT') ...
def reverse_complement(dna): ''' (str) -> str Return the reverse complement of a dna string >>> reverse_complement('ATGTC') GACAT ''' dna2 = dna.upper() compl_dna = '' for base in dna2: if base == 'A': compl_dna += 'T' elif base == 'T': comp...
def expected_offsprings(offspring): ''' Return the number of expected offsprings with the dominant phenotype in the next generation given that each couple has exactly 2 offsprings ''' myfile = open(offspring, 'r') expected = 0 line = myfile.readline() line = line.rstrip() line = li...
def distance_matrix(fasta_file): ''' (file) -> str Return the p-distance matrix between sequences in the fasta_file Precondition: all sequences in the fasta file have the same length ''' # convert the fasta file into a dictionary # change the sequence names to numbers seq = {} i = 1...
def translate_RNA_splice(file): ''' (file) -> str File contains a dna sequence and introns in FASTA format Return the protein translation of the dna sequence after introns have been spliced >>> translate_RNA_splice('splice_example.txt') MVYIADKQHVASREAYGHMFKVCA* ''' # convert the FAS...
# -*- coding: utf-8 -*- """ Created on Wed Apr 24 23:25:54 2019 @author: Richard """ def LongestIncreasingSubsequence(X): """ (list) -> list Returns the Longest Increasing Subsequence in the Given List/Array """ N = len(X) # initialize lists or size N and N+1 respectively ...
def find_all_motifs(a, b): ''' (str, str) -> list Return all the indices of string a in string b into a list >>>find_all_motifs('ATAT', 'GATATATGCATATACTT') [1, 3, 9] ''' i = 0 pos = [] found = True while found: i = b.find(a, i) if i >=0: pos.append(i...
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 20:12:21 2015 @author: Richard """ def odd_sum(input_file): ''' (file) -> int Given 2 positive integers a and b (a<b<10000) in input file, return the sum of all odd integers from a through b, inclusively ''' # open file infile = open(...
# http://www.careercup.com/question?id=5145121580384256 # n is the number of balls (n = 3^d) # Time: O(log n) - Space: O(n) class BallSet: def __init__(self,ballset): #ballset is list of 81 weights #the index is the identifier of the ball # 81 = 3 * 3 * 3 * 3 self....
import requests import hashlib # The pwnedpasswords API receives only the first 5 characters of a hached password and return a text list. def request_api_data(query_parameter): url_api = 'https://api.pwnedpasswords.com/range/' + query_parameter response = requests.get(url_api) if response.status_code != 2...
for i in range(1,100): result=1 if i%3 == 0: sure="Fizz" result=2 if i%5 == 0: sure="Buzz" result=2 if i%3 == 0 and i%5 == 0: sure="Fizzbuzz" result=2 if result ==1: p=1 multiples=0 while (p<100): if i%p == 0: ...
class team(): def __init__(self, Name ="Name", Origin= "Origin"): self.teamName= Name self.TeamOrigin = Origin def defineTeamName(self, Name): self.teamName =Name def defineTeamOrigin(self, Origin): self.TeamOrigin= Origin '''class InheritanceClassName (parent...
#Assess the passage for each of the following: # #Approximate word count # #Approximate sentence count # #Approximate letter count (per word) # #Average sentence length (in words) # #As an example, this passage: # #“Adam Wayne, the conqueror, with his face flung back and his mane like a lion's, stood #wit...
# This program reads in a string # and strips any leading or trailing spaces. # It also converts all the letters to lower case. #This program also informs the user whats the length #original string and of the normalised one rawString = input("Please enter a string:") normalisedString = rawString.strip().lower() lengt...
import world import unittest from io import StringIO class test_world(unittest.TestCase): def test_1(self): x = world.do_forward("HAL", 20)[1] self.assertEqual(x, " > HAL moved forward by 20 steps.") def test_2(self): x = world.do_back("HAL", 20)[1] self.assertEqual(x, " > HAL...
''' Created on 23 dec. 2020 @author: Caroline ''' import random import math a = 1 b = 250 x = random.randint(a,b) guess_x = math.inf turn = 0 def multiple(x, guess_x): ans = x * guess_x print(str(int(ans)) + "\n") def divisible(x, guess_x): ans = x / guess_x print(str(int(ans)) + "...
#importing library from collections import Counter #computing frequency of each note freq = dict(Counter(notes_)) #library for visualiation import matplotlib.pyplot as plt #consider only the frequencies no=[count for _,count in freq.items()] #set the figure size plt.figure(figsize=(5,5)) #plot plt.hist(no) #From ...
# 6. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, # составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он # разносторонним, равнобедренным или равносторонним. a = int(input('Введите длину первого отрезка: ')) b = int(inp...
# 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было? graph = [ [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0] ] # n * (n - 1) / 2 b = 0 for i in range(len(graph)): # длину графа умножить на количество единиц в одном элеме...
# 多继承的搜索顺序: 经典类 新式类 class P1(object): def foo(self): print('p1--->foo') def bar(self): print('p1---->bar') class P2(object): def foo(self): print('p2--->foo') class C1(P1, P2): pass class C2(P1, P2): def bar(self): print('C2---->bar') class D(C1, C2): pa...
# 类方法 """ 特点: 1.定义需要依赖装饰器@classmethod 2.类方法中的参数不是一个对象,而是类 print(cls) # <class '__main__.Dog'> 3.类方法值可以使用类属性 4.类方法中可否使用普通方法? 不能 类方法作用: 因为只能访问类属性和类方法,所以可以在对象创建之前,如果需要完成一些动作(功能) """ class Dog: def __init__(self, nickname): self.nickname = nickname def run(self): print...
# 声明 names = ['jack','tom','lucy','superman','ironman'] # 列表 computers_brands = [] # 增删改查 # 地址 # print(id(names)) # print(id(computers_brands)) # 查 # 元素获取使用:下标 索引 # print(names[0]) # print(names[1]) # 获取最后一个元素 # print(names[-1]) # print(len(names)) # print(names[len(names)-1]) # # 获取第一个元素 # print(names[-5]) ...
''' str() int() len() list() sorted() print() input() enumerate() ''' # l1 = ['a','abc','jk','oppo'] # for index,value in enumerate(l1): # print(index,value) # for index,value in enumerate('happy'): # print(index,value) # 算法 # 冒泡排序 numbers = [5,4,3,2,1] # numbers = sorted(numbers) # print(numbers) # numbers...
# 闭包 # 在函数中提出的概念 ''' 条件: 1.外部函数中定义了内部函数 2.外部函数是有返回值 3.返回的值是:内部函数名 4.内部函数引用了外部函数的变量 格式: def 外部函数(): .... def 内部函数(): ..... return 内部函数 ''' def func(): a = 100 def inner_fun(): b = 99 print(a, b) print(locals()) return inner_fun # print(a) # inner_func() x = f...
# 类型转换 # str() int() list() dict() set() tuple() # str ----> int,list,set,tuple s = '8' i = int(s) s = 'abc' l = list(s) print(l) # ['a', 'b', 'c'] s = set(s) print(s) t = tuple(s) print(t) # 反过来: int,list,set,tuple,dict,float ----> str i = 8 s = str(i) l = str(['a','b','c']) print(l,type(l)) # lis...
# print用法 # 1.用法 print('hello world!') name = '小白' print(name) # 2.用法:print(name,age,gender) age = 18 gender = 'boy' print(name,age,gender) # sep默认的分割是空格 print(name,age,gender,sep='-') # sep='*' ... # 3.用法 print(value,value,value,...,sep=' ',end='\n') print(name,age,gender,sep='-') # 转义字符: \n 换行 print('hello\nkitty...
# global 变量的范围 # 局部变量 全局变量 # 生命在函数外的是全局的,所有函数都可以访问 name = '月月' def func(): # 函数内部声明的变量,局部变量,局部变量仅限于在函数内部使用 s = 'abcd' s += 'X' print(s, name) # print(s) # 报错 def func1(): global name # 不修改全局变量,只是获取打印,但是如果要发生修改全局变量,则需要在函数内部声明:global 变量名 print(name) name += '会弹吉他' # 函数内部的变量可以随便修改赋值,但是全...
# 可变 不可变 # 不可变:对象所指向的内存中的值是不可以改变 # 不可变的类型:int str float tuple frozenset num = 10 s1 = 'abc' print(id(s1)) s1 = 'abcd' print(id(s1)) t1 = (3,4,5) print(id(t1)) t1 = (3,5) print(id(t1)) # 可变的:对象所指向的内存中的值是可以改变 # 可变类型:字典dict 列表list 集合set list1 = [1,2,3,4,5] print(id(list1)) list1.pop() print(id(list1)) d...
# 可变参数 # def add(a, b): # pass # 定义方式: # def add(*args): # arguments 参数 # # print(args)] # sum_1 = 0 # if len(args) > 0: # for i in args: # sum_1 += i # print('累加和是:', sum_1) # else: # print('没有值可计算 sum:', sum_1) # # # add() # ()空元组 # add(1) # (1,) # add(1,...
''' 输入两个字符串,从第一个字符串中删除第二个字符串中所有的字符 例如,输入"They are students."和"aeiou" 则删除之后的第一个字符串变成"Thy r stdnts." ''' # s1 = 'They are students.' # s2 = 'aeiou' # s3 = '' # 字符串: 'hdfasfa' # 方法一: # for i in s1: # 类似range(6) # # print(i,end='') # if i not in s2: # t not in 'they' # s3+=i # print(s3) # s1 = s3 # print(s1) # 方法...
# list列表的添加 # 临时小数据库 # 创建一个空列表 girls = ['杨幂'] # quit 表示退出 # 列表的函数使用: append extend insert # append 末尾追加 # while true: # name = input('请输入你心目中的美女名字:') # if name == 'quit': # break # girls.append(name) # print(girls) # extend 类似列表的合并 names = ['孙俪','巩俐','王丽坤'] # name = input('请输入你心目中的美女名字:') # gi...
# random 模块 import random ran = random.random() # 0~1之间的随机小数 print(ran) ran = random.randrange(1, 10, 2) # randrange(start,end,step) 1 ~ 10 step=2 ---> 1,3,5,7,9 print(ran) ran = random.randint(1, 10) print(ran) list1 = ['sss', 'syh', 'sss1', 'sss2'] ran = random.choice(list1) # 随机选择列表的内容 print(ran) pai = ['红...
# 找出列表的最大值 # 自己封装一个求最大值的函数 def max_collection(iterable): max_num = iterable[0] for i in iterable: if i > max_num: max_num = i print('最大值是:', max_num) # 调用:测试是否能找出最大值 list1 = [4, 1, 3, 4, 6, 7, 8, 0] max_collection(list1) tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 98) max_collection(tuple1) ...
# CLASS = raggruppamento logico di dati e metodi # OBJECT = un insieme di dati e metodi # CLASS = istruzioni per OBJECT class Learner (object): #le classi si scrivono in camel case->LearnerFederico """Creo una classe/funzione 'Learner' dove inserirò tutte le informazioni degli studenti di cui ho bisogno (nome,...
''' A module that implements a class to represent an undirected graph. ''' class UndirectedGraph: ''' A class representing an undirected graph. Each vertex is represented by an integer from zero to the number of vertices minus one. ''' def __init__(self, num_vertices, edges): if num_vertic...
#asyncio 应用,文件名不能为asyncio.py 不然会有错误 import asyncio @asyncio.coroutine def hello(): print("Hello world!") r = yield from asyncio.sleep(1) print("Hello agagin!") loop = asyncio.get_event_loop() #执行协程(coroutine) loop.run_until_complete(hello()) loop.close() #@asyncio.coroutine把一个generator标记为coroutine类...
# -*- coding:utf-8 -*- import pandas as pd from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py # import visuals as vs def get_data(show=False): # Pretty display for notebooks # matplotlib inline # Load t...
name = input("Wie heist du?\n\n" + "Name :") name = name.lower() #macht das groß und kleinscreibung egal ist solange "arvid" if name in ("arvid"): #andere möglichleiten sind; #("arvid", "Arvid"): #if name == ("arvid") or name == ("Arvid"): print ("\nOk " + name + "," + "\n" + "Ich würde sie gerne besträuseln ...
''' Created on 11/27/2015 @author: jj1745 The module where we read and process user inputs. ''' import sys from league import * from loader import processData def getAllTeams(): ''' get all teams that have played in the last 5 seasons in the premier league @return: the set of teams ...