text
stringlengths
37
1.41M
# # [55] Jump Game # # https://leetcode.com/problems/jump-game/description/ # # algorithms # Medium (29.50%) # Total Accepted: 162.3K # Total Submissions: 550.3K # Testcase Example: '[2,3,1,1,4]' # # # Given an array of non-negative integers, you are initially positioned at the # first index of the array. # # # ...
# # [287] Find the Duplicate Number # # https://leetcode.com/problems/find-the-duplicate-number/description/ # # algorithms # Medium (44.31%) # Total Accepted: 104.8K # Total Submissions: 236.6K # Testcase Example: '[1,1]' # # # Given an array nums containing n + 1 integers where each integer is between 1 # and n ...
# # [72] Edit Distance # # https://leetcode.com/problems/edit-distance/description/ # # algorithms # Hard (32.54%) # Total Accepted: 114.4K # Total Submissions: 351.6K # Testcase Example: '""\n""' # # # Given two words word1 and word2, find the minimum number of steps required to # convert word1 to word2. (each op...
# # [165] Compare Version Numbers # # https://leetcode.com/problems/compare-version-numbers/description/ # # algorithms # Medium (20.82%) # Total Accepted: 99K # Total Submissions: 475.2K # Testcase Example: '"0.1"\n"1.1"' # # Compare two version numbers version1 and version2. # If version1 > version2 return 1, if ...
# # [198] House Robber # # https://leetcode.com/problems/house-robber/description/ # # algorithms # Easy (39.96%) # Total Accepted: 195.5K # Total Submissions: 489.1K # Testcase Example: '[]' # # You are a professional robber planning to rob houses along a street. Each # house has a certain amount of money stashed,...
# # [309] Best Time to Buy and Sell Stock with Cooldown # # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ # # algorithms # Medium (41.96%) # Total Accepted: 59.6K # Total Submissions: 142.1K # Testcase Example: '[1,2,3,0,2]' # # Say you have an array for which the ith elem...
#!/usr/bin/python #***************************************************************************************************************************************************** # Linguagem ..........: Python # Criado por..........: Bruno Teixeira # Data da Criação.....: 10/02/2021 # Exercicios...........: Crie uma função recur...
import sqlite3 conn = sqlite3.connect('ages.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS Ages') cur.execute('CREATE TABLE Ages (name VARCHAR, age INTEGER)') cur.execute('INSERT INTO Ages (name,age) VALUES (?,?)', ('Billy', 14)) cur.execute('INSERT INTO Ages (name,age) VALUES (?,?)',('Billy', 15)) c...
''' This is a program to rotate a nxn array by 90 degrees clockwise. ''' def rotate(arr): size = len(arr) - 1 for i in range(len(arr) // 2): for j in range(i, size - i): (arr[i][j], arr[-(j+1)][i], arr[-(i+1)][-(j+1)], arr[j][-(i+1)]) = (arr[-(j+1)][i], arr[-(i+1)][-(j+1)], arr[j][-(i+1)], ...
#!/usr/bin/env python3 """ This file contains the functionality to detect websites """ ## Local Imports from .tld_list import get_tld_list def detect_website(section): """ Looks for websites in a section For example passwordwww.rockyou.com123 will extract www.rockyou.com Va...
#!/usr/bin/env python3 """ Logic to create the PRINCE wordlist Top level function is: create_prince_wordlist(pcfg, max_size) """ import sys # Local Imports from lib_guesser.priority_queue import PcfgQueue def create_prince_wordlist(pcfg, max_size): """ This is basically a stri...
#!/usr/bin/env python3 """ Name: PCFG_Guesser Priority Queue Handling Function Description: Section of the code that is responsible of outputting all of the pre-terminal values of a PCFG in probability order. Because of that, this section also handles all of the memory management of a running password gen...
# You are given two non-empty linked lists representing two non-negative integers. # The digits are stored in reverse order, and each of their nodes contains a single digit. # Add the two numbers and return the sum as a linked list. # You may assume the two numbers do not contain any leading zero, except the number ...
#!/usr/bin/env python3 """ Find optimal policy for the following problem: Jack manages two locations for a nationwide car rental company. Each day, some number of customers arrive at each location to rent cars. If Jack has a car available, he rents it out and is credited $10 by the national company. If he is out of ca...
import pygame import pygame.sprite from random import randint class Star(pygame.sprite.Sprite): """ Places stars on the screen randomly """ def __init__(self, ai_game): """initializes the stars""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings...
# -*- coding:utf-8 -*- # time: 2019/7/31 15:50 # File: 08-Craps赌博游戏.py """ Craps赌博游戏 玩家摇两颗色子 如果第一次摇出7点或11点 玩家胜 如果摇出2点 3点 12点 庄家胜 其他情况游戏继续 玩家再次要色子 如果摇出7点 庄家胜 如果摇出第一次摇的点数 玩家胜 否则游戏继续 玩家继续摇色子 玩家进入游戏时有1000元的赌注 全部输光游戏结束 """ import random def craps(): chips = 1000 while chips > 0: print("...
def main(): ''' 用type动态创建一个类 ''' # 通常type的使用方式是判断一个变量的类型 a = type('ooo') print(a) # 实际上,type本身是一个类,除了上面的用法外,还可以用来创建类 # type(类名, (类的父类名,), {类的属性}) b = type("Myclass", (), {"num": 100, "name": "张三"}) # 返回值是一个类 print(b) c = b() print(c.name) ...
from tkinter import * import time tk = Tk() canvas = Canvas(tk,width=1000,height=1000) canvas.pack() c = canvas.create_polygon(10,10,10,60,50,35) ''' print(c) for x in range(0,60): canvas.move(1,5,5) tk.update() time.sleep(0.05) for x in range(0,60): canvas.move(1,-5,-5) tk.update() ...
# -*- coding:utf-8 -*- # time: 2019/7/31 16:24 # File: 09-九九乘法表.py def table(): for i in range(1, 10): for j in range(1, i + 1): x = i * j print("%dx%d=%d" % (i, j, x), end='\t') print() if __name__ == '__main__': table()
# -*- coding:utf-8 -*- # time: 2019/8/4 9:53 # File: 11-最大公约数和最小公倍数.py def gcd(x, y): (x, y) = (y, x) if x > y else (x, y) for factor in range(x, 0, -1): if x % factor == 0 and y % factor == 0: return factor def lcm(x, y): return x * y // gcd(x, y) if __name__ == '_...
import pandas as pd import numpy as np # 创建DataFrame数据 # 包含行索引(index)和列索引(columns) t1 = pd.DataFrame(np.arange(12).reshape(3,4), index=["A","B","C"], columns=["D","E","F","G"]) print(t1) # 也可以用字典来创建 a = { "name": ['zhangsan', 'lisi'], "age": [23,42], 'tel': [12323532, 135235246], } t2 = pd...
''' class Parent: def hello(self): print("I am your parent") class Father: def hello(self): print("I am your father") class Son(Father,Parent): def hello(self): super().hello() print("who is my parent?") s = Son() s.hello() ''' class Myclass: def ...
# -*- coding:utf-8 -*- # time:2018/12/03 dict1 = {} d = dict1.fromkeys((1, 2, 3), []) d[1].append(1) print(d)
import sys def moon_weight(): print('please enter your Earth weight:') E_weight=int(sys.stdin.readline()) print("please entry the ratio:") ratio=float(sys.stdin.readline()) for i in range(1,16): print('year %s is %s' % (i,E_weight*ratio)) E_weight+=1 result= moon_weight() ...
# -*- coding:utf-8 -*- # time: 2019/7/31 14:40 # File: 03-判断是否是闰年.py def is_leap(year): if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: return True else: return False if __name__ == '__main__': print(is_leap(2020))
class Parent: x = 1 class son(Parent): pass class daughter(Parent): pass if __name__ == "__main__": # 继承父类的类属性:实际上是, 子类中创建一个同名变量,同时指向父类的类属性 # 本例中三个x都指向同一个内存空间 # python中,类变量是作为字典处理的,如果在当前类中没有发现,则去父类中找,都没找到就报错 # 1 1 1 print(Parent.x, son.x, daughter.x) print('...
class Person(object): kind = 'human' def __init__(self): self.words = [] def talk(self): print('talk') def add_words(self, word): self.words.append(word) @classmethod def what_is_my_kind(self): return self.kind class Car(object): def run(self): print('run') class PersonCar(Car, Perso...
#!/usr/bin/python3 """ In this module the class Place which inherits from the class BaseModel """ from models.base_model import BaseModel class Place(BaseModel): """ Initialization of the class attributes """ city_id = "" #will be the City.id user_id = "" # will be the User.id name = "" descripti...
# -*- coding: utf-8 -*- """ Created on Mon Mar 16 13:59:23 2020 @author: xingya """ # Returns index of i if i exist in arr, else return -1 def binarySearch(arr, l, r, i): if r>=l : # find the index of the element in the middle sof the array mid = (l + r) // 2 ...
# -*- coding: utf-8 -*- """ Created on Sat Oct 10 13:47:32 2020 82. Remove Duplicates from Sorted List II (Medium) Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: 1->2->3->3->4->4...
# -*- coding: utf-8 -*- """ Created on Tue Sep 15 22:22:22 2020 288. Unique Word Abbreviation (Medium) An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations: a) it --> it (no abbreviation) 1 ↓ b) d|o|g ...
# -*- coding: utf-8 -*- """ Created on Thu Aug 13 22:51:58 2020 @author: xingy Task description: TapeEquilibrium A non-empty array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A...
# -*- coding: utf-8 -*- """ Created on Sun Sep 20 20:52:03 2020 937. Reorder Data in Log Files (Easy) You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier will consist only of l...
# -*- coding: utf-8 -*- """ Created on Sat Mar 28 19:31:40 2020 @author: xingy """ import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] """ self.org = list(nums) self.nums = nums def reset(self): """ Resets the arra...
# -*- coding: utf-8 -*- """ Created on Fri Sep 4 20:06:53 2020 367. Valid Perfect Square Given a positive integer num, write a function which returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt. Example 1: Input: num = 16 Output: true Example 2: In...
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 12:19:50 2020 CountFactors Count factors of given number n. Task description A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M. For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 =...
# -*- coding: utf-8 -*- """ Created on Wed Sep 2 17:10:11 2020 Leetcode 136. Single Number Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 00:36:16 2020 @author: xingy GenomicRangeQuery Find the minimal nucleotide from a range of sequence DNA. Task description A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in...
# -*- coding: utf-8 -*- """ Created on Mon Sep 28 20:13:01 2020 695. Max Area of Island (Medium) Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find t...
# -*- coding: utf-8 -*- """ Created on Tue Sep 15 22:01:31 2020 Intersection of Two Arrays Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the ...
# -*- coding: utf-8 -*- """ Created on Mon Sep 28 14:45:24 2020 322. Coin Change (Medium) You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any comb...
# -*- coding: utf-8 -*- """ Created on Sun Nov 1 22:12:18 2020 359. Logger Rate Limiter (Easy) Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds. Given a message and a timestamp (in seconds granular...
# -*- coding: utf-8 -*- """ Created on Tue Sep 8 21:27:15 2020 153. Find Minimum in Rotated Sorted Array Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. You may assume no duplicate exis...
import time string = 'worldshsdjflsdfjdslkffldsjflsjflsjfls' * 999999 # 파이썬 slice 기능 사용 start_time1 = time.time() reversed_string1 = string[::-1] end_time1 = time.time() # for 문 사용 start_time2 = time.time() reversed_string2 = "" for i in range(len(string)-1, -1, -1): reversed_string2 += string[i] end_time2 = time...
def gcd(a, b): return a if b == 0 else gcd(b, a % b) def solution(n, m): a = max(n, m) b = min(n, m) return [gcd(a, b), n*m // gcd(a, b)]
from collections import deque def solution(n, computers): visited, bfs_nodes = set(), deque([]) count = 0 for node in range(n): if node in visited: continue count += 1 bfs_nodes.append(node) visited.add(node) while bfs_nodes: new_node = bfs...
from fractions import gcd # def gcd(a, b): # 속도 조금더 빠름 # return a if b == 0 else gcd(b, a % b) def solution(arr): while len(arr) > 1: n, m = arr.pop(), arr.pop() arr.append(n*m // gcd(n, m)) return arr.pop()
""" 数をカウントできるようなクラスを実装する ・数はカウントアップ(ダウン)するたびに、指定の刻み幅ずつ増える(減る) ・カウントの上限と下限、初期値及び刻み幅を指定できるようにする ・カウントをリセットできるようにする """ import pytest class Counter: def __init__(self, value: int, step: int, upper_limit=90, lower_limit=0): self.value = value # 50 self.step = step # 15 self.upper_limit = upp...
import turtle import random print("Hello! Welcome to the Snake Game!") print("The objective of this one-player game is to score as many points possible by chasing after the red target.") print("Here are the Rules: You cannot go outside of the screen or touch the other random barriers!") print("Each time you do, the ...
def Euclid1(n, m): if m == 0: return n else: return Euclid1(m, n % m) n, m = map(int, input().split()) gcd = Euclid1(n, m) print(gcd)
def bin_search(n, S, x): low, high = 0, n - 1 while low <= high: mid = (low + high) // 2 if x == S[mid]: return mid elif x < S[mid]: high = mid - 1 else: # x > S[mid] low = mid + 1 return -1 n = int(input()) S = list(map(int, input().split...
import sys import random import os #This the dice game, whoever rolls the higher amount pvcpu def game_logics(dice,rounds): cpu_score = 0 user_score = 0 for x in range(0,rounds): ur = random.randrange(1,dice) cpr = random.randrange(1,dice) if(cpr == ur): print("\nLooks like we have a tie!!!") ...
#id=input('enter id name') #pw=input('enter password') #if id=='thub' and pw=='1234': ##### task ##### # print('login') #else: #print('wrong credentials') #s=int(input('enter a start number')) ##i=0 ##while True: ## i+=1 ## print(i) ## if i==10: #...
# Week 02 Day 2 # Homework 1 def asciiAlphabet(): for i in range(65, 65+26): print(i, " stands for ", chr(i)) for i in range(97, 123): print(i, " stands for ", chr(i)) # asciiAlphabet() # Homework 2 def createCypher(plain): cypherText = "" for i in range( 0 , len(plain)): cypherText = cypherText + str(or...
# A few things to try # *** 01 # Full name greeting. Write a program that asks for a person’s first name, then middle, and then last. Finally, it should greet the person using their full name. response = '' fullName = '' response = input('What is your first name : ') fullName = response response = input('What is yo...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ from math import sqrt def area(sideA,sideB,sideC): """lasku kolmion pintaala""" s = (sideA + sideB + sideC)/2 A = sqrt(s*(s-sideA)*(s-sideB)*(s-sideC)) return A def main(): lineA = float(input("Ente...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ import math def tarkista(yht, on): """tarkista onko mollemmat positivinen ja onko lottopallojen kokonaismäärä isompi entä arvottavien pallojen määrän""" if on > yht or on < 0 or yht < 0: return Fals...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ LOAN_TIME = 3 MAX_LOANS = 3 class Librarycard: def __init__(self, card_id, card_holder): self.__id = card_id self.__holder = card_holder self.__books = {} self.__time = 0 def ...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ def are_all_members_same(mass): """ löydä min ja max ja tarkista onko se sama""" if mass == []: return True elif max(mass) == min(mass): return True else: return False def ...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ def sravnenie(mass, vrema): """ Tarkista mita aika nym ja koska seurava bussi""" for i in range(0,len(mass)): if vrema <= int(mass[i]): start_znach = i break else: ...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ def create_an_acronym(text): """ Akronyymin muodostaminen Parameters ---------- text : sanat Returns ------- Vastaus summ """ delim_text = text.split() summ = "" for i ...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ def print_verse(sanoY, sanoK): """ tulostaa laulun Old MacDonald Had a Farm sanoituksen""" if sanoY == "lamb": print("Old MACDONALD had a farm") print("E-I-E-I-O") print("And on his farm ...
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ def read_file(filename): """ Tässä avataan tiedosto, luetaan jokainen rivi, luodaan sanakirja ja täyttetään se parametri: filename: tiedoston nimi return: subjects: sanakirja, missa o...
# -*- coding: utf-8 -*- """ Created on Tue May 29 15:03:31 2018 @author: giris """ #Simple Linear Regression import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing the Dataset dataset = pd.read_csv("E:\Machine Learning\Machine Learning A-Z Template Folder\Part 2 - Regression\S...
#coding:utf-8 import os def dir_list(dir_name, subdir, *args): '''Return a list of file names in directory 'dir_name' If 'subdir' is True, recursively access subdirectories under 'dir_name'. Additional arguments, if any, are file extensions to add to the list. Example usage: fileList = dir_list(r'H:\TEMP'...
class Matrix(object): def __init__(self, array): assert all([len(array[0]) == len(row) for row in array]) self.array = array self.shape = (len(array), len(array[0])) def size(self): return self.shape def __getitem__(self, ids): if isinstance(ids, tuple):...
#!/usr/bin/env python from math import sqrt def prime(): yield 2 count = 2 p = 3 while count < 10002: if len(list(filter(lambda x: p % x == 0, range(2, int(sqrt(p) + 1))))) == 0: yield p count += 1 p += 2 print(max(prime()))
lista = [] lista.append("Thiago") lista.append("Gabriel") lista.append("Elias") lista.append("Augusto") lista.append("Giordano") lista.append("Lucas") lista.append("Nicolas") nome = input("Digite um nome para verificarmos se ele está na lista: ") if (nome) in lista: print("Sim, está na lista!") else: print(...
# my notes about python basics syntax # jupiter installed locally" # Build-in function dict(a=1) # no # i better directly create my dictionary {"a": 1, 2: 5} # instead of: tuple(1, 2, 3) (1, 2, 3) # instead of: list(1, 2, 3) # do: [1, 2, 3] # len functions runs on everythin (dict, tuple, list, sets, geneators) le...
import time import numpy as np from copy import deepcopy ''' Solves sudoku grids recursively ''' def convert(string): ''' Takes an input string of the rows of a sudoku and converts it to a 9x9 numpy array ''' arr=[] vector=[] for i in range(len(string)): vector.append(int(st...
import enum class TicTacToeCell(enum.IntEnum): N = 0 O = 1 X = 2 class InvalidMoveError(RuntimeError): pass class GameFinished(RuntimeError): pass class TicTacToeGameBoard: winner = TicTacToeCell.N finished = False def __init__(self): self.game_board = [x[:] for x in [[T...
# NOT DONE BY ME THIS IS FROM SOLUTION PROVIDED IN COMMENTS # Link to the question: # https://www.interviewbit.com/problems/first-missing-intgerer/ # ESSENTIAL TO KNOW "MARK PRESENCE OF ELEMENT X" LOGIC class Solution: # @param A : list of integers # @return an integer def firstMissingPositive(self, A): # ...
# Link to the question: # https://www.interviewbit.com/problems/search-for-a-range/ class Solution: # @param A : tuple of integers # @param B : integer # @return a list of integers def searchRange(self, A, B): start=0 end=len(A)-1 ans=[-1,-1] if (A[0]...
# Link to the question: # https://www.interviewbit.com/problems/power-of-two-integers/ class Solution: # @param A : integer # @return an integer def reverse(self, A): flag=0 if (A>2147483648 or A<-2147483649): return 0 if (A<0): A=A*-1; flag=1 A=str(A) A=A[::-1] ...
def odd_even(num): if num%2==0: return "even" return "odd" print(odd_even(9))
# name = input("enter your name ") name ="sajid" age =24 print(f" Hello {name} your age is {age}")
print("break loop \n") for i in range (1,11): if i==5: break print(i) print("continue block \n") for i in range (1,11): if i==5: continue print(i)
######################################### # # # CodinGame Classic Puzzles - Easy # # Horse-Racing Duals # # # ######################################### def heapsort(aList): length = len( aList ) - 1 leastParent ...
################################### # # # CodinGame Community Puzzles # # How Time Flies # # # ################################### from datetime import date begin = input() end = input() start_year = int(begin[6:]) end_year = int(en...
######################################### # # # CodinGame Classic Puzzles - Medium # # Scrabble # # # ######################################### letter_scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, ...
################################### # # # CodinGame Community Puzzles # # Magic Stones # # # ################################### n = int(input()) stones = sorted([int(i) for i in input().split()]) some_changes = True while some_chan...
"""Approximating functions as functions. Which appears to be approximating all functions that are not polynomials as polynomials of some form. This is useful and basically required because computers can *generally* only handle operations associated with polynomials, namely, addition, subtraction, multiplication, and...
import face_recognition as fr import os import cv2 import face_recognition import numpy as np import sys from time import sleep def get_encoded_faces(folder): """ looks through the faces folder and encodes all the faces :return: a dict of (name, image encoded) """ # Dictionary with the names ...
# coding=utf-8 # Readability counts. """ Code homework problem 2: Implement a least recently used (LRU) cache mechanism using a decorator and demonstrate it use in a small script. The LRU must be able to admit a ‘max_size’ parameter that by default has to be 100. """ ## for me: breadcrumbs for deb...
def f(a, b, x): return { '+': a + b, '-': a - b, '*': a * b, '/': a / b, '%': a % b, '^': a ** b, }[x] A = int(raw_input("\n\nPress FIRST number: ")); B = int(raw_input("\n\nPress SECOND number: ")); O = raw_input("\n\nPress OPERATOR: "); print(f(A, B, O));
a=input("문자 와 숫자입력:") b="" for i in range(0,len(a)): if a[i].isalpha(): b += a[i] print("숫자 제거 문장: " + b)
r=int(input("반지름 입력 :")) area=r*r*3.14 print("원의 넓이 : ",area)
##지역변수, 전역변수,global예약어## def func4(): print("func4에서 a값:%d"%a) def func1(): global a#a를 전역변수로 지정해 지역변수 a는 존재하지 않는다. a=10 #지역변수 print("func1에서 a값:%d"%a) def func2(): a=10 #지역변수 print("func2에서 a값:%d"%a) def func3(): print("func3에서 a값:%d"%a) a=20 #전역변수 ##함수사용## func4() func1() func2() func3(...
a=int(input(" 연도를 입력하세요 : ")) if ((a%4 == 0) and (a%100 != 0)) or (a%400 ==0): print("%d는 윤년입니다." %a) else : print("%d는 윤년이 아닙니다. " %a)
##커피자판기 사용을 함수를 이용하용하여 표현 ##함수 선언## def coffee_machine(user): print("*********커피주문*********") button=int(input(user+"씨 어떤커리를 드릴까요?(1:아메리카노, 2:카페라떼 3:카푸치노 4:에스프레소)")) print("#1.뜨거운물준비") print("#2.종이컵 준비") if button==1: print("#3.아메리카노 커피를 만든다") elif button==2: print("#3 까페라떼 커피를 ...
for i in range(2,10): print("# %d단 # "%i,end="") print("") for i in range(1,10): for r in range(2,10): print("%2d X %2d = %2d " %(r,i,r*i),end="") print("")
a=input("입력문자열 : ") print("출력문자열 : ",end="") if a.startswith(" ")==True: print("[", end='') print(a, end="") if a.endswith(" ")==True: print("]")
# Name: Nate McCain # Date: October 23, 2014 # Class: CS 142 # Pledge: I have neither given nor received unauthorized aid on this program. # Description: TurtleMaze is a class object that creates a maze and defines the # functions to navigate the maze. The function searchFrom finds # ...
class Nodo: def __init__( self, data=None ): self.data = data self.next = None class LL: def __init__( self ): self.first = None def push( self, data ): if self.first is None: self.first = Nodo( data=data ) else: temp = self.first while temp.next is not None: temp =...
# -*- coding: utf-8 -*- """ https://plotly.com/python/plotly-express/ @author: Nick """ import pandas as pd import plotly.express as px from plotly.offline import plot df = pd.read_csv("election.csv") # define the target feature and other meaningful features targets = [" DemocratWon"] features = ["Re...
#!/usr/bin/env python3 # display a welcome message print("The Miles Per Gallon program") print() # get input from the user miles_driven= float(input("Enter miles driven:\t\t")) gallons_used = float(input("Enter gallons of gas used:\t")) gallons_cost = float(input("Enter cost per gallons:\t\t")) # calculate ...
import os path = "/Users/christinechan/Development/AddressBook/" # Menu def menu(): flag = True while flag == True: action = input("Welcome to the Address Book. Please select an option below: \n [Press 1] Create new contact \n [Press 2] Search contacts \n [Press 3] Delete contact \n [Press 4] Exit \n") if int(...
def queen(n, y): global count if n == y and check(n): flag = 1 for i in range(len(r)): for j in range(len(board)): if r[i][0] == j and r[i][1] != board[j]: flag = 0 break if flag == 1: for i in range(len(boar...
from random import random as rand def PI(n): inCircle = 0 for i in range(n): x = rand() y = rand() d = (x - 0.5)**2 + (y - 0.5)**2 if d < 0.25: inCircle = inCircle + 1 return 4 * inCircle / n n = 1 for i in range(1, 6): n *= 10 print("n =", n) prin...
# To print out a board. board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] # write a function to display the board. ...