text
stringlengths
37
1.41M
def Diameter(graph): return Max(AllShortestDistance(graph)) def AllShortestDistance(graph): """Compute the shortest distance between all pairs of vertices. Args: graph: Adjacency matrix, where entries are non-negative distance or None if there is no edge between the pair of vertices. Returns...
def InversionCountSq(values): inversion_count = 0 for i in xrange(len(values)): for j in xrange(i + 1, len(values)): if values[i] > values[j]: inversion_count += 1 return inversion_count def InversionCountFast(values): _, inversion_count = MergeSort(values) return inversion_count def M...
"""Minimum path of letter replacements to translate from one string to another. First solution is A*search. Second solution is much faster and simpler. """ from typing import List, Set, Dict, Callable, TypeVar, Tuple import string T = TypeVar('T') class PathData(object): def __init__(self, parent: T, distance_f...
def BinarySearch(values, key): left, right = 0, len(values) while left < right: mid = (left + right) / 2 if key < values[mid]: right = mid elif key > values[mid]: left = mid + 1 else: return (mid, True) else: if left == 0: return (0, False) if left == len(values): ...
import matplotlib.pyplot as plt import numpy as np def plotdata(x,y,line=False): plt.plot(x, y, 'rx') plt.ylabel('h(heta) or y ') plt.xlabel('feature x') plt.xticks(np.arange(min(x), max(x)+1, 2)) plt.yticks(np.arange(min(y), max(y)+1, 2)) if line: l1 = np.linspace(min(x),max(...
from typing import List def three_sum(nums:List[int])->List[List[int]]: if len(nums) < 3: return [] nas = [] nums.sort() for first in range(len(nums)-2): if nums[first] > 0: break if first > 0 and nums[first] == nums[first-1]: continue target = -...
name = input("Enter the your name : ") num1 = int(input("Enter the number : ")) for i in range(0,num1): for n in name: print(n)
input_surname = input("사용자의 성을 입력하세요 : ") input_firstname = input("사용자의 이름을 입력하세요 : ") print('Hello, '+ input_surname + input_firstname)
#day calculator day = int(input('예정일까지 얼마나 남았습니까? : ')) hours = day * 24 minutes = hours * 60 seconds = minutes * 60 print(hours, "시간 남으셨습니다.") print(minutes, "분 남으셨습니다.") print(seconds, "초 남으셨습니다.")
input_name = input('당신의 이름은? : ') input_age = input('당신의 나이는? : ') print(input_name, 'next birthday you will be', input_age)
import random color = random.choice(["black", "white" ,"purple", "orange", "green"]) print(color) #알고리즘 확인을 위해 삽입. a_color = input('Choose one of the following colors.\n"Black", "White" ,"Purple", "Orange", "Green" : ') a_color = a_color.lower() answer = True while answer == True: if color == a_color: print...
import operator d = {'java':10, 'r':6, 'python':18, 'firebase':16 } print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(1)) print('Dictionary in ascending order by value : ',sorted_d)
def del_key(n): dic = {"r":1, "python":5, "java":3, "swift":4, "flutter":2} del dic[n] return dic l = input("eneter one key value:") print(del_key(l))
#输出9*9乘法口诀表。 def mul(n): for i in range(1,n): for j in range(1,n): print(i,'*',j,'=',i*j) mul(10)
#学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。 def stratified(x): if x>=90: return 'A' elif x>=60: return 'B' else: return 'C' n=int(input()) print(stratified(n))
#一个5位数,判断它是不是回文数。 def Five_number_Palindrome(x): if x < 100000 and x>9999: sum=[] while x>9: mid=x%10 x=int(x/10) sum.insert(0,mid) sum.insert(0,x) else: print('input error number') sys.exit() return sum n=int(input()) s=Five...
# coding:utf-8 class Person(object): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex print(name, age, sex) # @property修饰的函数:定义时只要self参数 # 调用时不要传递任何参数,并且不能写括号 @property def get_age(self): pass xiaohong = Person("小红", 18, "girl") xiaoming = Person("小明", 18, "boy") xi...
#coding: utf8 import sys import math print "S-Salir" print "1-Sumar" print "2-Restar" print "3-Multiplicar" print "4-Dividir" opcionmain = raw_input("Introduzca una opcion :") while (opcionmain == False): print "Continue" if (opcionmain == 'S' or opcionmain == 's'): print "Adios" salir = True if (opcionmain ...
n=int(input("How many names will you input?" )) for i in range(0,n): name=input() print("Hello {}".format(name))
""" 一个回合制游戏,2个角色都有hp和power myhp = hp - enemy_power enemyhp = hp - my_power """ class First(): hp = 2000 def __init__(self, enemy_power, my_power): self.enemy_power = enemy_power self.my_power = my_power def first_battle(self): for i in range(1, 10): myhp = self.hp ...
import random questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?" } ingredients = { "str...
numero = int(input("Dime un numero: ")) palabra="" c=0 for i in range (1,numero+1): c=i+c print(f"{c}")
import random def drawBoard(board): # "board" is a list of 10 strings representing the board (ignore index 0) print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('----------------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ...
def heapyfy(arr,n,i): largest=i left=2*i+1 right=2*i+2 if(left<n and arr[largest]<arr[left]): largest=left if(right<n and arr[largest]<arr[right]): largest=right if(largest!=i): arr[i],arr[largest]=arr[largest],arr[i] heapyfy(arr,n,largest) def heapsort(arr,...
from utils import create_lsystem, Position import turtle """ F - moving forward [ - push current posiotion to stack ] - pop position from stack + - rotate to left - - rotate to right """ axiom = 'X' angle = 20 length = 30 def create_turtle(): sticks = turtle.Turtle() sticks.pensize(2) stic...
# 사전 키를 사용해 값을 불러오는 예제 dic = {"boy": "소년", "school": "학교", "book": "책"} print(dic["boy"]) # print(dic["student"]) # KeyError print(dic.get("boy")) print(dic.get("student")) print(dic.get("student", "사전에 없는 단어입니다.")) # in, not in 사용하여 사전에 단어가 있는지 알아보자. dic = {"boy": "소년", "school": "학교", "book": "책"} if "student...
# 일련의 문자를 따옴표(“, ‘)로 감싸 나열해 놓은 것이다. print("Hello World!") a = "Hello World!" print(a) print('Hello World!') a = 'Hello World!' print(a) # 따옴표(“, ‘) 잘 못 사용한 예 # print("Hello World!') # SyntaxError # print('Hello World!") # SyntaxError # # print("I Say "Help" to you") # SyntaxError # print('I S...
''' *Team id:eYRC-LM#448 *Author List: Akhil Guttula, Sai Kiran, Sai Gopal, Mohan *Filename: algo_mod *Theme: Launch a Module *Functions:find_route,delete_point,insert_point,ext_route,graph_dist,minDistance,set_objects_positions,get_objects_positions,set_free_loc,get_neighbours,dijkistra *Global Variables: graph,...
in_x, in_y = input("Enter x, y. eg: 5 27\n").strip().split(" ") def find_min_step(x, y): """Return min step between x, y when x become y. In one step x just eq x*2 or x-=1""" if x > y: exit(1) counter = 0 for i in range(y): if y % 2 != 0: y += 1 y = y / 2 ...
import pygame import sys import random # CONSTANTS SCREEN_W = 640 SCREEN_H = 480 BRICK_W = 60 BRICK_H = 15 PADDLE_W = 60 PADDLE_H = 12 BALL_DIAMETER = 16 BALL_RADIUS = int (BALL_DIAMETER / 2) MAX_PADDLE_X = SCREEN_W - PADDLE_W MAX_BALL_X = SCREEN_W - BALL_DIAMETER # State Machine S_BALL_IN_...
#python 3 userEntry = input() userAge = int(userEntry) if userAge > 18: print("Adult. Congrats.") elif (userAge > 10 and userAge <= 18): print("Teen. Rad, yo.") elif (userAge < 10): print("Child. Cool.")
import censusdata from gather_data import * import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--search', action='store_true', help="To perform a search for variables") parser.add_argument('--get', action='store_true', help="To load variables data...
def rsum(list1): '''(list of int) -> int ''' # this will check if there only one item if len(list1) == 1: # thats the only sum result = list1[0] else: # recursilvy calls the list and adds them up result = list1[0] + rsum(list1[1:]) return(result) de...
class Solution(object): def merge_sort(self,array): """ :type nums: List[int] ex:[3,2,-4,6,4,2,19],[5,1,1,2,0,0] :rtype: List[int] ex:[-4,2,2,3,4,6,19],[0,0,1,1,2,5] """ if len(array) <= 1: return array else: #####拆到只剩下一個,這裡是不耗時的 ...
import sys # Autor: Mailson Felipe # Data: 26/03/2021 def main(): padrao = input("Insira a string padrao (DDMMM:HHmm): ") flag = 0 dia = padrao[0]+padrao[1] mes = padrao[2]+padrao[3]+padrao[4] hora = padrao[06]+padrao[7] minutos = padrao[8]+padrao[9] if(len(dia) == 2): flag = 0; else: flag = 1 print(...
# Autor: Mailson Felipe # Data: 26/03/2021 def main(): data = input("Digite uma data no formato DD/MM/AAAA: ") dia = data.split('/')[0] mes = data.split('/')[1] ano = data.split('/')[2] auxDia = int(data.split('/')[0]) auxMes = int(data.split('/')[1]) if (auxDia < 1 or auxDia > 31): print('Dia invalido') ...
#!/usr/bin/env python # coding: utf-8 # In[3]: #1.Write a program in python to check whether a person is eligible for voting or not using if-else age=int(input("enter age : ")) if age >= 18 : print("eligible to vote") else: print("not eligible to vote") # In[4]: #2.Write a program in python to check whe...
# 객체변수 value가 100 이상의 값은 가질 수 없도록 제한하는 MaxLimitCalculator클래스 만들기 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val return self.value class MaxLimitCalculator(Calculator): def add(self, num): self.value += num if self.valu...
import sys import csv # 목적: 열의 헤더를 사용하여 특정 열을 선택하기 # 열의 헤드명으로 검색하는 것은 새로운 열이 추가및 삭제 되었을 경우에 # input_file = sys.argv[1] # output_file = sys.argv[2] input_file = "supplier_data.csv" output_file = "./output_files/7csv_reader_column_by_name.csv" my_columns = ['Invoice Number', 'Purchase Date'] my_columns_index = [] wi...
# coding: cp949 print("I eat %d apples."%3) # ˽Ʈ ٷ print str = " In addition, I eat %d bananas"%2 # Ʈ ڿ Ȯϴ ̽ print(str) number = 4 print("Further more, I eat %d mangoes" %number) number = "five" print("Moreover, I eat %s tangerine" % number) number = 0.25 print("At the end, I eat %s melon" %number) # %s ⺻ ڿ ...
# 목적: 날짜 형식 할당 import pandas as pd # input_file = sys.argv[1] # output_file = sys.argv[2] input_file = 'sales_2013.xlsx' output_file = 'output_files/3output_pandas.xls' data_frame = pd.read_excel(input_file, sheet_name='january_2013') # 이동평균 열 추가 연습 # data_frame['Acc'] = data_frame['Sale Amount'].rolling(window=3).m...
import datetime import time day_time = time.strftime("%H%M", time.localtime(time.time())) print(day_time) print("==="*10) cur_time = datetime.datetime.now() cur_time = cur_time.strftime("%Y%m%d %H%M") ymd = cur_time.split(" ")[0] print(ymd) print(cur_time) print(cur_time.split(" ")[1]) # day_time = datetime.datetime...
# class Calculator를 상속하는 UpgradeCalculator를 만들고 값을 뺄 수 있는 minus메서드를 추가 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val return self.value class UpgradeCalculator(Calculator): def minus(self, val): self.value -= val return s...
import sys # csv모듈 없이 파이썬 기본으로 파일읽고, 쓰기 # input_file = sys.argv[1] # output_file = sys.argv[2] input_file = "supplier_data.csv" output_file = "./output_files/1output_index_false.csv" with open(input_file, 'r', newline='') as filereader: with open(output_file, 'w', newline='') as filewriter: header = file...
# Enter your code here. Read input from STDIN. Print output to STDOUT size1 = int(input()) li1 = list(map(int, input().split())) size2 = int(input()) li2 = list(map(int, input().split())) final_list = [] for i in li1: if i not in li2 and i not in final_list: final_list.append(i) for i in li2: if i not i...
# Enter your code here. Read input from STDIN. Print output to STDOUT size = int(input()) details = {} for i in range(size): s = input() price = int(s.split(" ")[-1]) ss = s.split(" ") name = " ".join(ss[:len(ss) - 1]) if name not in details: details[name] = price else: details[n...
import random from Chromosome import Chromosome def single_point(parents): """Single point crossover. Creates a new Chromosome by combining the genes of both parents. A crossover point is found and the crossover is performed as follows: Parent A genes: AAAA AAAA Crossover point: ↕ Parent B g...
a = [5,1,1,19,29,2,0,0, 3, 34,23] def qsort(arry, low, high): left = low right = high key = arry[low] while low<high: while right >= key: right -= 1 arry[low] = arry[right] while left < low: left += 1 arry[high] = arry[left] arry[left] = key ...
'''Maximum of two number in python''' def maximum(a,b): if a>=b: print(a) else: print(b) a = 12 b = 14 print(maximum(a,b)) ''' Python program to find the maximum of two number using max function''' a = 14 b = 16 print(max(a,b)) c = 70 d = 90 maximum = max(c,d) print(maximum) #Ternary Meth...
""" """ class Contact(object): def __init__(self,name,hpnum,email,age): self.name = name self.hpnum = hpnum self.email = email self.age = age def to_string_(self): return self.name + ";" + self.hpnum + ";" \ + self.email + ";" + str(self.age) if __name...
import random import copy class Graph(object): class Edge(object): def __init__(self, source, destination, weight): """ DO NOT EDIT! Class representing an Edge in a graph :param source: Vertex where this edge originates :param destinatio...
''' Scaffolding code for the Machine Learning assignment. You should complete the provided functions and add more functions and classes as necessary. You are strongly encourage to use functions of the numpy, sklearn and tensorflow libraries. You are welcome to use the pandas library if you know it. ''' # Scik...
import time def factorial(N) : fac = 1 for i in range(1,N+1) : fac*=i return fac def main() : n = 50000 k = 50000 j = 50000 start = time.time() results = [factorial(n),factorial(j),factorial(k)] print ("time 1 = %s"%(time.time()-start)) if __name__ == '__main...
from functools import wraps def decorator(func): @wraps(func) def wraper(*args, **kwargs): print(type(args), args) print(type(kwargs), kwargs) print('hey, you') ret = func(*args, **kwargs) print('processing', ret) print('ok, done') return ret retu...
def getIndexOf(s, m): if s == None or m == None or len(m)< 1 or len(s)<len(m): return -1 str1 = list(s) str2 = list(m) x = 0 # str1中比对到的位置 y = 0 # str2中比对到的位置 next_list = getNextArray(str2) # 这个next_list既表示长度,也表示你该往哪儿跳 while x < len(str1) and y< len(str2): # 跳出while的条件,要么x越界,...
def LeftToRight(N: int): """ N层汉诺塔从左到右的过程 """ if N == 1: print("Move 1 From Left to Right.") return else: LeftToMid(N-1) print("Move %d from Left to Right." % N) MidToRight(N-1) def LeftToMid(N): if N == 1: print("Move 1 From Left to Mid") ...
def divide(arr, num): flag = -1 for i in range(len(arr)): if arr[i]<= num: arr[flag+1], arr[i] = arr[i], arr[flag+1] flag += 1 else: pass if __name__ == "__main__": arr = [1,5,2,3,5,2,1,6] divide(arr,2) print(arr)
class UnionFindSet: def __init__(self, value_list): self.elementMap = {} # 点和节点的对应关系,相当于一个注册表 self.fatherMap = {} # 父节点对映关系 self.sizeMap = {} # sizeMap中每一个key都是集合的头节点,也叫做代表节点 for v in value_list: element = Element(v) self.elementMap[v] = element se...
from 大根堆的heapify import heapify def popmax(arr, heap_size): """ 找到最大值返回,并删掉该值 """ t = arr[0] arr[0] = arr[heap_size-1] heap_size -= 1 heapify(arr, 0, heap_size) return t if __name__ == "__main__": a = [8,7,5,6,4,3] heap_size = len(a) print(a[:heap_size]) print(popmax(a,...
class Program: def __init__(self, start, end): self.start = start self.end = end def __lt__(self, other): return self.end < other.end def bestArrange(programs, timePoint ): programs.sort() ret = 0 for program in programs: if timePoint <= program.start: r...
class Solution: def rotate(self, nums, k): """ Do not return anything, modify nums in-place instead. """ length =len(nums) t = k%length for i in range(t): nums.insert(0,nums.pop()) def rotate1(self, nums, k): """ Do not return anything,...
def heapify(arr, index, heapSize): """ 查看index是否能够下沉 """ left = index *2+1 while left<heapSize: largest = left+1 \ if left+1 < heapSize and arr[left+1] > arr[left] else left largest = largest if arr[largest] > arr[index] else index if largest == index: ...
class Solution: def arrangeCoins1(self, n: int) -> int: i = 1 count = 0 while n>=0: n -= i count += 1 i += 1 if n<0: count -= 1 return count def arrangeCoins(self, n: int) -> int: # i = 1 count = 0 w...
from 链表类 import ListNode class Solution: def getIntersectionNode1(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return node_a = headA node_b = headB len_a = 1 while node_a.next: len_a += 1 node_a = node_a....
class Solution: def lengthOfLastWord(self, s: str) -> int: if not s: return 0 len_s = len(s) start = len_s-1 while not ( (s[start] >= 'A' and s[start] <='Z') or (s[start] >= 'a' and s[start] <='z') ): start -= 1 if start <0: return...
class RandomPool: def __init__(self): self.keyIndexMap = {} self.indexKeyMap = {} self.size = 0 def insert(self, key): if not key in self.keyIndexMap: self.keyIndexMap[key] = self.size self.indexKeyMap[self.size] = key self.size += 1 def de...
class Solution: def findWords(self, words): """ 给定一个单词列表,返回可以用同一行字母打印的单词 """ l= ['qwertyuiop','asdfghjkl','zxcvbnm'] ret=[] for word in words: for line in l: found = True for c in word.lower(): if c not i...
class Solution: def countPrimes1(self, n: int) -> int: if n<=2: return 0 if n == 3: return 1 count = 1 l = [2] for m in range(3,n): Flag = True for j in range((len(l))): if m % l[j] == 0: Flag...
from 链表类 import ListNode class Solution: def middleNode(self, head: ListNode) -> ListNode: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow if __name__ == "__main__": a = Solution() l = ListNode([1,...
class Solution: def maxCount(self, m: int, n: int, ops) -> int: """ 在执行给定的一系列操作后,你需要返回矩阵中含有最大整数的元素个数。 """ min_x = m min_y = n for op in ops: min_x = min(min_x, op[0]) min_y = min(min_y, op[1]) return min_x * min_y if __name__ == "__mai...
def divide(arr, num): l_arr = -1 r_arr = len(arr) i = 0 while i<r_arr: if arr[i]< num: arr[l_arr+1], arr[i] = arr[i], arr[l_arr+1] l_arr += 1 i+=1 elif arr[i] == num: i+=1 else: arr[r_arr-1], arr[i] = arr[i], arr[r_arr-1...
def heapSort(arr, asec=1, order_fun=lambda x: x): if not arr and len(arr)<2: return for i in range(len(arr)-1, -1,-1): heapify(arr,i,len(arr), asec, order_fun=order_fun) heap_size = len(arr) arr[0], arr[heap_size-1] = arr[heap_size-1], arr[0] heap_size -= 1 while heap_size>0: ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # def process(head): # if head == None: # return # # 1 # # 先序 print(head.val) # process(head.left) # # 2 # # 中序 print(head.val) # ...
from queue import PriorityQueue import heapq class KthLargest: def __init__(self, k: int, nums): self.h = nums[:] self.k = k # self.pq = PriorityQueue(maxsize=k) # for i in nums: # self.addpq(i) heapq.heapify(self.h) k1 = len(nums)-k whil...
class Node: def __init__(self, p, c): self.p = p self.c = c class NodeP(Node): def __lt__(self, other): return other.p < self.p class NodeC(Node): def __lt__(self, other): return self.c < other.c def findMaximizedCapital(k, W, profits, capital): from queue import Priori...
from 用列表实现栈 import MyStack class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack = MyStack() self.helper = MyStack() def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.s...
from 二叉树类 import TreeNode class Solution: def invertTree(self, root: TreeNode) -> TreeNode: def helper(root): if not root: return None root.left, root.right =helper(root.right), helper(root.left) return root return helper(root) if __name__ == "__...
class Solution: def intersect(self, nums1, nums2) : ret = [] for i in nums1: if i in nums2: ret.append(i) nums2.pop(nums2.index(i)) return ret if __name__ == "__main__": a = Solution() print(a.intersect([1,2,2,1,3], [2,3,3]))
import nltk from nltk import sent_tokenize from nltk import word_tokenize from nltk.stem import WordNetLemmatizer text = "I love Python Programming Language. I love to work with it. It is very easy to all for all ages peoples" words = nltk.word_tokenize(text) lemmatizer = WordNetLemmatizer() print(wor...
import os import sys import tempfile import ConfigParser class OneTimePad(): def __init__(self): # Read settings from config file parse = ConfigParser.ConfigParser() parse.read("config/app.ini") self.block_size = int(parse.get("settings", "otp.block_size")) self.prng ...
#!/usr/bin/env python # encoding: utf-8 str_input = raw_input("pls input sth >") str_encode = str_input.decode(encoding="utf-8") flag = True for i in range(len(str_encode)/2): if str_encode[i] != str_encode[len(str_encode)-i-1]: flag = False print u"是回文序列" if flag else u"不是回文序列"
x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] # How woul...
# Biggie Size def posbig(arr): for i in range(len(arr)): if(arr[i]>0): arr[i]='pos' print(arr) posbig([-1,2,5,-6,-9]) # Count Positives def lastposval(arr): count = 0 for i in range(len(arr)): if(arr[i]>0): count = count +1 arr[len(arr)-1] = count pr...
#!/usr/bin/env python3 def main(): limit = 1000 a = sum(x for x in range(limit) if x % 2 == 0 and fib(x)) print(a) print(a) def fib(a): return if __name__ == "__main__": main()
#-*- coding: utf-8 -*- class Singleton(type): def __init__(cls,name,bases,dict): super(Singleton,cls).__init__(name,bases,dict) cls.instance=None def __call__(cls,*args,**kw): if cls.instance is None: cls.instance=super(Singleton,cls).__call__(*args,**kw) ...
# 建立整个无环有向图 graph = {} graph["start"] = {} graph["start"]["a"] = 5 graph["start"]["b"] = 2 graph["a"] = {} graph["a"]["c"] = 4 graph["a"]["d"] = 2 graph["b"] = {} graph["b"]["a"] = 8 graph["b"]["d"] = 7 graph["c"] = {} graph["c"]["fin"] = 3 graph["c"]["d"] = 6 graph["d"] = {} graph["d"]["fin"] = 1 graph["fin"] = ...
__author__ = 'azmi' ''' British mathematician John Conway developed in 1970 so-called "Game of life". A simplified simulation of the development of cell colonies, of which various properties were the subject of discussion of mathematicians and computer scientists. The game is played on a rectangular board divided into...
__author__ = 'azmi' def checkpossibility(bh, gh): if len(gh) < len(bh): return False if bh[0] <= gh[0]: return False for a, b in zip(bh, gh): if b > a: return False return True t = int(raw_input()) for _ in range(t): m, n = map(int, raw_input().split()) ...
import tkinter as tk window = tk.Tk() window.title('my window') window.geometry('200x200')#这里是字母x不是乘号 var=tk.StringVar() l=tk.Label(window,bg='yellow',width=20,text='empty') l.pack() def print_selection(): l.config(text='youn have selected'+var.get()) rl=tk.Radiobutton(window,text='Option A', ...
import tkinter from tkinter import * root=Tk() e=Entry(root,width=50) e.pack() e.insert(0,"Enter Your Name") #function defination def myClick(): myLabel2=Label(root,text="Hello "+e.get()) myLabel2.pack() mylabel1=Label(root,text='Welcome in GoDigital ') button=Button(root,text='Enter Your Nam...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 2 15:16:25 2018 @author : gaurav gahukar : caffeine110 AIM : To Predict the Stock PRice of a perticular stock Using Recurrent Neural Network : Implimentation of RNN using LSTM layers """ #Phase - 1 : importing depende...
#Find GST Usign Python #By Programmers0_0; op = int(input("Enter Original Price:")) gst = int(input("Enter GST:")) cal = op * gst / 100 total = op + cal print("Total:", total)
# Function to find contiguous sublist with the largest sum # in a given set of integers def kadane(A): # stores the sum of maximum sublist found so far max_so_far = 0 # stores the maximum sum of sublist ending at the current position max_ending_here = 0 # traverse the given list for i in r...
#program for checking an integer is palindrome or not ''' a=int(input("Enter number of string you wanted to run:-")) list1=[] for i in range(a): a=str(input()) list1.append(a) print(list1) for index,items in enumerate(list1): if items==items[::-1]: print (items,",yes It is palindrome") ...
# the mathematics problem in x+y movie def mainFunc(cards): for c in range(0, len(cards)-1): if cards[c] == 1: cards[c] = 0 if cards[c+1] == 0: cards[c+1] = 1 else: cards[c+1] = 0 return cards if _...
MAX = 50 # Function to print Excel column name # for a given column number def printString(n): # To store result (Excel column name) string = ["\0"] * MAX # storing current index in str which is result i = 0 while n > 0: # Find remainder rem = n % 26 # if ...
import turtle PIXEL_POSITION = [(0, 0), (-20, 0), (-40, 0)] # positions for the 3 square pixels MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake: def __init__(self): self.snake_segment = [] self.create_snake() self.head = self.snake_segment[0] def...
""" Dictionary of PC Games """ d = {"MAX":"PAYNE", "STAR":"WARS", "CONTROL":1, "GTA":5, "FARCRY":3, "WITCHER":"GERALT OF RIVIA"} print("Enter a word") w = input().upper() # print(len(d)) print(w,d[w]) # print(d[w].lower().capitalize())
# Python code to convert temperature from celsius to fahrenheit temp_c = int(input("Enter temperature (in celsius):")) temp_f = ((temp_c/5)* 9 ) + 32 print("Temperature in Fahrenheit:", temp_f )
# Wave Print # For a given two-dimensional integer array/list of size (N x M), print the array/list in a sine wave order, i.e, print the first column top to bottom, next column bottom to top and so on. # Input format : # The first line contains an Integer 't' which denotes the number of test cases or queries to be run...