text
stringlengths
37
1.41M
#Familiarizing text editor,IDE,code analysis tools. print("Enter your address") n=input("Enter your name : ") hname=input("Enter your house name : ") p=input("Enter your place : ") pin=int(input("Enter your pincode: ")) d=input("Enter your district : ") print("Address details :") print("Name :",n) print("House...
#Program to find the factorial of a number a=int(input("Enter the number:")) fact=1 for x in range(1,a+1): fact=fact*x print("The factorial",fact)
#Generate a list of four digit numbers in a given range with all their digits even and the number is a perfect square. a=int(input("Enter the lower digit:")) b=int(input("Enter the upper digit:")) import random print(random.randint(a,b)) c=[] c=[x for x in range(a,b)if(int(x**0.5)**2==x and int(x%2==0))] print(c...
#List of color names entered by user and display first and last color c=[] x=int(input("Enter limit: ")) for i in range(1,x+1): a=input() c.append(a) print(c) print(c[0],c[-1])
#Program to check whether a number is positive or negative a=int(input("Enter the number:")) if a>0: print("The given number is positive") elif a==0: print("The given number is zero") elif a<0: print("The given number is negative")
#Program to check whether the given number is palindrome or not a=int(input("Enter the number:")) temp=a rev=0 while a > 0: d=a%10 rev=rev*10+d a//=10 if temp==rev: print("The given number is Palindrome") else: print("The given number is not palindrome")
class BinarySearch(list): def __init__(self,a,b): self.a = a # a is length of ist to be created self.b = b # b is the step between consequtive numbers self.li = [i for i in range(b,a+1)] self.length = len(self.li) def search(self,item): self.count =0 self.ind...
def remove_parentheses(s): level = {s} while True: res = [] for cur in level: if is_valid(cur): res.append(cur) if res: return res new_level = set() for cur in level: for i in range(len(cur)): new_level...
def max_swap(num): digits = list(str(num)) res = 0 for i in range(len(digits)-1): for j in range(i+1, len(digits)): c_digits = digits[:] c_digits[i], c_digits[j] = c_digits[j], c_digits[i] if int("".join(c_digits)) > res: res = int("".join(c_digits...
from typing import List from collections import defaultdict from queue import Queue class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: ...
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def rob(self, root): cache = {} return self._rob(root, cache) def _rob(self, root: TreeNode, cache) -> int...
# dummy class class BinaryMatrix(object): def get(self, row: int, col: int) -> int: return 1 def dimensions(self) -> list: return [] class Solution: def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: n_row, n_col = binaryMatrix.dimensions() j = n_col - ...
from typing import List, Set class Solution: def count_components(self, n, edges: List[List[int]]) -> int: if n == 0: return 0 graph = self._create_adjacent_list(n, edges) visited = set() res = 0 for v in range(n): if not v in visited: ...
def max_diff(root): res = [0] dfs(root, 0, 100000, res) return res[0] def dfs(node, max_val, min_val, res): """ Top-down approach. Keep track of the max and min encountered when going down. When reaching a leaf, the max diff is max_val - min_val. Since dfs covers all the path, the max diff...
from collections import Counter import heapq class Word: def __init__(self, w, c): self.w = w self.c = c def __lt__(self, other): if self.c < other.c: return True elif self.c == other.c: return self.w > other.w else: return False ...
from queue import Queue def is_bipartite(graph): colors = dict() # store nodes and its color q = Queue() for i in range(len(graph)): if i not in colors: q.put(i) colors[i] = 0 while not q.empty(): cur = q.get() for v in graph[c...
from collections import deque class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ Using the BST property, we can the value range to determine if the current node is done. Comparing with serialize and deserialize a BT, we don't need to add indicator ...
import heapq from typing import List class Solution: def k_smallest_pairs_brutal_force(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: """ Time complexity O(m*n*log(k)) Space complexity O(k) """ if not nums1 or not nums2: return [] ...
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ Flatten the tree using in-order traversal and check if the array is sorted. """ def isValidBST(self, root: Tre...
from typing import List class Solution: def length_of_lis(self, nums: List[int]) -> int: """ maintain a array dp whose i-th element is the length of the longest increasing substring in nums[:i+1] and must contain nums[i], the dynamic programming relation is: dp[i] = max(dp[j]) + 1...
# Definition for a binary tree node. from queue import Queue class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class CodecPreOrder: def serialize(self, root): """ Use pre-order traversal to serialize the tree """ ...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: cur1 = l1 cur2 = l2 dummy = ListNode(0) cur = dummy carry = 0 while cur1 or ...
def product(nums): front = [1] for num in nums[:-1]: front.append(front[-1] * num) end = [1] for num in nums[::-1][:-1]: end.append(end[-1] * num) end = end[::-1] res = [] for i in range(len(nums)): res.append(front[i] * end[i]) return res def product_space_...
def is_sorted(words, order): n_order = 'abcdefghijklmnopqrstuvwxyz' map_dict = {} for c1, c2 in zip(order, n_order): map_dict[c1] = c2 n_words = [] for w in words: temp = [] for c in w: temp.append(map_dict[c]) n_words.append(''.join(temp)) for i in...
from typing import List class Solution: def max_sub_array(self, nums: List[int]) -> int: """ maintain an array dp and dp[i] is the maximum subarray that ends with nums[i]. Thus: dp[i+1] = nums[i+1] if dp[i] <= 0 = nums[i+1] + dp[i] if dp[i] > 0 """ ...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # class ListNode: def partition(head, x): left_head = ListNode(None) right_head = ListNode(None) left = left_head right = right_head cur = head while cur: if cur.val < x: ...
class Solution: def insert(self, intervals, new_interval): res = [] new_low, new_high = new_interval for i in range(len(intervals)): if intervals[i][1] < new_low: res.append(intervals[i]) elif intervals[i][0] > new_high: res.append([ne...
def is_equal(nums): if len(nums) < 7: return False n_sum = [nums[0]] for i in range(1, len(nums)): n_sum.append(n_sum[-1] + nums[i]) for j in range(3, len(nums)-3): # it is possible there are more than one sum value # 2, 1, -1, 2, 1, remove -1, we have 3, remove 1, we h...
#!/bin/python name = "Alli" print(name) if len(name) >=5: print("name is long") elif len(name) == 4: print("name is average") else: print("name is short") print("Condition successul")
#16진수로 입력된 정수 한 개를 8진수로 바꾸어 출력하는 프로그램을 작성해보자. #따로 생각나는 방법이 없어서 일단 10진수로 변경후, 다시 8진수로 변경하는 방법을 사용하였다. num = int(input(), 16) nums = oct(num)[2:] print(nums) ''' 다른 사람의 풀이 a=input() n=int(a, 16) print('%o' % n) 다음엔 꼭 이 방법으로 풀어봐야지.. '''
#정수가 순서대로 입력된다. 0이 아니면 입력된 정수를 출력하고 0이 입력되면 출력을 중단해보자. #이전에 있던 문제랑 무엇이 다른지요..? #아무튼 다시 풀었습니다. a = input().split() for i in range(len(a)): if a[i] != '0': print(a[i]) else: print(a[i]) break
#단어를 하나 입력받는다. 입력받은 단어(영어)의 각 문자를 한줄에 한 문자씩 분리해 출력한다. #'B''o''y' 이런 식으로 문제에서는 답을 원해서.. 어떤 방법으로 할까 하다가.. 그냥 프린트에 ""를 포함해서 출력해주었다. #다른 방버이 있었을 지도.. word = list(input()) for i in range(len(word)): print("'"+word[i]+"'")
#두 정수 사이의 합 #https://programmers.co.kr/learn/courses/30/lessons/12912 #두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. #예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다. def adder(a, b): sum = 0 if a < b: for i in range (a, b+1): sum += i else: for i in ra...
#정수 한 개가 입력되었을 때, minus(음)/plus(양) even(짝)/odd(홀)을 출력해보자. #첫 줄에 minus(음) 나 plus(양) 를 출력하고, 두번째 줄에 odd(홀) 나 even(짝) 을 출력한다. num = int(input()) if num > 0: print("plus") else: print("minus") if num%2 == 0: print("even") else: print("odd")
#입력된 두 정수 a, b 중 큰 값을 출력하는 프로그램을 작성해보자. #(단, 조건문을 사용하지 않고 3항 연산자 ? 를 사용한다.) #삼항 연산자: 항이 3개인 형태일 때 a, b = input().split(" ") a = int(a) b = int(b) c = a if a>b else b print(c) #파이썬의 3항 연산자 #(조건을 충족할 때) if (맞는 조건) else (조건을 충족하지 않을 때) #ex: a if a>b else b
# 나의 풀이 def solution(s): answer = '' numbers_english = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] curr = '' for i in s: if i.isalpha(): curr += i if curr in numbers_english: answer += str(numbers_english.ind...
#정수 한 개가 입력되었을 때 카운트다운을 출력해보자. num = int(input()) while num>0: print(num) num = num -1
#x만큼 간격이 있는 n개의 숫자 #https://programmers.co.kr/learn/courses/30/lessons/12954 #함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다.\ #다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요. #나의 풀이 def solution(x, n): answer = [] for i in range(1, n+1): answer.append(x*i) return answer...
# 큰 수 만들기 - 그리디 알고리즘 # https://programmers.co.kr/learn/courses/30/lessons/42883 def solution(number, k): stack = [number[0]] for num in number[1:]: while len(stack) > 0 and stack[-1] < num and k > 0: k -= 1 stack.pop() stack.append(num) return ''.join(stac...
#정수 두 개(a, b)를 입력받아 합, 차, 곱, 몫, 나머지, 나눈값을 자동으로 계산해보자. #정수 두 개(a, b)가 공백을 두고 입력된다. ''' 출력 기준 첫 줄에 합 둘째 줄에 차(a-b) 셋째 줄에 곱, 넷째 줄에 a를 b로 나눈 몫, 다섯째 줄에 a를 b로 나눈 나머지, 여섯째 줄에 a를 b로 나눈값(실수, 소수점 셋째 자리에서 반올림해 둘째 자리까지 출력) 을 출력한다. ''' a, b = input().split(" ") a = int(a) b = int(b) print(a+b) print(a-b) print(a*b) print(a//b) pr...
#문자열 내 마음대로 정렬하기 #https://programmers.co.kr/learn/courses/30/lessons/12915 #문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. # 예를 들어 strings가 [sun, bed, car]이고 n이 1이면 각 단어의 인덱스 1의 문자 u, e, a로 strings를 정렬합니다. #나의 풀이 def solution(strings, n): for i in range(len(strings)): #그냥 n번째 ...
#입력된 세 정수 a, b, c 중 가장 작은 값을 출력하는 프로그램을 작성해보자. #(단, 조건문을 사용하지 않고 3항 연산자 ? 를 사용한다.) #짜잔 세 개의 수를 비교하려면 삼항연산자 안에 삼항연산자를 넣어야 합니다. #삼항연산자 이렇게 썼으니 안 잊어먹기를 #a i f (a<b) else b .. 혹시 모르니까 연습 a, b, c = input().split(" ") a = int(a) b = int(b) c = int(c) small = a if (a<b and a<c) else (b if (b<c and b<a) else c) print(small...
command = input('Console command: ').upper() started = False while command != 'QUIT': if command != 'HELP': print('Command not recognized.') command = input('Console command: ').upper() else: print(''' Type "Start" to start the car. Type "Stop" to stop the car. Type "Quit" to terminate p...
def find_max(elements): # Redefining 'list' thru new variable numbers = elements # Set highest number based from 1st element in list. high = numbers[0] # Working Equation for x in numbers: if x > high: high = x # Value Returned to main.py return high
import random # For generating any number: print(random.random()) # Example No.01: for x in range(10): print(random.random()) # Example No. 02: # For generating any number but within specific range: for x in range(3): print(random.randint(10, 20)) # For generating any string based from a certain list: memb...
a = input('What is your weight? ') b = input("Press 'L' for lbs (pounds) or 'K' for kgs (kilograms) with respect to the unit of your inputted weight: ") if b == 'l' or b == 'L': c = float(a) / 2.2 print(f'You are {c} kgs.') elif b == 'k' or b == 'K': c = float(a) * 2.2 print(f'You are {c} lbs.') else: ...
""""A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.""" listx = [] listy = [] listz = [] for x in range(100,1000): listx.append(x) for y in ra...
# https://leetcode-cn.com/problems/rotate-list/submissions/ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: # step 1: corner case...
# filter(関数, イテレータ) def is_even(n): return n % 2 == 0 print(list(filter(is_even, range(10)))) print(list(filter(lambda n: n % 2 ==0 , range(10))))
# Miguel Angel Montoya # montoya5@purdue.edu # ID: 0031152048 # A* algorithm for the cannibals-missionaries problem # For python 2.7 import Queue as Q right = "Right" left = "Left" # Abstraction of priority queue. It lets the insertion of objects with priority. class MyPriorityQueue(Q.PriorityQueue): def __init...
__author__ = 'gopalindians' #Operators a=3 b=3 print(a+b) print(a-b) print(a*b) print(a/b) print(a%b) print(a**b) print(a//b) #Assignment operator a+=2; print("Now a is :" , a);
__author__ = 'gopalindians' #Lists (Like arrays) val=[1,2,3,4,5,6,7,8] print(val[0]) #v2 using for loop for a in val: print(a) #v3 using index print(val[1:5]) #prints [2 3 4 5] #Common operations on List print(val) # List before appending val.append(12) print(val) #List after appending
""" Simulates a pandemic using pygame """ import pygame as pg from environment import Environment from organisms import Organism, Health import random, math, itertools, time, pickle # plotting import matplotlib.pyplot as plt from scipy import asarray as ar,exp import numpy as np # size of window (width, height) ...
import random import turtle # Returns a random color! from turtle import Turtle def get_random_color(): return "#%06X" % (random.randint(0, 0xFFFFFF)) def get_next_color(i): return colors[i % len(colors)] # ====================== DO NOT EDIT THE CODE ABOVE =========================== if __name__ == '__...
a=[] def even_number(x): for i in range(0,100): if i%2==0: x.append(i) print(x) even_number(a)
# https://adventofcode.com/2015/day/5 import sys import re from pathlib import Path path = Path(__file__).parent / "input/inputDay5.txt" vowels = "AaEeIiOoUu" pairs=["ab","cd","pq","xy"] f = open(path) def Check_Vow(string, vowels): final = [each for each in string if each in vowels] return fi...
# coding: utf-8 from Tkinter import * import time import math root=Tk() root.title("画图") running=1 #c=circle_color,d_c=dot_color c=d_c='red' #r=rectangle_fill_color,l_c=line_color,r_o_c=rectangle_outline_color r=l_c=r_o_c=c_o_c='blue' #l=line_width,d=dot_width,e=erase_width,r_o_w=rectangle_outline_width l=d=e=r_o_w=c_o...
# -*- coding: utf-8 -*- # 所有名片记录的列表 cards_list = [] def show_menu(): """显示菜单""" print('*' * 50) print('欢迎使用【名片管理系统】V1.0') print('') print('1.新建名片\n' '2.显示全部\n' '3.查询名片\n' '\n' '0.退出系统') print('*' * 50) def new_card(): """新建名片""" print('-' * 50...
class HouseItem(object): """家具类""" def __init__(self, name, area): # 家具名称 self.name = name # 家具占的面积 self.area = area def __str__(self): """输出对象时显示的信息""" return '家具名称:%s 占用面积:%s平米' % (self.name, self.area) class House(object): """房类""" def __init__...
# 动态规划:将大问题分解为小问题,先解决小问题,再逐步解决大问题 # 1.当给定约束条件下优化某种指标 # 2.问题可分解为离散子问题 # 绘制表格:每个单元格都是一个子问题,将每个子问题作为一列,单元格中的值就是要优化的值,每次迭代,更新子问题中的优化值 # 背包问题 # 约束条件:背包大小4 # 优化值:背包中物品总价值 # 将4背包分解成小背包作为列 # 每次迭代小背包,更新小背包中能存放的最大价值 # 单元格中的值: # cell[i][j] = max(cell[i-1][j], value+cell[i-1][j-当前商品重量]) # 上一单元格的值/当前商品价值+当前剩余空间的最大价值 # 注意事项: # 1....
import socket if __name__ == '__main__': # 1. 创建服务端套接字对象 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置端口号服用:程序退出时立即释放端口号 # SOL_SOCKET:当前套接字 # SO_REUSEADDR:复用选项 tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) # 2. 绑定端口号 socket.bind((...
# 单元格中的优化值:两个字符串都包含的最长子串的长度 # 子问题:比较两个字符串的子串 # 坐标轴:两个单词 # 答案:网格中最大的数字 import numpy as np def dynamic(str1, str2): str_index = (0, 0) num = 0 cell = np.zeros((len(str1), len(str2)), dtype=int); for i in range(len(str1)): for j in range(len(str2)): if str1[i] == str2[j]: # 两个字母相同 if i==0 or j==0: cel...
class A: a=222 def method1(self): self.a=123 self.b=345 @classmethod def method2(cls): print(cls.a) class B: def method3(self): self.a=999 self.b=777 s1=A() s1.method1() print(self.a,self.b,s1.a,s1.b) A.method2() ...
''' Realiza un programa que reciba una cantidad de minutos y muestre por pantalla a cuantas horas y minutos corresponde. Por ejemplo: 1000 minutos son 16 horas y 40 minutos. ''' tiempo = int(input("Introduzca minutos a convertir: ")) horas = tiempo // 60 minutos = tiempo % 60 print(tiempo, " minutos, equivalen a ", ...
import math '''Dados dos números, mostrar la suma, resta, división y multiplicación de ambos.''' num1 = int(input('Introduzca primer número: ')) num2 = int(input('Introduzca segundo número: ')) print("La suma es = ",num1 + num2, "\nLa resta es = ",num1-num2, "\nLa multiplicación es = ",num1*num2, "\n...
def next_number(fibonacci_sequence): # item -2 (penultimate) or 1 penultimate_item = fibonacci_sequence[-2] if len(fibonacci_sequence) > 1 else 0 # item -1 (last) or 1 last_item = fibonacci_sequence[-1] if bool(fibonacci_sequence) else 1 return penultimate_item + last_item def fibonacci(n): if not isinstan...
#!/usr/bin/python3 hrs = input("Enter Hours:")# enter the hours h = float(hrs)#after converting it to float rate = input("Enter rate:")#enter the hours r = float(rate) def computepay(h,r): if h <= 40: pay = h * r elif h > 40: pay = 40 * r + (h-40) * r * 1.5 return pay print(computepay(h,r))...
import copy def combination(arr, r): a=[] def generate(chosen): if len(chosen) == r: print(chosen) b=copy.deepcopy(chosen) a.append(b) return start = arr.index(chosen[-1]) + 1 if chosen else 0 for nxt in range(start, len(arr)): ...
# add numbers x = 0 def func(): b =eval(input("enter the number")) for i in range(b+1): if i % 2 == 0: global x x = i + x print (x) else: print("Try next") func()
class a(): def __init__(self): self.x = 0 print ("hai i am in cons of a") def foo(self): print ("hai a") class b(): def __init__(self): self.x = 10 print ("i am in cons of b") def foo(self): print ("hai b") class c(b,a): def __init__(self): ...
class abc(): count = 0 def __init__(self,var1 =1,var2 ="pop") self.arg1 = var1 self.arg2 = var2 abc.count = abc.count + 1 print ("in constructor") def print_obj(self): print("object" , self.arg1) print ("object", self.arg2) def __del__(self): ...
e = 1 som = 0 while e != 0: e = int(input(" entrer le montant : ")) som = som + e print(" vous devez : ", som , "euros")
#project_title專題題目 #name_list成員名字 name=['林郁婷','陳妤瑄','林嘉欣','甘庭銨','游佳樺','蔡柏薪','林昱承','簡郁虹','王子維'] #number_list成員學號 number=['A109260010','A109260028','A109260036','A109260038','A109260042','A109260044','A109260046','A109260074','A109260096'] #duty_list分工內容 duty=['聊天內容','程式碼'] #load_list分工比重 load=['5%','10%'] #code...
# 1. Определение количества различных подстрок с использованием хеш-функции. # Пусть на вход функции дана строка. # Требуется вернуть количество различных подстрок в этой строке. import hashlib def subs(str): sub = set() for i in range(len(str)): for j in range(len(str), i, -1): hash_str ...
# 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, # заданный случайными числами на промежутке [-100; 100). # Выведите на экран исходный и отсортированный массивы. import random SIZE = 10 MIN_ITEM = -100 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] de...
# 1. В диапазоне натуральных чисел от 2 до 99 определить, # сколько из них кратны каждому из чисел в диапазоне от 2 до 9. array = [0]*8 for i in range(2,100): for j in range(2,10): if i%j == 0: array[j-2] += 1 i = 0 while i < len(array): print(f'Числу {i+2} кратны {array[i]}') i += 1
# Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. # Проанализировать результат и определить программы с наиболее эффективным использованием памяти. # В данной задаче массив генерируется рандомно, но присутствуют переменные, задающие его параметры. # ...
import pandas as pd import matplotlib.pyplot as plt data = { # python dictionary 'apples': [3,2,0,1], 'oranges':[0,3,7,2] } purchases_dataframe = pd.DataFrame(data) print(purchases_dataframe) dataset = pd.read_csv('data/ml-assessment-dataset.csv') print(dataset.head(10)) # displays the header and top half of...
""" makes a parenthesis input valid by removing necessary characters for example: input: (2 + 4) * ((34 + 5) output: (2 + 4) * (34 + 5) """ def makeValid(s): paraStack = [] openStack = [] for i in range(len(s)): if s[i] == "(" or s[i] == ")": paraStack.append({"type":s[i], "idx...
import tkinter from tkinter import * from PIL import Image, ImageTk def capture(): window = Tk() window.geometry("1280x800") window.title("DSL") window.configure(bg="#969696") background_intro = tkinter.PhotoImage(file="Pics\capture_bckgrnd.png") background_label = tkinter.Label...
class Solution: def isValid(self, s: str) -> bool: stack = [] open_brackets = ["(", "{", "["] closed_brackets = [")", "}", "]"] for char in s: if char in open_brackets: stack.append(char) elif char in closed_brackets: ...
n = int(input("Enter number of columns ")) for i in range(n) : print("*", end='')
word = input('Enter your word ') characters = list(word) from random import choice n = len(characters) i = 0 while i < n : random_characters = choice(characters) print(random_characters, end=' ') characters.remove(random_characters) i = i + 1 count = 0 loop = True while loop and count < 8 : guess = ...
# n = int(input("n ")) # for i in range(0, n, 2): # # range(start, stop, step) # print(i, end=', ') n = int(input("n ")) for i in range(n): # i la bien gan voi cac gia tri cua n if i % 2 == 0 : print("Fizz") elif i % 3 == 0 : print("buzz") else i % 2 % 3 == 0 : print("Fi...
print("The area of a circle") r = float(input("Enter radius")) if r < 0 : print("The radius input must > 0") else : s = 3.14 * r**2 print("The area of a circle is s = {0}".format(s),"unit area")
''' Class: CPSC 427 Team Member 1: Robert Brajcich Team Member 2: Damon George Submitted By Damon George GU Username: dgeorge2 File Name: proj6.py Uses breadth-first search to list states while finding goal state of given eight puzzle initial state Usage: python proj6.py Date: 22 February 2019 ''' from copy import de...
INFINITY = float('inf') #class Node(): # def __init__(self, x, y, distance): # self.x = x # self.y = y # self.distance = distance def isInsideGrid(x, y): return 0<=x<ROW and 0<=y<COLUMN # Moves x = [-1, 0, 1, 0, 1, -1, 1, -1] y = [0, 1, 0, -1, 1, 1, -1, -1] def dijkstrasAlgo(mat, ROW, COLUMN): # Initial...
# To get file name print('Enter file name') filename = str(input()) #To check File Name if(filename == "" or filename=="con" or filename == "aux"): print('Error in your file name \n You cant use file names like con or aux'); else: # To get maximum number print("\nEnter maximum number") ...
#Multiplication table a = 1 while a < 11: b = 1 while b < 11: print('%d X %d = %d' % (a, b, (a * b))) b += 1 a += 1
from Question import Question question_prompts = [ "What's the capital of Brazil?\n(a) Rio de Janeiro\n(b) Brazilia\n(c) Sao Paolo\n\n", "What's the capital of Australia?\n(a) Canberra\n(b) Sydney\n(c) Perth\n\n", "What's the capital of Pakistan?\n(a) Lahore\n(b) Islamabad\n(c) Karachi\n\n" ] qu...
# Ecommerce Purchases Exercise # # In this Exercise you will be given some Fake Data about some purchases done through Amazon! # Just go ahead and follow the directions and try your best to answer the questions and complete the tasks. Feel free to reference the solutions. # Most of the tasks can be solved in differ...
class Board: def __init__(self): self.board = self.initialize_pieces( [[" " for i in range(8)] for j in range(8)]) self.move_list = [] def initialize_pieces(self, board) -> list: board[1] = ['P' for i in range(8)] board[6] = ['p' for i in range(8)] board[0] ...
import math a=10 print(type(a)) print(a) print("-------------") b=10.9 print(type(b)) print(b) print("-------------") c=5+6j print(type(c)) print(c) print("-------------") d=0B1010 print(type(d)) print(d) print("-------------") e=0XFF print(type(e)) print(e) print("-------------") f=0O77 print(type(f)) print(f) pr...
# How to simulate animation #required import pygame pygame.init() #create a surface gameDisplay = pygame.display.set_mode((800,600)) #initialize with a tuple #lets add a title, aka "caption" pygame.display.set_caption("Movement!") pygame.display.update() #only updates portion specified #create colors white = (255...
import pygame pygame.init() Display = pygame.display.set_mode((600,300)) pygame.display.set_caption("Bar Graph") pygame.display.update() white = (255,255,255) black = (0,0,0) red = (255, 0, 0) green = (0, 255, 0) yellow = (255, 255, 0) # You will be visualizing this data. # (Label, Color of the bar, Length of the...
""" 다음 행렬과 같은 행렬이 있다. m = np.array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) 1.이 행렬에서 값 7 을 인덱싱한다. 2.이 행렬에서 값 14 을 인덱싱한다. 3.이 행렬에서 배열 [6, 7] 을 슬라이싱한다. 4.이 행렬에서 배열 [7, 12] 을 슬라이싱한다. 5.이 행렬에서 배열 [[3, 4], [8, 9]] 을 슬라이싱한다. """ import numpy as np a = np.array(range(15)...
myList=[0, -5, 8, 10, 200, -100] print(myList.index(200)) print(myList.count(0)) sortList=sorted(myList) print(myList.reverse()) print((myList.remove(10))) print(len(myList)) print(copyList = myList.copy()) myList.extend([4,1,3]) myList.pop() myList.index(-5)
num= int(input("숫자입력==>")) if (num % 2 == 0) : print("짝수") else : print("홀수")
import numpy as np import matplotlib.pyplot as plt A = np.array([[1,2],[3,4],[5,6]]) print(A.shape) #(3, 2) # 행렬의 내적 A = np.array([[1,2],[3,4]]) B = np.array([[5,6],[7,8]]) print(np.dot(A,B)) A = np.array([[1,2,3],[4,5,6]]) #2*3 B = np.array([[1,2],[3,4],[5,6]])#3*2 print(np.dot(A,B)) #2*2 # A가 2차원,B...
money, c50000, c10000, c5000, c1000 = 0, 0, 0, 0, 0 money = int(input("지폐로 교환할 돈은 얼마?")) c50000 = money // 50000 money %= 50000 c10000 = money // 10000 money %= 10000 c5000 = money // 5000 money %=5000 c1000 = money // 1000 money %=1000 print("\n5만원짜리==>%d장"% c50000) print("1만원짜리==>%d장"% c10000) print("5천원짜리==>%d...