text
stringlengths
37
1.41M
from threading import Thread, Lock class WordExtractor: INVALID_CHARACTERS = ["'", ",", ".", "/", "?", ";", ":", "(", ")", "+", "*", "[", "]", "{", "}", "&", "$", "@", "#", "%", "\"", "|", "\\", ">", "<", "!", "=", "(", ")", "`"] NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] HIFEN = "-" ENCODING =...
# encoding: utf-8 __author__ = 'liubo' """ @version: @author: 刘博 @license: Apache Licence @contact: ustb_liubo@qq.com @software: PyCharm @file: cat_dog_deque.py @time: 2016/6/1 23:39 """ from Queue import Queue def func(): pass class Pet(): def __init__(self, type): self.type = type class Cat(Pe...
# encoding: utf-8 __author__ = 'liubo' """ @version: @author: 刘博 @license: Apache Licence @contact: ustb_liubo@qq.com @software: PyCharm @file: stack_sort.py @time: 2016/6/9 16:37 """ def stack_sort(stack): ''' :param stack: 需要排序的栈 利用一个辅助栈完成栈的排序 ''' pop_num = 0 stack_tmp = [] wh...
# -*- coding:utf-8 -*- __author__='liubo' class Node(object): def __init__(self, value, pre=None, next=None): self.data = value self.next = pre self.prev = next class LinkList(object): def __init__(self): self.head = None self.length = 0 def __getitem__(self, ke...
#!/usr/bin/python # -*- coding: utf-8 -*- height = 1.82 weight = 74.5 bmi = weight/(height*2) print('BMI = %.2f' %bmi) if bmi < 18.5: print('低于18.5:','过轻') elif bmi >= 18.5 and bmi < 25: print('18.5-25:','正常') elif bmi >= 25 and bmi < 28: print('25-28:','过重') elif bmi >= 28 and bmi < 32: print('28-32:',...
""" Scientist stores DNA information in the database Each record will be a binary number All binary numbers will have same number of bit sets These numbers can have many digits, but may have relatively few bit sets To save space they are stored using the compression scheme: - instead of storing...
""" Given a string s containing digits, return a list of all possible valid IP addresses that can be obtained from the string. Note: The order in which IP addresses are placed in the list is not important. A valid IP address is made up of four numbers separated by dots ., for example 255.255.255.123. Each number falls ...
""" A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. The next permutation of an array of integers is the next lexicographically ...
""" The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] an...
def add_it_up(n): sum = 0 if n <= 0: return sum else: return sum + n + add_it_up(n-1) print(add_it_up(100 )) # 1,2,3,4,5,6,7,8,9,10
""" Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. Example 1: Input: nums = [2,1,2] Output: 5 Example 2: Input: nums = [1,2,1] Output: 0 Constraints: 3 <= nums.leng...
class Solution(object): def sortByBits(self, arr: list[int]) -> list[int]: def count_bit(num): count = 0 while num > 0: num, rem = divmod(num, 2) if rem == 1: count += 1 return count new_list = [(count_bit(num)...
""" Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse ...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ''' input data --> wieght --> hidden layer 1 --> weights --> hidden layer 2 (activation funtion) --> weight --> output # Data is passed straight though Feed - Forward compare output to intended --> cost function(cross entropy) optimiza...
def quickSort(alist): quickSortHelper(alist, 0, len(alist) - 1) def quickSortHelper(alist, first, last): if first < last: splitPoint = partition(alist, first, last) quickSortHelper(alist, first, splitPoint-1) quickSortHelper(alist,splitPoint+1, last) def swap(alist, x, y): alist[x...
# O(logn) def binary_search(alist, item): start = 0 end = len(alist) - 1 found = False while start <= end and not found: middle = (end + start)//2 if alist[middle] == item: found = True elif alist[middle] < item: start = middle + 1 elif alist[midd...
import math class Vector: def __init__(self, x, y): self.x = x self.y = y def setxy(self, x, y): self.x = x self.y = y def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __add__(self, other): return Vector(self.x + other.x...
# from spellchecker import SpellChecker # # spell = SpellChecker() # # # find those words that may be misspelled # misspelled = spell.unknown(['Alberto', 'Jose', 'Debes', 'Selman', '930', 'Spring', 'St', 'NW', 'Apt', 'TI', 'Atlanta,', 'GA', '3Iberto.j.debes@gmail.cor']) # # for word in misspelled: # # Get the one `...
#http://cs231n.github.io/python-numpy-tutorial/ #%% import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np x = np.linspace(0, 20, 100) plt.plot(x, np.sin(x)) plt.show() #%% def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if ...
import streamlit as st import os import nltk # nltk.download('punkt') #nlp pakages from textblob import TextBlob import spacy def text_analyzer(my_text): nlp=spacy.load("en") docx=nlp(my_text) all_data=[('"token":{},\n "Lemma":{}'.format(token.text,token.lemma_)) for token in docx ] return all_data d...
# 2015-04-04 recursively:85 ms iteratively:53 ms # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): ...
# 2015-05-21 # Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] ###########DFS Runtime: 204 ms############## class Solution: # @param node, a undirected graph node # @return a undirected graph node def c...
# 2015-06-04 Runtime: 56 ms # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} n # @return {ListNode} def removeNthFromEnd(self, head, n): dummyHead =...
# 2014-01-18 Runtime: 58 ms class Solution: # @param num, a list of integers # @return a string def largestNumber(self, num): num = [str(i) for i in num] # what's this lambda function? for input string x, y # if x + y > y + x, return -1 # if x + y < y + x, return 1 ...
# 2015-06-26 Runtime: 172 ms # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def con...
import numpy as np import matplotlib.pyplot as plt ################################### # Clustering ################################### class kMeans(): def __init__(self, k, random_state = 123): self.k = k self.random_state = random_state self.cluster_centers = None def _update_cl...
#CustomNeuralNetwork.py import numpy as np import pandas as pd #Activation function: f(x) = 1/(1+e^(-x)) def sigmoid(x): return 1/(1+np.exp(-x)) #Derivate of sigmoid function def deriv_sigmoid(x): fx = sigmoid(x) return fx * (1 - fx) class Neuron: def __init__(self, weights, bias): self.weights = weights ...
# -*- coding: utf-8 -*- import requests import json # GET request # res is a Response object, which contains a server's response to an HTTP request. res = requests.get('https://api.github.com/events') #print(res.text) # get a str object # print(res.content) # get a bytes object #print(res.encoding) # print(res.json...
# -*- coding: utf-8 -*- import re line_number = 0 # Regular Expression # \w => Matches Unicode word characters [a-zA-Z0-9_] # [] => to indicate a set # [\w-] => any word char and char '-' # [\w-]+ => any word composed by word chars and '-' custList = [] with open('data/20161121134754-RCHMA-utf8.txt', encoding='utf...
# -*- coding: utf-8 -*- # import urllib.request from http.client import HTTPConnection from urllib.request import urlopen HTTPConnection.debuglevel = 1 a_url = 'http://www.diveintopython3.net/examples/feed.xml' # urllib.request.urlopen(a_url) => return a file-like object # that you can just read() from to get the...
class User: def __init__(self, name, login, password, role): self.__name = name self.__login = login self.__password = password self.__role = role self.__is_blocked = False def getName(self): return self.__name def getLogin(self): return self.__login...
from abc import ABC, abstractmethod class Car(ABC): """ Стандартный автомобиль со скоростью в километрах. """ @abstractmethod def set_speed(self, speed: float): pass @abstractmethod def get_speed(self) -> float: pass class CarMiles(ABC): """ Нестандартный автомобил...
# creating an empty list people = [] # creating a dictionary to store person details person = { 'first_name': 'ibby', 'last_name': 'blaq', 'age': '20', 'city': 'dsm' } person = { 'first_name': 'icon', 'last_name': 'man', 'age': '22', 'city': 'new city' } people.append(person) person ...
def make_shirt(size='large',message='I love python'): # summarize the shirt that is gonna be made print(f"\nI'm gonna make a {size} T-shirt.") print(f"Tha's gonna say {message}") # calling the make_shirt function make_shirt() make_shirt(size='medium') make_shirt(message='Python for life baby!', size='extr...
# chnaging cases of the string name = 'Ibrahim' print(name.upper()) print(name.title()) print(name.lower()) print() # quotetion print('Albert Einstein once said, “A person who never made a mistake never tried anything new.”') print() ####################### famous_person = 'Albert Einstein' quote = f'{famous_person...
favorite_places = { 'eric': ['bear mountain', 'death valley', 'tierra del fuego'], 'maulin': ['hawaii', 'iceland'], 'john': ['mt. verstovia', 'the playground', 'new hampshire'] } for person, places in favorite_places.items(): print(f'\nMy friend {person.title()} like:') for place in places: ...
numbers = [] for threes in range(3,30,3): numbers.append(threes) print(numbers)
name = 'Ibrahim' # the letter f used to insert variable values to a string message = f'Hello, {name} would you like to learn some python today?' print(message) print()
invited = ['mom','dad','kids'] # print a message for individual print(f"Hey! {invited[0].title()}, I'm having a dinner at my place tonight. You're invited.") print(f"Hey! {invited[1].title()}, I'm having a dinner at my place tonight. You're invited.") print(f"Hey! {invited[2].title()}, I'm having a dinner at my place ...
usernames = [] if usernames: for username in usernames: if (username == 'admin'): print('Hello admin, there is a report status.') else: print(f'Hello {username}, thanks for logging in again') else: print("We need some users.")
# list of favourite animals/pets # but i don't real like animals at all. fav_animals = ['dog','cat','lion'] for pet in fav_animals: print(f"I like {pet} 'cause I like it.") print() print("I'm not a fan of pets. goddamnit!")
list=[2,3,4,1,5,6] '''if 4 in list: print("yes") if 10 in list: print("yupp") else: print("no")''' for x in range(len(list)): print(x,end="we") print("") #print(list[x])
class Plant: pass plant = Plant() print(plant) print(isinstance(plant, Plant)) print(isinstance(plant, object)) class BreedingPlant(Plant): pass class WildPlant(Plant): pass breedingPlant = BreedingPlant() wildPlant = WildPlant() print(breedingPlant) print(isinstance(breed...
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Exam...
""" Implement int sqrt(int x). Compute and return the square root of x. If x is not a perfect square, return floor(sqrt(x)) Example : Input : 11 Output : 3 DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY """ class Solution: # @param A : integer # @return an integer def sqrt(self, A): if A == 1...
""" Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details. Example: Input: 1 2 3 4 5 6 7 8 9 Return the following : [ [1], [2, 4], [3, 5, 7], [6, 8], [9] ] Input : 1 2 3 4 Return the following : [ [1], [2, 3], [4] ] """ class Solution: # @param a...
""" Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. """ from list_node impo...
# Review the following link for the question prompt: https://www.algoexpert.io/questions/Group%20Anagrams # O(N + N * mlog(m)) time | O(N) space def groupAnagrams(words): memory = {} for anagram in words: sorted_anagram = ''.join(sorted(anagram)) if sorted_anagram in memory: memory[sorted_anagram].append(a...
# Review the following link for the question prompt: https://www.algoexpert.io/questions/Branch%20Sums # Time Complexity: O(N^2 + m) # Space Complexity: O(N + m) def patternMatcher(pattern, string): if len(string) < len(pattern): return [] newPattern = getNewPattern(pattern) didSwitch = pattern[0] == 'y' ...
# coding=utf-8 """ A robot is located at the top-left corner of an A x B grid (marked ‘Start’ in the diagram below). Path Sum: Example 1 The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below). How many...
# Review the following link for the question prompt: https://www.algoexpert.io/questions/Three%20Number%20Sum # Solution 1 - Brute Force # Time Complexity - O(n^3) # Space Complexity - O(1) # Solution 2 - Sort values and iterate # Time Complexity - O(n^2) # Space Complexity - O(n) def threeNumberSum(array, targetSum)...
# Review the following link for the question prompt: https://leetcode.com/problems/validate-binary-search-tree/ # O(N) time | O(d) space # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.righ...
import pygame from pygame.sprite import Sprite class Ship(Sprite): # Clase que gestiona las configuraciones de la nave def __init__(self, ai_settings, screen): super().__init__() self.screen = screen self.ai_settings = ai_settings # Carga la imagen de la nava y obtiene su rectáng...
savings = 100 growth_multiplier = 1.1 print("Enter number of years you want to save") numberOfYears = int(input()) i = 1 while i < numberOfYears: yearY = savings*growth_multiplier savings = yearY i += 1 totalSum = yearY print("Din totala summa blir: "); print(totalSum)
maternos= input("Inserte Genes maternos: ") paternos= input("Inserte Genes paternos: ") cadena_adn= input("Inserte cadena ADN: ") mami=0 papi=0 CGA_validacion = "" for letra in cadena_adn: for letraX in maternos: if letraX == letra: mami = mami + 1 for letra in cadena_adn: for letraY in paternos: if ...
""" :Module Name: **log** ======================= This module contains the classes for log handling """ import logging import os import time class LogHandler(logging.FileHandler): """ LogHandler class is for handling logs generation and log file path generation """ def __init__(self, logdirec...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): current_node = self.head while(current_node): print(current_node.data) current_node = curren...
# Program to find how many times the sorted array is rotated def find_rotation_count(arr,length): first,last = 0,length-1 while(first<=last): if(arr[first]<=arr[last]): return first #sorted #case:1 mid = (first+last)//2 prev,next = (mid+length-1)%length,(mid+1)%length ...
def fibonacci(n): a = 0 b = 1 while (a <= n): yield a a, b = b, a+b for i in fibonacci(99999999999999999999999999): print(i)
#pickandshowRev1_LScroggs.py #this program allows user to pick and display a pre-selected image #10/19/2017 #JES print("Image Select\n") prompt = raw_input("Would you like to select an image? ") prompt = prompt.lower() if prompt == "yes": print("please select") else: sys.exit() def main(): ...
class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return self.__next def set_next(self,next_node): ...
#DSA-Assgn-7 #This assignment needs DataStructures.py file in your package, you can get it from resources page from src.DataStructures import LinkedList def remove_duplicates(duplicate_list): list1=[] temp = duplicate_list.get_head() while temp is not None: list1.append(temp.get_data())...
#DSA-Assgn-4 class Player: def __init__(self,name,experience): self.__name=name self.__experience=experience def get_name(self): return self.__name def get_experience(self): return self.__experience def __str__(self): return(self.__name+"...
#OOPR-Assgn-18 class Customer: def __init__(self,customer_name): self.__customer_name = customer_name self.__payment_status = None def get_customer_name(self): return self.__customer_name def get_payment_status(self): return self.__payment_status def pays...
''' Created on Sep 20, 2018 @author: jatin.pal ''' def encode(message): result = "" oldL = message[0] count = 1 for i in range(1,len(message)): if(message[i] == oldL): count +=1 else: result += str(count) + oldL oldL = message[i] ...
#task 1 import numpy as np old = np.array([[1, 1, 1], [1, 1, 1]]) new = old new[0, :2] = 0 print(old) #task 2 old = np.array([[1, 1, 1], [1, 1, 1]]) new = old.copy() new[:, 0] = 0 print(old)
''' PROJECT 8 - Graphs Name: Clare Kinery ''' import random def Generate_edges(size, connectedness): """ DO NOT EDIT THIS FUNCTION Generates directed edges between vertices to form a DAG :return: A generator object that returns a tuple of the form (source ID, destination ID) used to co...
import re import sys from datetime import datetime class nudb: #method save() to insert entries into the database def __init__(self): self.log_fh = open('logs/log.txt','a') def save(self,object): ''' This method saves the entries into the database use case: 1)If you want to save a single a...
# Import everything from tkiner. from tkinter import * root = Tk() def clik_zero(): greeting = "Hello "+ entry_zero.get() + "!" label_zero = Label(root, text=greeting) label_zero.pack() # Creating of an entery. entry_zero = Entry(root, width=50, borderwidth=10, bg="#dedede", fg="#004f3b") # Pack ...
# coding: utf-8 # author: RaPoSpectre # time: 2016-09-20 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def system_change(self, l3): pp = l3 while True: if l3.val >= 10: ...
from abc import abstractmethod import Algorithms from Core import LOGGER logger = LOGGER.attach(__name__) class Player(): @staticmethod def create_player(args): if (args["type"].upper() == "HUMAN"): logger.info("Creating Human " + args["colour"]) return Human(args[...
# Project : Quiz Game print("Welcome to Computer Quiz Game!") playing = input("Do you want to Play? ") if playing.lower() != "yes": quit() print("Okay! Let's play! \n") score = 0 # Question 1 answer = input("What does CPU stands for? ") if answer.lower() == "central processing unit": print('Correct!') ...
import random d={8:37,38:9,11:2,13:34,40:64,65:46,52:81} p=random.choice([2,8,9,13,40,65,52]) print("You got... ",p) if p in d: if p>d[p]: print("Oops a Snake") else: print("Climb the ladder") print("you can go to",d[p])
# 예제 3. 4변수함수 f(w,x,y,z) = wx + xyz + 3w + zy^2를 미분하여 ## f'(1.0, 2.0, 3.0, 4.0)의 값을 구하여라. import numpy as np def numerical_derivative(f, x) : delta_x = 1e-4 grad = np.zeros_like(x) it = np.nditer(x, flags=["multi_index"],op_flags=["readwrite"]) while not it.finished : idx = it.mu...
""" # Derivative : 미분 f'(x) = df(x) / dx x가 변할 때, f(x)가 얼마나 변하는 지를 구하는 것 f(x)가 입력 x의 미세한 변화에 얼마나 민감하게 반응하는 지 알 수 있는 식 # 머신러닝 / 딥러닝에서 자주 사용되는 함수의 미분 (1) f(x) = a (a는 상수) / f'(x) = 0 (2) f(x) = ax^n (a는 상수) / f'(x) = nax^n-1 (3) f(x) = e^x / f'(x) = e^x (자기자신) (4) f(x) = ln x / f'(x) = 1 / x (5) f(x) = e^(...
def generar_lista_con_saltos(tamanio_listas,salto_entre_elemento,lista): if type(lista) not in [list]: raise TypeError("se espera una lista en el parametro lista para generar una lista con saltos") if type(tamanio_listas) not in [int]: raise TypeError("se espera un entero") if type(salto_ent...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Administrator' #字符统计,统计文本中除空格以外的字符数目 with open("hh.txt", 'r') as f: res = 0 res1 = 0 for line in f: res1 +=1 for word in line.split(): res +=len(word) print res1, res '文件过滤,显示一个文件的所有行,忽略#开头的行' with open('hh.txt','r') a...
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 20:18:00 2020 @author: Ercan Karaçelik """ def linear_search(item,my_list): i=0 found=False while i<len(my_list) and found==False: if my_list[i]==item: found=True else: i+=1 return found ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 28 14:04:34 2020 @author: Ercan Karaçelik """ #Dictionaries, Zip Command, Matplotlib lorem_ipsum=""" What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever ...
# -*- coding: utf-8 -*- """ Created on Wed Apr 1 09:56:49 2020 @author: Ercan Karaçelik """ # CLASS # naming class and function # my_function # MyClass class Patience(object): ''' Class Definition''' status='patience' def __init__(self,name,age): self.var_name=name ...
shoppingList = [] # This item shows how to navigate the app. def show_help(): print("Welcome the shopping app.") print(""" --------------------------------------------- SHOW - Show All Items currently on the list DONE - Finish the list and exit out of the app. HELP - Show this line. UPDATE - Updates an item ...
''' 1.산술 연산자 + - * / : 두값을 나눈 결과를 반환(실수 값) // : 두 값을 나눈 결과의 몫 반환(정수 값) % : 두 값을 나눈 결과의 나머지 반환 ** : 거듭 제곱의 결과 바환 == : 두 피 연산자 값을 비교하여 동일하면 True, 동일하지 않으면 False 예) 3==3 (True) , 3==4(False) != : 두 피 연산자 값을 비교하여 동일하면 False, 동일하지 않으면 True(연산자 '=='와 반대개념) > : 두 피 연산자 값을 비교하여 왼쪽의 값이 크면 True, 그렇지 않으면 False < : ...
""" 산술연산자 의미 = 대입 연산자 + 더하기 - 빼기 * 곱하기 / 나누기 // 나누기(몫) ★ % 나머지 구하기★ ** 제곱 """ ''' num1=9;num2=2 print(num1,'+',num2,'=',num1+num2) print(num1,'-',num2,'=',num1-num2) print(num1,'*',num2,...
s = '''import java.util.*; public class BrainyThings { public static void main(String[] args) { Integer[] a = {1, 4, 2, 3, 5}; List<Integer> l = Arrays.asList(a); System.out.println(l); System.out.println(Arrays.toString(a)); l.set(2, 8); System.out.println(l); System.out.print...
#!/usr/bin/python3 #This function return integer in [a, b] range def input_int(a, b): print("Please enter the number in [{}, {}] range".format(a,b)) while True: print(">", end=' ') x = input() if x.isdigit(): if(int(x) >= a and int(x) <= b): return x else: print("Only in [{}, {}] range. Try more...
#!/usr/bin/python3 def find_nonpaired(digits): ''' x, y, flag - 3 variables; for x ... & for y ... - 2 loops res[] - only to return answer from function, so if we rewrite it as one plain function we don't need it ''' res = [] for x in range(0, len(digits)): flag = False for y in range(0, len(digits))...
daftar1 = input("Masukan daftar belanja 1 : ") daftar2 = input("Masukan daftar belanja 2 : ") tambah_daftar1 = input("Tambahkan data ke daftar belanja 1 : ") tambah_daftar2 = input("Tambahkan data ke daftar belanja 2 : ") daftar_belanja1 = [daftar1, tambah_daftar1] daftar_belanja2 = [daftar2, tambah_daftar2] print("D...
class Stock(object): def __init__(self, stockName, basicHistoricalData, fibonacciNumbers, strategies, links): self.stockName = stockName self.basicHistoricalData = basicHistoricalData self.fibonacciNumbers = fibonacciNumbers self.strategies = strategies self.links = links cl...
import string import random wordlist = 'wordlist.txt' #Choosing length of word for game def get_random_word(length_of_word): words = [] with open(wordlist, 'r') as f: for word in f: if '(' in word or ')' in word: continue word = word.strip().lower() ...
# Script that gets the mood of user on a scale of 1 - 10. # Program runs on startup of computer, therefore this mostly # represents morning mood. Write 'plot' to plot the graph. import matplotlib.pyplot as plt mood = input("Enter your mood on a scale of 1-10: ") if mood == "plot": with open("moods.txt") as read_f...
import random a=int(input('じゃんけんぽん 0=グー、1=チョキ、2=パー')) b=random.randint(0,2) c='グー' if b==1: c='チョキ' if b==2: c='パー' print('CPUの手は',c,'でした') if a==0: if b==0: print('あいこ') elif b==1: print('勝ち!') elif b==2: print('負け……') if a==1: if b==0: print('負け……') elif ...
import os def loadCiphers(): pathToFile = input('Enter path to the .txt file with ciphertexts split per line:') if pathToFile == "": loadCiphers() if os.path.exists(pathToFile) == False: print('File wasn\'t found') loadCiphers() with open(pathToFile, 'rb') as file: te...
# insertion sort def insertion_sort(A): for j in range(1, len(A)): key = A[j] # 将A[j]插入到A[0:j]已排序的数组中 i = j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i] i -= 1 A[i + 1] = key return A A = insertion_sort([5, 2, 4, 6, 1]) print(...
# 基本栈结构 class stack: def __init__(self): self.data = [0 for _ in range(16)] self.top = -1 def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def stack_empty(S): if S.top == -1: r...
# This script accepts a data file in json form containing pairs of friends in a social network and outputs asymmetric friendship pairs using MapReduce import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not mo...
t = int(input()) while t: x = int(input()) y = 1 for i in range(1,x+1): y = y*i print(y) t = t-1
""" r 讀取模式 r+ 讀寫模式 w 寫入模式。如果該檔案不存在,將建立一個新檔案。如果檔案存在,則會被覆蓋。 w+ 讀寫模式。如果該檔案不存在,將建立一個用於讀寫的新檔案。如果檔案存在,則會被覆蓋。 a 追加模式。新資料將寫在檔案末尾。如果該檔案不存在,將建立一個用於寫入的新檔案。 a+ 追加和讀寫模式。新資料將寫在檔案末尾。如果該檔案不存在,將建立一個用於讀寫的新檔案。 #readlines() 會把整個檔案讀出來第i行放在line[i] #readline() 讀出一行(\n)第i個字放在line[i] #readline(3) 讀出三個字第i字放在line[i] """ import os,time MaxLine=10...
import csv # csv_file=csv.reader(open('stu_info.csv','r')) # print(csv_file) # # for stu in csv_file: # print(stu) stu=['Marry',28,'ChangSha'] stu1=['XiaoNan',31,'ChengDu'] out=open('stu_info.csv','a',newline='') csv_write=csv.writer(out,dialect='excel') csv_write.writerow(stu) csv_write.writerow(stu1) print('W...
class Student(): def __init__(self,name,city): self.name=name self.city=city print('My name is %s and come from %s'%(name,city)) def talk(self): print('Hello World!') stu1=Student(input('请输入'),input('请输入城市')) stu1.talk()
#Exercício Python 071: Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: #considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. print(...