text
stringlengths
37
1.41M
# Import the required module for text # to speech conversion from gtts import gTTS #from playsound import playsound as ps # This module is imported so that we can # play the converted audio import os import pygame # The text that you want to convert to audio def play_audio(mytext): # Language in which you wa...
#Mohtasim Howlader, Aleksandra Koroza: Team Bitelguese #SoftDev1 pd8 #K16 -- No Trouble #2018-10-05 import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O DB_FILE="discobandit.db" #delete before every subsequent run db = sqlite3.connect(DB_FILE) #open if file exists, otherwise...
n=int(input(">")) for j in range(n): for k in range(n): print(" "*(n-1-j),end="") for i in range(j+1): print("/"+"\\",end="") print(" "*(n-1-j),end="") print() print("-"*(n*n*2)) for j in range(n-1,-1,-1): for k in range(n): print(" "*(n-1-j),end="") ...
n=int(input(">")) print(str(1)*(n-1)+str(2)) for i in range(n-2): print(str(4)+" "*(n-2)+str(2)) print(str(4)+str(3)*(n-1))
class Solution(object): def isMatch(self, s, p): sl = len(s) pl = len(p) dp = [[False for i in range(pl+1)] for j in range(sl+1)] s = " "+s p = " "+p dp[0][0]=True for i in range(1,pl+1): if p[i] == '*': dp[0][i] = dp[0][i-1] for i in ra...
n=int(input(">")) for i in range(n): for j in range(n): print(str((j+1+n*i)%10),end="") print()
while True: n=int(input(">")) for k in range(5): for j in range(5): for m in range(n): for i in range(n): if (k==0 or k==2 or k==4 or (k==1 and m==n-1) or (k==3 and m==0)) and (j==0 or j==2 or j==4 or (j==1 and i==n-1) or (j==3 and i==0)): ...
n=int(input(">")) for i in range(n): print(" "*(n-1)+str(1)+" "*(n-1),end=" ") print() for j in range(n-2): for i in range(n): print(" "*(n-2-j)+str(2+j)+" "*(2*j+1)+str(2+j)+" "*(n-2-j),end=" ") print() for i in range(n): print(str(n)*(1+2*(n-1)),end=" ")
def getList(): msglist = [] file = open('input', 'r') for line in file: msglist.append(line) return msglist def lettersCounter(msg): letterlist = {} for letter in msg: if letter in letterlist: letterlist[letter] += 1 else: letterlist[letter] = 1 ...
#recursive function def fibonacci(n): if n==1: return 1 elif n==2: return 1 elif n>2: return fibonacci(n-1) + fibonacci(n-2) for n in range(1,100): print(fibonacci(n))
# class variables # variables shared among all the instances of a class # instance variables can be unique like name,email and pay # class variables should be same for all instances class Employee: no_of_emp = 0 raise_amount = 1.05 def __init__(self,first,last,pay): self.first = first self.last = last self.p...
# You are given an m x n integer grid accounts where accounts[i][j] is the amount # of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. # A customer's wealth is the amount of money they have in all their bank accounts. # The richest customer is ...
#Largest number in a list import random a = [] for i in range(0,4): a.append(random.randrange(-100,101)) n = len(a) temp = 0 print(a) for count in range(0,n): swap = 0 print("Step-",count+1) for i in range(0,n-1): print("Iteration-",i+1,"of step-",count+1) if a[i]>a[i+...
n = int(input("Enter number of elements: ")) l1 = [] for i in range(1,n+1): l1.append((i,i**2,i**3)) print(l1) l2 = ["Vaibhav","Rai","Python","coding","!"] print(l2) l2.sort(key = len) print(l2)
def set_global_var(): ''' Объявление глобальной переменной внутри функции ''' global z z = 'Try set global value into function' def set_scope_fun_var(): ''' Изменение переменной внешней функции ее подфункцией ''' car = 'Toyota' def set_name(): nonlocal car car = "BMW" ...
# 절댓값(abs) num_integer=[-3, -2, -1, 0, 1, 2, 3] num_natural= list(map(abs,num_integer)) print("a list consists of integer", num_integer) print("can change by applying abs func to natural numbers", num_natural) # all and any # can check out if there is True or False type all_true= [1, 2, 3] any_false= [0, 2, 3, 3] prin...
def qcut(x, n): """ The function to discretize a numeric vector into n pieces based on quantiles Parameters: x: A numeric vector. n: An integer indicating the number of categories to discretize. Returns: A list of numeric values to divide the vector x into n categories. Example: qcut(range(...
# -*- coding: utf-8 -*- """ Activation Functions """ import numpy as np import matplotlib.pylab as plt def step(x): return np.array(x > 0, dtype=np.int) def sigmoid(x): return 1 / (1 + np.exp(-x)) # 0 & 1 def relu(x): return np.maximum(0, x) def tanh(x): ...
primes = [2] i = 3 while len(primes)<10002: for x in primes: if i % x == 0: i += 1 break else: primes.append(i) i += 1 print(primes[10000])
import time initial = time.time() answer = 0 number = 1 while answer == 0: if sorted(str(number * 2)) == sorted(str(number)): if sorted(str(number * 3)) == sorted(str(number)): if sorted(str(number * 4)) == sorted(str(number)): if sorted(str(number * 5)) == sorted(str(number)): ...
#Find the largest palindrome made from the product of two 3-digit numbers. product = 1 for i in range(1,1000): for j in range(1,1000): test = str(i * j) reverse = '' for k in range(-1,-len(test)-1,-1): reverse = reverse + test[k] if test == reverse: if int(tes...
import re def doubles(s): res=''.join(c.group() for c in re.finditer(r'(.)\1|.', s) if len(c.group())==1) return doubles(res) if res!=s else res
def sum_of_threes(n): powers = [] while n > 0: if n == 2: return 'Impossible' res = gen_power(n); n -= pow(3, res) powers.append(res) return '+'.join('3^'+str(p) for p in powers) \ if len(set(powers)) == len(powers) else 'Impossible' def gen_power(lim,...
from string import ascii_lowercase as AL def caesar(pt,shift): al = AL[shift:] + AL[:shift] return pt.translate(str.maketrans(AL+AL.upper(), al+al.upper()))
from itertools import combinations_with_replacement as cwr def palindrome(num): if not isinstance(num, int) or num < 0: return "Not valid" num = str(num) return search(num) if len(num) > 1 else False def search(s): for i,j in cwr(range(len(s)+1), 2): check = s[i:j] if len(check) > 1 a...
def is_pangram(string, alphabet = 'abcdefghijklmnopqrstuvwxyz', recurring = False): if alphabet == "": return True if recurring: string = string.lower() search_char = alphabet[0] if search_char in string: new_alphabet = alphabet[1:] new_string = string.replace(search_cha...
#Median in a stream of integers (running median) #http://www.geeksforgeeks.org/median-of-stream-of-integers-running-integers/ ''' 5 > 5 5, 15 > 10 5, 15, 1 > 5 5, 15, 1, 3 > 4 ''' #Modified insertion sort #go left: if the new value at index left is < val at index left-1 def insertionSort(a,left): while left > 0 and...
''' Linked List Libraries class LLNode: def __init__(self,data): self.data = data self.next = None ''' #Print Linked List def PrintLinkedList(list): while list is not None: if list.next is not None: print(list.data,end=" -> ") else: print(list.data,end="\n") list = list.next #Add to end of li...
''' Design Elevator system using Object Oriented Programming Concepts OO Concepts: 1. Encapsulation: Binding code and data it manipulates and keeping it safe from misuse. Variables here are private 2. Polymorphism: Many forms in Greek. Using an operator or function in different ways for different data input. 3. Inher...
#Merge Sort ''' ALGORITHM: 1. Comparison based 2. Divide and conquer algorithm 3. Merge sort recursively splits a list in half and merges the results NOTES: 1. STABLE - can be modified to retain order of same values 2. NOT in place sorting 3. EXTRA space is needed to hold two halves. 4. Requiring additional space is...
''' Remove duplicate values & retain order of existing values ''' class LinkedListNode: def __init__(self,data): self.val = data # contains the data self.next = None # contains the reference to the next node #Print Linked List def PrintLinkedList (node): while node is not None: print(node.val,en...
#Given random numbers. Find length of Longest Increasing Subsequence (LIS) and the sequence. # REFERENCE: # 1. https://github.com/mission-peace/interview/blob/master/src/com/interview/array/LongestIncreasingSubSequenceOlogNMethod.java # 2. https://www.youtube.com/watch?v=S9oUiVYEq7E # # NOTES: # 1. Keep track of index...
''' Question: Find the max value of the binary tree Algorithm: 1. Recursively traverse the tree 2. Recursive function take node and max value computed so far and returns new max value ''' import sys sys.path.append("./mylib") import Tree #Recursive traversal def MaxValue(root,maxvalue): if (root.data > maxvalue):...
#Question: Test if a string is a Palindrome. Ignore all non-alphanumeric characters. #Source: Section 7.3, Elements of Programming Interviews #Answer: #Solution 1 #Limitations: # 1. Does not handle non-alphanumeric characters # 2. Not efficient since entire string is reversed for comparison #n = "racecaR" #if n.lo...
''' Question: Given an array of integers, write a functions that returns true if there is a triplet (a,b,c) that satisfies a^2 + b^2 = c^2 Exmaple: [1,2,4,5,-3] 4^2 + -3^2 = 5^2 ''' #Time complexity::O(n^3) #Solution 1: def Solution1(input,ilength): for i in range(0,ilength): for j in range(1,ilength): ...
#Check if a number is a happy number ''' SOURCE: https://leetcode.com/problems/happy-number/ A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will st...
#Given a string and limit provide line breaks based on even distribution of empty spaces #AKA Best arrangement to provide even distribution of empty spaces #Text justification ''' NOTES: Even distribution factor (Badness factor or Cost factor): Square of empty spaces in every line. Example: 3 empty space on one line ...
''' Question: Implement a max queue using a linked list ''' ''' NOTES input max 1 1 1,2 2 1,2,5 5 -- 5 5 3 5,3 5,3,3 5,3,3 1. max values are in descending order! 2. dequeue all values less than new value ''' def...
#Sort a string of printable characters (BUCKET SORT) ''' 1. 256 ASCII characters. This includes standard ASCII characters (0-127) and Extended ASCII characters(128-255). 2. 95 printable characters in ASCII characters in range 0 - 127 3. ord('a') converts a character to corresponding ASCII value (int) 4. chr(40) c...
''' Question: Design an algorithm for computing the k-th largest element in a sequence of elements. It should run in O(n) expected time where n is the length of the sequence, which is not known in advnance. The value of K is known in advance. Your algorithm should print the k-th largest element after the sequence has ...
''' Question: Find the min value of two unsorted lists ''' a = [6,3,4,8] b = [9,4,10,3] #Step 1: Iterate through both the list and find the intersection #c = [val for val in a if val in b] #simple generator! c = [x for x in a and b] #Step 2: Iterate through the intersection to find the min min = c[0] for x in range(...
''' How many different 10-digit numbers can be formed starting from 1? The constraint is that the movement from 1 digit to the next is similar to the movement of the Knight in a chess game. Reference: http://stackoverflow.com/questions/2893470/generate-10-digit-number-using-a-phone-keypad ''' def initialize(): tabl...
#Introduction to heapq library import heapq input = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] print ("input >>>", input) #Min Heap (DEFAULT) heapq.heapify(input) print ("input after min heap >>>", input) #Max Heap heapq._heapify_max(input) print ("input after max heap >>>", input)
''' Double Linked List introduction ''' class LLNode: def __init__(self,data): self.val = data # contains the data self.next = None # contains the reference to the next node self.prev = None #Print Linked List def PrintLinkedList (node): a = [] while node is not None: print(node.val,end=" ") if (no...
'''Binary Tree Class and its methods''' class BinaryTree: def __init__(self, data): self.data = data # root node self.left = None # left child self.right = None # right child # set data def setData(self, data): self.data = data # get data def getData(self): return self.data # get left child of a ...
#Heap Library #Source: https://github.com/careermonk/DataStructureAndAlgorithmicThinkingWithPython/blob/ad9d11b94a6b06e32831afbcb520d07cd758d0da/src/chapter07priorityqueues/KthSmallestWithExtraHeap.py #Max Heap Implementation class MaxHeap: def __init__(self): self.heapList = [0] # index position 0 = 0 (SIMPLICITY...
''' Use BFS find all path between two edges. REFERENCE: 1. http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/ 2. https://www.cs.berkeley.edu/~vazirani/algorithms/chap4.pdf NOTES: 1. Breadth-first search visits vertices in increasing order of their distance from the starting point. 2....
''' Question: Swap two variable values without using additional space Solution: Use XOR Reference: http://betterexplained.com/articles/swap-two-variables-using-xor/ ''' x = 5 y = 9 print("x=%d,y=%d changed to " % (x,y),end="") x = x ^ y y = x ^ y x = x ^ y print("x=%d,y=%d" % (x,y))
#Find the largest rectangular area in a histogram ''' NOTES/OBSERVATION 1. Store index positions in stack 2. Stack has increasing values 3. If we arrive at a bar with height greater than top of stack, this may be the START of a max area rectangle so add to stack 4. If we arrive at a bar with height smaller stack ...
#Question: Find the height (max depth) of the binary tree ''' OBSERVATIONS: - Height is the number of nodes along the longest path from the root node down to the farthest leaf node - Height of a node = max(height of left sub-tree, right sub-tree) + 1 - Leaf node has height 1 http://stackoverflow.com/questions/133226...
#Generate all Numeronyms for a given string #Example: "careercup"=>"c7p","ca6p","c6up","car5p","ca5up","care4p"... def generateNumeronyms(a): size = len(a) S = 1 #start characters are fixed E = 1 #end characters are fixed N = size-S-E #max result = set() for n in range(N,0,-1): #print("aaa",n) #FRONT for ...
#Implement stack using linked lists #Source: https://github.com/careermonk/DataStructureAndAlgorithmicThinkingWithPython/blob/master/src/chapter04stacks/StackWithLinkedList.py # Node of a Singly Linked List class Node: # constructor def __init__(self): self.data = None self.next = None ...
#Spiral print matrix ''' input >>> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 NOTES: 1. Use 4 pointers to mark start end end of rows and columns rowStart = 0 rowEnd = 4 colStart = 0 colEnd = 4 2. Traverse until index pass each other - left 2 right - top 2 bottom - right...
''' Question: Given an input string and pattern find the minimum window in the input string that will contain all the characters in the pattern. ''' #Modified from: https://github.com/careermonk/DataStructureAndAlgorithmicThinkingWithPython/blob/ad9d11b94a6b06e32831afbcb520d07cd758d0da/src/chapter15stringalgorithms/Mi...
#Implement a function that inserts, deletes and getrandom in O(1) ''' Source: https://leetcode.com/problems/insert-delete-getrandom-o1/ // Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomSet.insert(1); // Returns false as ...
#Balanced Binary Tree: Add, Delete, isBalanced? class BalancedBinaryTree: def __init__(self,data): self.data = data self.left = None self.right = None def insertRight(self,node): self.right = node def insertLeft(self,node): self.left = node def height(node): if node is None: return 0 lheight = hei...
''' Question: Find min value of Binary Search Tree(BST) Min value is the left most leaf ''' class BinarySearchTree: def __init__(root, data): root.left = None root.right = None root.data = data def insertNode(root, node): if root is None: root = node else: if root....
#Determine if a Sudoko puzzle is valid #https://leetcode.com/problems/valid-sudoku/ ''' Sudoku Rules: 1. 9x9 grid 2. Numbers 1-9 appear once in each row 3. Numbers 1-9 appear once in each column 4. Numbers 1-9 appear once in each 3x3 Questions to ask: 1. Are there empty cells? 2. How are empty cells represented? 3. ...
''' Question: Given a list of meeting start and end times find #meetings that have conflict Source: http://stackoverflow.com/questions/27449948/schedule-optimization-in-python-for-lists-of-lists-interval-scheduling Notes: #Interval scheduling optimization is a standard problem with a greedy algorithm #The following g...
#Question: Given two binary trees, return true if they are structurally identical ''' OBSERVATION: * left and right sub-trees are arranged in the exactly same way (no value comparison) ''' import sys sys.path.append("./mylib") import Tree def CheckIdentical(t1,t2): #condition1: both nodes are empty if (t1 is No...
# coding=utf-8 from header import * class Graph(object): class AdjNode(object): def __init__(self, src, dst, cst=1): self.raiz = src self.destino_ver_dat = dst self.cost = cst self.next = None class AdjList(object): def __init__(self): ...
from random import randint rand_num = randint(0,5) if rand_num == 0: comp = 'rock' elif rand_num == 1: comp = 'scissors' elif rand_num == 2: comp = 'paper' elif rand_num == 3: comp = 'lizard' else: comp = 'spock' p2 = input('player move:\n').lower() print(f'comp - {comp}\n') if comp == p2: pr...
# -*- coding: utf-8 -*- """ Created on Mon Sep 7 20:41:00 2020 @author: 91852 """ import numpy import numpy as np np.random.randint(100, 1000) np.random.randint(100) #start and end can be mentioned np.random.randint(10, 1000) #multiple random nos. from same command #this is the new dataset which "Array" and sin...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/21 10:04 # @File : code.py # ---------------------------------------------- # ☆ ☆ ☆ ☆ ☆ ☆ ☆ # >>> Author : Alex 007 # >>> QQ : 2426671397 # >>> WeChat : Alex-Paddle # >>> Mail : alex18812649207@gmail.com # >>> Github : https://...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/20 8:29 # @File : code.py # ---------------------------------------------- # ☆ ☆ ☆ ☆ ☆ ☆ ☆ # >>> Author : Alex 007 # >>> QQ : 2426671397 # >>> WeChat : Alex-Paddle # >>> Mail : alex18812649207@gmail.com # >>> Github : https://g...
# draggable rectangle with the animation blit techniques; see # http://www.scipy.org/Cookbook/Matplotlib/Animations import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle class EditableRectangle(object): lock = None # only one can be animated at a time def __init__(se...
# draggable rectangle with the animation blit techniques; see # http://www.scipy.org/Cookbook/Matplotlib/Animations from matplotlib.patches import Rectangle class RectangleBasic(object): def __init__(self, rect_big, mu, nu, color_mu=None, color_nu=None, alpha=0.5): self.rect = ...
def mergeList( A, p, k, q ) : ##5. A[p]~A[k]와A[k+1]~A[q]를합병한다. # print ("...........", p, k, q, " : ", A) B = A[p:k+1] C = A[k+1:q+1] i = j = 0 t = p # print ("......before..........", B, " , ", C) while ( i < len(B) and j < len(C) ) : if ( B[i] <C[j] ) : A[t] = B...
# How to take user input in python: input_string = input('Enter your age: ') age = int(input_string) if age >= 18: print('You are an adult') elif age >= 13: print('You are a teenager') print('You will be an adult in', 18-age, 'years') else: print('You are a child')
# Variables: # Substituting names for specific values name = 'Suresh' age = 29 print(name) # same as print('Suresh') print(age) # same as print(29) # Benefit: we can reuse these names any number of times print(name, 'is', age, 'years old')
''' Most Booked Hotel Room Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z]. You are given a sequence of rooms, where + suggests room is booked, - room is freed. You have to find which room is booked maximum number of times. You may assume that the list describe a correct sequence of bookin...
# Define your Node class below: class Node: def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def set_next_node(self, next_node): self.next_node = next_node def get_next_node(self): return self.next_node def get_value(self): ...
'''License Key Formatting You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, exce...
#!/usr/bin/env python import sys nargs = len(sys.argv) if nargs < 3: print "Usage: python count_occurances.py <file> <string>" sys.exit(1) file = sys.argv[1] string = sys.argv[2] print "Searching <%s> for occurances of <%s>" % (file,string) contents = open( file, 'r' ).read() number = contents.count( s...
import os #使用套件 def read_file(filename): #"reviews.txt" data = [] #空的List count = 0 with open (filename, 'r') as f: for line in f: count += 1 #每讀取一筆count +1 data.append(line) if count % 10000 == 0: print(len(data)) print ("讀取完成...") print...
#!/usr/bin/python #coding=utf-8 import socket import sys import argparse host = 'localhost' def echo_client(port): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #第一个是只通过网络进行通信,第二个是TCP协议 server_address = (host,port) sock.connect(server_address) try: message = "This is the Test M...
from tkinter import * def button_clicked(): my_label.config(text=input.get()) window = Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) window.config(padx=50, pady=50) # Label my_label = Label(text="I am a label", font=("Arial", 24, "bold")) my_label.grid(column=0, row=0) my_lab...
# Enter your code here. Read input from STDIN. Print output to STDOUT from scipy import stats n=int(input()) arr = list(map(int, input().split())) # mean sum=0 for i in range(n): sum+=arr[i] m=sum/n mean=round(m,1) print(mean) #median med=arr.sort() x1=n//2 x2=x1-1 medi=(arr[x1]+arr[x2])/2 median=round(medi,1) ...
#!/usr/bin/env python3 class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] >>> sol = Solution() >>> sol.twoSum([2, 7, 11, 15], 9) [0, 1] """ table = dict() for index, ...
""" Merge sort Divide an conquer strategy: divide the list in two till we have the two smallest lists of one item, then merge sorted arrays Merging sorted is TH(n) and we do that log(n). So it is TH(n log()) Sorting is in place, but the code returns the array given. """ from math import inf def merge(items, p, q, ...
""" Given two string, check if one is permutation of the other """ def check(one, other): """ Using sorting ((a+b)log(a*b)) >>> check("abcda", "aadcb") True >>> check("abc", "bcd") False >>> check("a", "bc") False """ if len(one) == len(other): return sorted(one) == sor...
class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left...
x = 5.6 y = 5.2 p = 5 z ="chandrasekhar yadav" print(type(x)) print(type(y)) print(type(z)) print("here x is typecasting fload to int",int(x)) print("here int is casting as float",float(p)) print("x is casting as string",str(p))
# -*- coding: UTF-8 -*- # PROBLEMA: ESCRIBIR UN PROGRAMA QUE RECIBA NOMBRE Y EDAD Y DECIR # EN QUÉ AÑO EL USUARIO CUMPLIRÁ 100 AÑOS Nom=raw_input('Hola, cual es tu nombre? \n') print('Hola '+Nom+' !') x=int(input('Que edad tienes?')) y=int(input('En que año estamos?')) #y=año actual print('Entonces en el año '+str((...
# seat reservation code chairs = ['-','-','-','-','-','-','-','-','-'] print ("SEAT RESERVATION. '-' means available, 'x' means taken.") def printchairs(): counter = 0 for x in chairs: print (chairs[counter], end='') if x[0] == chairs[counter]: counter += 1 ...
import psycopg2 #from database import ConnectionFromPo from database import CursorFromConnectionFromPool class User: def __init__(self, email, first_name, last_name, id): self.email = email self.first_name = first_name self.last_name = last_name self.id = id def __repr__(self):...
from threading import Thread import time def do_work(start_no, end_no, result): sum = 0 for i in range(start_no, end_no): sum += i result.append(sum) while True: num = int(input("input number: ")) start = 0 end = num result = [] t1 = time.time() th1 = Thread(target=do_work, args=(start, int(en...
from tkinter import * import turtle import random def create_circle(): num = int(in_num.get()) for i in range(num): circle = turtle.RawTurtle(drw) circle.color("red") circle.shape("circle") circle.penup() circle.goto(x=random.randint(-200, 200), y=random.randint(-200, 2...
in_file = None # txt file in_str = "" # read string # 1. open file in_file = open("data.txt", "r") # 2. read in_list = in_file.readlines() for in_str in in_list: print(in_str) # 3. close file in_file.close()
out_file = None out_str = "" # 1. open file out_file = open("output.txt", "w") while True: out_str = input("input string : ") if out_str == "exit": break # 2. write string out_file.write(out_str) out_file.write('\n') # 3. close flle out_file.close()
# import tkinter module from tkinter import * # Tk instance win = Tk() win.title("python window") # buttons btn1 = Button(win, text="BUTTON 1") btn2 = Button(win, text="BUTTON 2") btn3 = Button(win, text="BUTTON 3") btn1.pack(side=LEFT) btn2.pack(side=LEFT) btn3.pack(side=LEFT) win.mainloop()
from tkinter import * def onClick(): myLabel.config(text = inp.get()) root = Tk() root.title("Calculator") inp = Entry(root,width = 35, fg = "black", bg = "white", borderwidth = 5) inp.grid(row=0,column=0,columnspan=3,padx = 5,pady = 5) btn_1 = Button(root,text = "1",command = onClick,padx = 50, pady = 50) btn_1.g...
# Randomly fills a grid of size 10 x 10 with 0s and 1s, # in an estimated proportion of 1/2 for each, # and computes the longest leftmost path that starts # from the top left corner -- a path consisting of # horizontally or vertically adjacent 1s --, # visiting every point on the path once only. # # Written by *** and ...
# Randomly generates a grid with 0s and 1s, whose dimension is controlled by user input, # as well as the density of 1s in the grid, and finds out, for a given direction being # one of N, E, S or W (for North, East, South or West) and for a given size greater than 1, # the number of triangles pointing in that direction...
import pandas as pd df = pd.read_csv("real_estate.csv", sep=",") print(df) # Alguna información estadística: rows, cols = df.shape print("\nFilas: ", rows) print("Variables explicativas: ", cols - 1) # Menos la variable respuesta print("\nResumen estadístico de las variables:") print("\n") print(df.describe()) # Pa...
import pandas as pd #En este caso lo primero que vemos es que no tenemos una variable respuesta a predecir, puesto que estamos en un caso no supervisado. #Nuestro objetivo aquí por tanto es la segmentación de los clientes disponibles: hacer agrupaciones de los clientes según patrones de compra. Vemos que todas las var...
# Read list commands from STDIN and perform them on a list. n = int(raw_input()) command = [] theList = [] for i in range(0, n): command = raw_input().split() if command[0] == "insert": theList.insert(int(command[1]), int(command[2])) elif command[0] == "print": print(theList) elif comm...
import docx #import module to read or write to word doc from openpyxl import Workbook #import module and class to create an excel document #get the name of the file doc_name = input('Please enter the name of the document:') try: #open work document to read doc = docx.Document("add your directory/" + doc_name)...
''' initialize a result variable to be an empty list loop create a new element append it to result return the result ''' a_k = ['banana', 'apple', 'pear', 'lemon'] def double_stuff(a_list): new_list = [] for value in a_list: new_elem = 2 * value new_list.append(new_elem) ...
# 1. 定义模块名: calc.py 内部分别实现 加/减/乘/除 四个函数 # 加 def add(a1, a2): a = a1 + a2 print(a) # 减 def minus(m1, m2): m = m1 - m2 print(m) # 乘 def times(t1, t2): t = t1 * t2 print(t) # 除 def divide(d1, d2): d = d1 + d2 print(d)