text stringlengths 37 1.41M |
|---|
# (1)
a = input('정수 1개를 입력 : ')
b = input('실수 1개를 입력 : ')
print(a + b)
# (2)
print(int(a) + float(b)) |
import sqlite3
conn = sqlite3.connect('ages.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Ages')
cur.execute('''
CREATE TABLE Ages (name VARCHAR(128), age INTEGER)''')
cur.execute('DELETE FROM Ages;')
cur.execute('INSERT INTO Ages (name, age) VALUES (?, ?)', ('Mathilda', 14));
cur.execute('INSERT IN... |
# 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, k):
if not head:
return None
size = 1
last = head
# get the size of LL
... |
'''
Given a binary tree, return the preorder traversal of its nodes' values.
pre-order traversal:
1. visit root
2. go to left sub-tree
3. visit the entire left sub-tree with pre-order traversal
4. go to right sub-tree
5. visit the entire right sub-tree with pre-order traversal
pseudo code:
def preorder(node):
if ... |
'''
Given a string and a string list, find the longest string in the list that can be formed by deleting some characters of the given string.
If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1... |
'''
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter.
Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice.Start is always smaller than... |
'''
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken in... |
'''
Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping.
A pattern is defined by its length and the number of repetitions.... |
'''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
'''
# dynamic programming
def maxSubArray(nums):
''' Demo
[0, 1, -3,... |
'''
A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).
Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.
Examples:
Input: sx = 1, sy = 1, tx =... |
'''
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below... |
'''
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent,
with the colors in the order red, white and blue. Use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort ... |
'''
Suppose you have a random list of people standing in a queue.
Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
Write an algorithm to reconstruct the queue.
Note:
The numbe... |
'''
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that
each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explan... |
'''
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
'''
class Solution:
def numSquares(self, n):
nSquare... |
'''
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
Y... |
'''
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3... |
'''
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you ... |
'''
Given a string s and an int k, return all unique substrings of s of size k with k distinct characters.
Example 1:
Input: s = "abcabc", k = 3
Output: ["abc", "bca", "cab"]
Example 2:
Input: s = "abacab", k = 3
Output: ["bac", "cab"]
Example 3:
Input: s = "awaglknagawunagwkwagl", k = 4
Outp... |
'''
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.733... |
'''
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
'''
class Solution:
... |
'''
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list.
These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the exampl... |
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
def ... |
'''
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16... |
from collections import defaultdict
class Cell(object):
remaining_values = {1, 2, 3, 4, 5, 6, 7, 8, 9}
final_value = None
def __init__(self, row, column, board, initial_value=0):
self.row = row
self.column = column
self.board = board
if initial_value:
self.fin... |
#FOR LOOP challenges 05
#Clay Palmer
number = int(input("Enter a number between 1 and 12: "))
for i in range(1,13):
print(number*i)
|
#WHILE LOOP challenges 05
#Clay Palmer
compnum = 50
guess = int(input("Enter a number: "))
count = 1
anotherGuess = 'Y'
while guess != compnum:
while anotherGuess == 'Y':
if guess < compnum:
print("Your guess is too low")
anotherGuess = str(input("Do you want another guess? (Y/N): ... |
#String Slicing Challenges 05
#Clay Palmer
word = str(input("Enter any word: "))
word = (word).upper()
print(word)
|
#WHILE LOOP challenges 02
#Clay Palmer
number = 0
while number <= 5:
number = int(input("Enter a number: "))
print("The last number you entered was",number,)
|
"""
Lab 2
"""
#4.1
my_name = "tom"
print(my_name.upper())
#4.2
my_id = "123"
print(my_id)
#4.3
my_id=your_id=123
print(my_id)
print(your_id)
#4.4
my_id_str="123"
print(my_id_str)
#4.5
#print(my_name+my_id)
#4.6
print(my_name + my_id_str)
#4.7
print(my_name*3)
#4.8
print('hello world. This is my first python stri... |
def decode(encoded):
# Write your code here
# reverse string
encoded = encoded[::-1];
result = ""
i = 0
while(i < len(encoded) - 1):
currVal = encoded[i]
nextVal = encoded[i+1]
val = (int) (currVal + nextVal)
if(val == 32):
result += chr(val)
... |
import os
import time
import numpy as np
import pandas as pd
from log import get_logger
logger = get_logger(__name__)
class MatchMaking:
"""
Implementation of a matchmaking algorithm to create balanced teams based on
a skill rating.
On initialization an initial seed is performed. When calling the ... |
import pandas as pd
from FileLoader import FileLoader
def youngestFellah(df, date):
m_min = df.loc[(df['Year'] == date) & (df['Sex'] == 'M')].min()['Age']
f_min = df.loc[(df['Year'] == date) & (df['Sex'] == 'F')].min()['Age']
min_age = {'m' : m_min , 'f' : f_min}
return (min_age)
f = FileLoader()
fl =... |
from recipe import Recipe
from book import Book
#print("What recipe do you want to add ?")
#name = input()
#print("What is its cooking level ?")
#lvl = input()
#print("What is the cooking time ?")
#time = input()
#print("What are the ingredients ?")
#ingr = input()
#print("What is the description ?")
#des = input()
... |
class Evaluator:
"""My evaluator"""
@staticmethod
def zip_evaluate(coefs, words):
if isinstance(coefs, list) == 0 or isinstance(words, list) == 0:
print("Both params should be lists")
elif len(coefs) != len(words):
print("Error, lists are not the same size")
e... |
#Created by Kamil Krawczyk
#03/04/2020
#Problem 2
#This program asks the user for two numbers and tells the user if the sum of the numbers is greater than, less than, or equal to 10.
def num_equation():
print("Input the first number - ")
x = int(input())
print("Input the second number - ")
y = int(i... |
"""
Запросите у пользователя значения выручки и издержек фирмы.
Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли... |
#!/usr/bin/env python
def quick_sort(unsorted, method='median'):
if len(unsorted) < 2:
return unsorted
piv = pivot(unsorted, method=method)
lesser = [i for i in unsorted if i < piv]
greater = [i for i in unsorted if i > piv]
piv_list = [i for i in unsorted if i == piv]
lesser = quic... |
import sys
for number in sys.stdin:
input_num=int(number)
n=0
max_in_the_group=1
while True:
if input_num<=max_in_the_group: print(n+1); break
else: n+=1; max_in_the_group+=(6*n)
|
n=int(input())
n_list=[]
for i in range(n):
n_list+=[int(input())]
n_list.sort()
for i in n_list:
print (i)
|
import random
cardarray = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
suits = ['Hearts', 'Clubs', 'Spades', 'Diamonds']
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def printcard(self):
self.cardlist = []
temp = ''
if self.va... |
'''
This is the exercises from the book titled 'Deep Learning with Python Keras'
Chapter 3: Getting started with neural networks
Section 6.2: Understanding recurrent nerual networks
section 6.2.1: A first recurrent layer in keras
reimplymented by zhiwen
date: 21-Jul-2018
'''
from keras import models, layers, losses, o... |
print("What's your name")#
x = input()
print("Thats a great name for an indian!")
print("How old are you?")
age = int(input())
if age >= 20:
print("Way too old")
if age < 20:
print("Too old")
print("How tall are you in centimeters?")
height = int(input())
if height >= 170:
print("Must have an extra chromo... |
def readias(r):
area=22//7*r**2
print(f"The area is:{area}")
p=int(input("Enter the redias:"))
readias(p) |
y=int(input("Enter the year"))
if y%4==0 and y%100!=0 or y%400==0:
print(f"The year {y} is leapyear")
else:
print(f"The year {y} is not leapyear")
|
#Equilateral ==
#Isosceles 2==
#Scalence !
def trang(a,b,c):
if a==b==c:
print("Equilateral")
elif a==b or b==c or a==c:
print("Isosceles")
else:
print("Scalence")
x=int(input("Enter 1st Side:"))
y=int(input("Enter 2nd Side:"))
z=int(input("Enter 3rd Side:"))
trang(x,y,z) |
# smallest element in ana array
from array import *
a=array('i',[])
n=int(input("Enter how many element:"))
for i in range(n):
a.append(int(input("Enter the element:")))
sm=a[0]
for i in range(1,len(a)):
if a[i]<sm:
sm=a[i]
print(f"The smallest element is:{sm}") |
def fac(n):
f=1
i=1
if n==0 or n==1:
return 1
else:
while i!=n:
f=f*n
n=n-1
return f
n=int(input("Enetr a number"))
ans=fac(n)
print(f"factorial={ans}")
"""
n=5-1=4-1=3-1=2-1=1
f=1*5=5*4=20*3=60*2=120
i=1""" |
# Exception Handling
# Errors
# Three types of errors
# 1) Compile time error
# compile time error ah chuan spelling te, semicolon dah hmaih te leh engemaw dah hmaih te khan a ni.
# 2) Logical error
# Logical error ah kha chuan run lai khan a hriat loh a run zawh a a output ah khan a hriat chauh a ni.
# Output dik lo t... |
## Recursion - recursion chu function call itself
# def a():
# print('Hello recursive function\n')
# a()
# a()
## Recursion set limit
# import sys
# print(sys.getrecursionlimit())
# import sys
# sys.setrecursionlimit(2000)
# print(sys.getrecursionlimit())
# i = 0
# def greet():
# global i
# i += 1
# ... |
a = int(input('Enter any number less than 5: '))
if a == 1:
print('your entered no. is: 1')
elif a == 2:
print('your entered no. is 2')
elif a == 3:
print('your entered no. is 3')
elif a == 4:
print('your entered no. is 4')
elif a == 5:
print('your entered no. is 5')
else:
print('wrong input bit... |
# constructor and self
# object kan siam apiang khan space tharah a in allocate thin.
class New:
pass
c1 = New()
print(id(c1))
# update dan kan lo zir ang
class Update:
def __init__(self, name, age):
self.name = name
self.age = age
def update(self):
self.age = 25
print(... |
a = 12
b = 2
a = a^b
b = a^b
a = a^b
print('a:',a,'\nb:',b)
|
# Multithreading
# Task lianpui kha te reuh te te ah kan then a chu mi te reuh te te chu thread chu a ni.
class Hello:
def run(self):
for i in range(5):
print('Hello')
class Hi:
def run(self):
for i in range(5):
print('Hi')
a = Hello()
a.run()
b = Hi()
b.run()
# A rua... |
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
text = open(file_path, "r")
text = text.read()
text = text.decode("utf-8")
text = text.replace("\n", " ")
text = text.replace("\r", " ")
text = text.replace("\t", " ")
text = text.split(" ")
words ... |
#!/usr/bin/env python3
# -*-coding:utf-8-*-
'''
测试生成器的send数据
'''
# def test():
# i = 1
# print('one line')
# temp = yield i
# i += 1
# print('two line', temp)
# yield i
#
# # 获取生成器
# gen = test()
#
# # one line
# next(gen)
#
# # 这个send的数据是发送给上一个yield点上进行接收的
# # two line haha
# gen.send('haha')
... |
import asyncio
# def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# yield b
# a, b = b, a + b
# n = n + 1
# return 'done'
# o = fib(6)
# print(o)
# for x in o:
# print(x)
def consumer():
r = 'a'
while True:
n = yield r
if not n:
return
... |
import threading
import time
# from threading import Thread
# 法一——封装的思想
class User(threading.Thread):
count = 10 # 定义一个类属性(全局变量)
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
while User.count > 0:
mutex.acquire()
print('%s... |
# 计算1~100的和
# sum = 0
# i = 1
# while i <= 10:
# sum = sum + i
# i = i + 1
# print("1~100的和为: %d" % sum)
# 计算1~n之间的和,n可以自己输入
sum = 0
i = 1
n=int(input('请输入:'))
while i <= n:
sum = sum + i
i += 1
print("1~%d的和为: %d" % (n,sum)) |
# # print("hello kitty")
# name = input("请输入姓名:")
# # print(name)
# a = 0
# if a > 0:
# print("aaa")
# else:
# print("bbb")
# """hel
# lo"""
# # "hel'lo"
# a = 1.5 * 3 + 2 # 乱写的
# a = 1.5 * 4 \
# + 3 - 2
#
#
# qqNum = 1234
# qqPsss = 3456
#
# print(qqNum)
# print(qqPsss)
str = "qwertyuiop"
a = str[1]
print... |
# g1 = (a * a for a in range(1, 5)) # 创建生成器法一
#
# print(next(g1)) # 用next()方法获得生成器的值
# print(next(g1))
# print(next(g1))
# print(next(g1))
#
# # print(next(g1)) #会报错,因为超过4次,所以的元素都显示完
# print('-----1-----')
#
# g2 = (a * a for a in range(1, 5))
# for i in g2: # 用for循环可以防止获取值得过程中出现报错
# print(i)
# print('-----2---... |
class Base:
def __init__(self):
self.basename = 'basename' # 父类属性不需要从外界传入
def base_func(self):
print('base_func()')
class Sub(Base):
def __init__(self): # ctrl+o 调用父类属性的快捷键
super().__init__() # 继承父类的属性,若父类有从外界传入的属性如:name,则此处应该为__init__(name)
self.subname = 'subname' #... |
for n in range(3,100):
for i in range(2,n):
if (n%i)==0:
break
else:
print('%d'% n,end=" ")
# i = 2
#
# for n in range(3,100):
# while i<n:
# if (n%i)==0:
# break
# i+=1
# else:
# print("%d" % n, end=' ')
|
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '点的坐标为(%d,%d)' % (self.x, self.y)
class Circle:
def __init__(self, r, point):
self.r = r
self.o = point
def __str__(self):
return '半径为:%d,圆心为:(%d,%d)' % (self.r, se... |
d = {'name': 'zhang3', 'score': 34, 'age': 10}
print(type(d))
print(d)
print('-' * 40)
d1 = {'name': 'zhang3', 'name': 'zhang3', 'age': 10} # 若有重复的,后面的会覆盖前面的元素
print(type(d1))
print(d1)
print('-' * 40)
print(d['name']) # 使用字典,通过键而不是索引值
print(d['score'])
print(d['age'])
print('-' * 40)
d1['name'] = 'li4' # 修改值
print(... |
a = None
def func():
if not a:
return True
else:
return False
def input_passward():
psw=input('请输入密码:')
if len(psw)>=8:
return psw
else:
ex=Exception('密码长度<8')
raise ex
if __name__ == '__main__':
# print(func())
# try:
# user_psw = input... |
# list1 = [1, 2, 3]
# list2 = [1, 'abc', 3]
# list3 = [1, [2, 5], 3, True]
#
# list4=list3.copy()
#
#
#
# print(list1)
# print(list2)
# print(list3)
# print(list2[1])
#
# print(type(0.2)) # type显示该数据的类型
# print(type(123))
print(type(True))
# print(type('abc'))
#
num = ['a', 'b', 'c']
print(num)
num[1] = 'ABC'
print(nu... |
# ==============================================================================
#
# Use:
# decrypt("Svool Dliow!")
# => "Hello World!"
#
# ==============================================================================
def decrypt(initial):
output = ""
alphabet = {}
for i in range(26):
... |
"""
You are required to write the code. You can click on compile & run anytime to check the compilation/ execution status of the program. The submitted code should be logically/syntactically correct and pass all the test cases.
Ques: The program is supposed to calculate the distance between three points.
For
x1 = 1 y... |
import numpy as np
from loader import MNIST
import pandas as pd
#sigmoid function
def sigmoid(z):
return 1/(1+np.exp(-z))
#sigmoid gradient function
def sigmoidgradient(z):
sig = sigmoid(z)*(1-sigmoid(z))
return sig
#forwardpropagation
def forwardprop(Theta1,Theta2,X,Y):
a1 = np.hstack([np.ones((len(X),... |
print()
# L1 How can we place a letter at the empty bottom right position
data = [
['O', 'X', 'O'],
['X', 'X', 'O'],
['X', 'O', '.']
]
# L2 How can we make the print board code above into a print board function we can re-use
# L3 How can we combine the data and the function into a Board class?
class ... |
""" Pour résoudre ce problème il est nécessaire de prendre le premier sous_mot
et de ce premier mot le découper en tous les sous_mots réalisable avec celui-ci
une fois que l'on a tous les sous mots possibles on regarde le plus long à l'intérieur
de tous les strings"""
import sys
N_word = int(input())
lines = []
for ... |
# coding:utf-8
'''
将华氏温度转换成摄氏温度
F = 1.8C + 32
Version:0.1
Author:不羡仙
Date:2019-5-30
'''
f = float(input("请输入华氏温度:"))
c = (f-32)/1.8
print("%.1f华氏度 = %.1f摄氏度" %(f,c)) |
# coding:utf-8
'''
打印三角形
Version:0.1
Author:不羡仙
Date:2019-5-30
* 3 1
*** 2 3
***** 1 5
******* 0 7
n =4
'''
n = 4
for i in range(1,n+1):
print(" "*(n-i),end='')
print("*"*(2*i-1),end='')
print()
|
names1 = ("Mg Mg","Aung Aung","Tun Tun","Su Su")
names2 = tuple(("Jhon Doe","Carrey","Robert","Plato")) # using Tuple Constructor
print(type(names1))
print(type(names2)) |
name = "Hello23123asd#fasd!fasDF"
print(name[len(name)-1]) # getting last index character
print(name[-10:-5]) # getting 5 character starting from last 10 t0 last 5 |
names = ["Mg Mg"]
names.append("Aung Aung") # ["Mg Mg","Aung Aung"]
names.append("Tun Tun") # ["Mg Mg","Aung Aung","Tun Tun"]
# ["Mg Mg","Aung Aung","Tun Tun"]
names.insert(0,"Su Su")
print(names[0])
print(names[1])
print(names[2])
print(names) |
class Main: # blueprint
name = "Mg Mg"
def change(self):
print(self.name)
m1 = Main() # Main().name
m1.name = "Aung Aung"
m1.change()
m2 = Main()
m2.name = "Tun Tun"
m2.change()
"""
to use properties or methods of a class, create its instance object
m1 => #x123123 => class Main: # blue... |
names1 = ("Mg Mg","Aung Aung")
names2 = ("Tun Tun","Su Su")
names = names1 + names2
name = '-'.join(names1) # from tuple make string value seperated by ,
namey = names1 * 4
print(names)
print(name)
print(namey) |
student = {
'name':'Mg Mg',
'age':20,
'heigh':5.11,
'city':'Rangoon',
'father':'U Hla',
'mother':'Dar Nu',
20:"He He"
}
print(student['name'])
print(student['age'])
print(student['city'])
print(student['heigh'])
print(student[20])
print(student)
"""
dictionary
-> use {} curle... |
ceetee = list(("Rangoon","Mandalay")) # memoty address #123 # ["Rangoon","Mandalay"]
bt = ceetee #bt => memoty address #123 # Value pass by Refrence
# ceetee[0] = "Hsipaw"
# bt[1] = "Siggai"
bt = ceetee.copy() # by value
bt[0] = "Hsipaw"
print(bt)
print(ceetee) |
name = "Mg Mg"
age = 20
bol = name == "Mg Mg" and age == 20
bol = name == "Aung Aung" or age == 21
bol = not(name == "Mg Mg")
print(bol)
"""
and
-> operator true if only left and right value are true
ro
-> operator true if one/both of the left or right value is true
not
->... |
def avg(arr): # the function that finds the average of the even indices elements
total = 0 # this variable finds the total of the elements at even indices only
divisor = 0 # this variable counts the number of even indices
for i in range(len(arr)): # a loop that goes from 0 to the length of the array
if i % 2 == 0:... |
import random
def coinToss():
number = int(input("How many coin tosses? "))
heads = 0
tails = 0
toss = 0
for x in range(number):
toss = random.randint(0,1)
if toss == 0:
heads += 1
else:
tails += 1
print("Heads: {}"... |
import tkinter as tk
def decalage(lettre_message):
a=ord(lettre_message)
if (a > 90 and 97 > a) or 65 > a :
return chr(ord(lettre_message) + 0)
elif a > 122 or (97 > a and a > 90) :
return chr(ord(lettre_message) + 0)
if a == 90 :
return chr(ord('A'))
if a == 1... |
from pymongo import MongoClient
# Establishing a connection
client = MongoClient() # connects to localhost by default
db = client["test"]
# Verifying connection to MongoDB
print("Total number of documents in the 'titanic' collection: ", db.titanic.count_documents({}))
print(db.titanic.find_one())
# Filtering
print(... |
import math
import sys
'''
a "Weber Street" (2,-1) (2,2) (5,5) (5,6) (3,8)
a "King Street S" (4,2) (4,8)
a "Davenport Road" (1,4) (5,8)
g
'''
street = []
st_name = [] #to save all the unique street names
#vertices = []
coords = {} #Dictionary of {street name:2-d Coordinates}
EDGES = [] #list of all the edges
V ... |
def fat(valor):
resultado = 1
while valor > 1:
resultado = resultado * valor
valor-= 1
print(resultado if valor > 0 and valor == int(valor) else -1)
fat(int(input("Fatorial: "))) |
# Import dependencies
import numpy as np
import random
import operator
import pandas as pd
import matplotlib.pyplot as plt
# Part of python's Data Model
# Objects are python's abstraction of data and way to interact with other data
# Create City class
class City:
# Double under or dunder methods are pre existing... |
# simple function
def my_function():
print("Hello From My Function!")
# my_function()
# function with argument
def my_function_with_args(username, greeting="Halo"):
print("Hello, %s , From My Function!, I wish you %s" % (
username, greeting)
)
# my_function_with_args("Mahrus", "JADI BARU")
# fu... |
import turtle
def random_fractal(t, x):
if ( x < 3 ):
t.fd(x)
return
else:
random_fractal(t, int(x/3))
t.lt(90)
random_fractal(t, int(x/3))
t.rt(90)
random_fractal(t, int(x/3))
t.lt(90)
random_fractal(t, int(x/3))
t.r... |
import unittest
from main import to_upper
class MyTestCase(unittest.TestCase):
def test_to_upper(self):
name = "Shubham"
upper_name = to_upper(name)
self.assertEqual(upper_name, "SHUBHAM")
if __name__ == '__main__':
unittest.main()
|
# The goal of the agent is to navigate a frozen lake and find the Goal without falling through the ice the
# Using the Q-learning algorithm
import gym
import numpy as np
import matplotlib.pyplot as plt
env = gym.make('FrozenLake-v0') # environment
RENDER = False # Visualise training
STATES = env.observation_space.n ... |
doc_list = ['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?']
keyword = 'casino'
response = []
for sentence in doc_list:
is_contained = False
word_list = sentence.strip().lower().split()
print(word_list)
for word in word_list:
if word == keyword.lower():
... |
N = int(input())
dishes = [int(input()) for _ in range(N)]
dishes.reverse()
for i in range(N):
if dishes[i] > dishes[i + 1]:
print(dishes[i + 1])
break
else:
continue
|
A = input()
answer = ""
if A == "a":
answer = -1
elif len(A) == 1:
answer = "a"
else:
for i in range(len(A)-1):
answer += A[i]
print(answer)
|
#
# Tile 0, 1, X or W
#
TILE_TYPE = dict(EMPTY = 0, SHIP_HULL = 1, HIT = 2, MISS = 3, HIDDEN = 4)
class Tile(object):
'''One tile'''
#constructor
def __init__(self, type):
if type == TILE_TYPE['EMPTY']:
self.__m_type = ('0', TILE_TYPE['EMPTY'])
elif type == TILE_TYPE['SHIP_HULL... |
# There're some illegal cases, it's unfair
import re
class Solution:
# Define the precedence of operators
__pre = {}
__fun = {}
def __init__(self):
pre_count = -1
self.__pre['('] = pre_count
pre_count += 1
self.__pre['+'] = pre_count
self._... |
''' PyPoll Solution
Author: Surabhi Mukati
Notes: This script expects the data called election_data.csv to be in a Resources folder.
Purpose: This script calculates the total number of votes cast, a complete list of candidates who received votes,
the percentage of votes each candidate won, the total number of votes eac... |
x = ('Glen', 'Sally', 'Joseph')
print(x[2])
y = (1, 9 , 2)
print(y)
print(max(y))
for iter in y:
print(iter) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.