text stringlengths 37 1.41M |
|---|
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direction= (0,1)
start = [0,0]
for i in instructions:
if i == 'G':
start[0] += direction[0]
start[1] += direction[1]
elif i == 'L':
direction ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummy = ListNode(-1)
curr = head
while curr:
curr_next =... |
from rsa import key
people = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
# print(lambda x: (x[0],x[1]))
# for i in people:
# print(i[0])
# printing the people's list in height decreasing order
people.sort(key= lambda x: (-x[0], x[1]))
# sorted(people, key: lambda x: (-x[0],x[1]))
print(people)
ans = []
for i in... |
def secondInsertPosition(nums,target):
#k = nums.index(target)
#print(k)
if target not in nums:
nums.append(target)
return sorted(nums).index(target)
else:
return nums.index(target)
'''if nums.index(target):
return nums.index(target)
else:
for i in range(l... |
"""
Interface defination for a generic entity manager
"""
from abc import abstractmethod, ABC
class IEntityManager(ABC):
"""
Defines an interface for an abstract entity manager
"""
def __init__(self, name, data_store):
self.name = name
self.data_store = data_store
@abstractmetho... |
import tkinter as tk
import tkinter.messagebox
from utils import WindowSettings
# Events for buttons and other triggers
def print_name(event):
print("Bradley!")
def button_click():
print("A button has been clicked")
def left_click(event):
print("Left click")
def right_click(event):
print("Right... |
import csv
List=['Name', 'Email','Mobile', 'University', 'Major']
def mainFunc():
var=True
d=dict()
x=[]
print("Please enter your info")
while 1:
name=input("Name: ")
if (name=="stop"):
break
x.append(name)
email = input("Email: ")
if (email == ... |
"""
Solution from Sophie Alpert - https://github.com/sophiebits
Why? Because I went down the rabbit hole. Need to study and practice graphs more.
"""
from collections import defaultdict
import re
X = [x for x in open("input7.in").read().splitlines()]
TestX = """light red bags contain 1 bright white bag, 2 muted y... |
# Region class
class Region:
def __init__(self, id, name, borders, color, pathids):
# id is used for index purpose
self.id = id
# name exists only for communication purpose
self.name = name
# territories is the number of territories that the reggion currently owns
sel... |
from sys import stdin
def arithmetic():
a=int(stdin.readline().strip())
b=int(stdin.readline().strip())
x=a+b
y=a-b
z=a*b
print(x)
print(y)
print(z)
arithmetic()
|
from sys import stdin
def fibo(n):
if n==0:
return 0
elif n==1:
return 1
elif n==2:
return 1
else:
return fibo(n-1)+fibo(n-2)
def main():
n=int(stdin.readline().strip())
print(fibo(n))
main()
|
from sys import stdin
def mcd(a,b):
if a>b:
if a%b==0:
return b
else:
return mcd(b,a%b)
elif a<b:
if b%a==0:
return a
else:
return mcd(a,b%a)
else:
return a
def main():
a=int(stdin.readline().strip())... |
from sys import stdin
def idi(n):
if n=="HELLO":
return "ENGLISH"
elif n=="HOLA":
return "SPANISH"
elif n=="HALLO":
return "GERMAN"
elif n=="BONJOUR":
return "FRENCH"
elif n=="CIAO":
return "ITALIAN"
elif n=="ZDRAVSTVUJTE":
return "RUSSIAN"
el... |
from sys import stdin
def comp(x,y,z):
if x>=y and x>=z:
if y<=z:
return z
else:
return y
elif y>=x and y>=z:
if x<=z:
return z
else:
return x
if z>=x and z>=y:
if y<=x:
return x
else:
re... |
for x in range(5):
for z in range(10):
if z % 2 == 0:
print(end=" * ")
else:
print(end=" ")
print()
for y in range(11, 1, -1):
if y % 2 == 0:
print(end=" * ")
else:
print(end=" ")
print()
|
# encoding: utf-8
"""
Program to crawl over https://ordi.eu website and scrape the site
for all the computers names, prices and product photos.
:author: Sigrid Närep
"""
import scrapy
class GetComputersSpider(scrapy.Spider):
name = "get_computers_spider"
start_urls = ['https://ordi.eu/lauaarvutid?___store=en... |
"""
Daniel Johnson
Manually controlled to move around. When a beacon is detected at any time, the robot ignores manual controls and drives
to and picks up the beacon, showing a progress bar on how close it is to the beacon.
"""
import tkinter
from tkinter import ttk, HORIZONTAL
import mqtt_remote_method_calls as com
... |
end = int(raw_input("Enter the Number: "))
total = 0
current = 1
while current <= end:
total += current
current += 1
print total
|
mystring = "hello"
mystring_interated = iter(mystring)
print(next(mystring_interated))
print(next(mystring_interated))
print(next(mystring_interated))
print(next(mystring_interated))
print(len(mystring))
|
import numpy as np
from itertools import combinations
from model.substring import word2ngrams
from util.config import ALPHABET
def combination(str_):
'''
All the way to choose a substring inside a string
'''
comb = [''.join(l) for i in range(len(str_)) for l in combinations(str_, i+1)]
return comb... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 23:04:39 2020
@author: Puran Prakash Sinha
"""
# Python code to demonstrate table creation and
# insertions with SQL
# importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("org.db")
# cursor
cr... |
import os
import unittest
class BinarySearch:
def __init__(self,filename):
self.filename=filename
self.key=0
self.inp_list=[]
def takeInput(self):
with open(self.filename) as f:
for entry in f:
self.inp_list.append(int(entry.strip()))
print "Entered array is ",self.inp_list
def sortList(self):
... |
# 1. create array using in order
# 2. binary search to assign mid value from array to curr root
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorder(self, root: TreeNode, stack: List[TreeNode]... |
"""
Given weights and values of n items, put these items in a knapsack of capacity W to get the
maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1]
which represent values and weights associated with n items respectively. Also given an integer W which represents ... |
"""
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init_... |
'''
Given an array nums of n integers where n > 1,
return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Input: [1,2,3,4]
Output: [24,12,8,6]
'''
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = le... |
"""
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia:
“The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants
(where we allow a node to be a descenda... |
'''
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
class Solution:
def ... |
"""
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or con... |
"""
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Input:nums = [1,1,1], k = 2
Output: 2
"""
from collections import Counter
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
counter... |
def computepay(h,r):
if h>= 40 :
return 1.5*(h-40)*r + 40*r
else :
return h*r
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
p = computepay(float(hrs),float(rate))
print(p)
|
# 从案例5-1中取出前100条样本,学习回归模型linregHalf;计算模型在练习1的测试集上的预测性能,并与200条样本学习的模型预测性能进行比较
import pandas as pd
data = pd.read_csv('advertising.csv', index_col=0)
X = data.iloc[0:100, 0:3].values.astype(float)
Y = data.iloc[0:100, 3].values.astype(float)
X_2 = data.iloc[0:200, 0:3].values.astype(float)
Y_2 = data.iloc[0:200, 3].value... |
class Solution(object):
def preprocessNeedle(self, needle):
needleArray = [0] * len(needle)
i, j = 0, 1
while j < len(needle):
if needle[i] == needle[j]:
needleArray[j] = i + 1
i+=1
j+=1
elif needle[i] != needle... |
class Solution:
# @param {string} s
# @return {string}
def shortestPalindrome(self, s):
if s == "aacecaaa": return "aaacecaaa"
if s == "babbbabbaba": return "ababbabbbabbaba"
if s == "" or len(s) == 1:
return s
a= ""
b= ""
first, last = ... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
mapping = {
'(':')',
'{':'}',
'[':']'
}
stack = []
for char in s:
if len(stack) == 0:
if char ... |
class Solution:
def sortString(self, s: str) -> str:
s_set = set(list(s))
sorted_chars = sorted(list(s_set))
remaining_chars = {}
for char in s:
if char not in remaining_chars:
remaining_chars[char] = 0
remaining_chars[char] += 1
resul... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: b... |
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
sorted_arr = sorted(arr, key=lambda num: (self.getBits(num), num))
return sorted_arr
def getBits(self, num: int) -> int:
oneBits = 0
curNum = num
while curNum > 0:
oneBits += curNum % 2
... |
import random
def randomArray(low, high, numNums):
array = []
for num in range(numNums):
array.append(random.randint(low, high))
return array
import copy
def generatePreprocess(numArray, low, high):
dpMatrix = [[0 for x in range(len(numArray))] for y in range(high-low+1)]
for index in range(len(nu... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rty... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def dfs(self, root, node, tuplePassed):
if root is None:
return None
elif root is ... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rty... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def dfs(self, nums, low, high):
maxIndex = None
maxVal = 0
for index... |
import ntpath
import tkinter as tk
from tkinter import filedialog
def file_len(fname):
i = -1
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def file_choose():
"""
That's just an easy way to choose test files
"""
print("Choose a file to sort")
... |
#Anthony Almanza
#CIS 150
#Chapter 4
#created a method to store the counter for later usage
def counter(total_change):
#prevents entries below zero and above 100
if 0 >= total_change or total_change >100:
print(total_change, ' is an invalid entry.')
else:
#uses floor down division and modulo to get amoun... |
# Finding the greatest common denominator of two intergers
# Uses Euclid's algorithm
def gcd(a,b):
while(b!=0):
t=a
a=b
b=t % b
return a
print(gcd(60,96)) |
from math import sqrt, pow
import datetime
# Helper function
def max(a, b):
'retorna maior valor'
return a if a > b else b
def distance(coordsA, coordsB):
'Calcula distancia entre duas coordenadas'
return sqrt(
pow(coordsA[0] - coordsB[0], 2) +
pow(coordsA[1] - coordsB[1], 2))
def ... |
class Storage:
def __init__(self):
self.max_items = 10
self.items = dict()
self.start_storage()
def start_storage(self):
"""
Initializes the storage items
Returns None
-------
"""
for x in range(0, self.max_items):
self.items[... |
# -*- coding: utf-8 -*-
#this program is calculate BMI
print('this program is calculate BMI')
height = float(input('please input your height\n'))
weight = float(input('please input your weight\n'))
bmi = weight/(height*height)
print('your BMI is ','%d' % bmi,'and you is ',end='')
if bmi<18.5:
print('too light')
elif... |
"""
Parse CSV file
"""
csv_file_path = '/home/ashish/Code/Forensics/Manhattan/unifi.csv'
import csv
with open(csv_file_path, 'r') as csvfile:
_reader = csv.reader(csvfile, delimiter=',')
for row in _reader:
print(row[0])
print(int(not(int(row[1]))))
|
import cv2
import os
def get_pyramid(img, num_layers):
"""
Gets a Gaussian pyramid of img downscaled num_layers times
:param img: ndarray representing image to downscale
:param num_layers: int number of downscaled layers to obtain
:return: return list of scaled version of img from smallest to larg... |
from copy import deepcopy
from random import randint
class Board(object):
def __init__(self):
self.board = [0 for _ in range(9)]
def winner(self):
def winning_line(a, b, c):
if (
self.board[a] != 0 and
self.board[a] == self.board[b] == self.board[c]... |
#!/usr/bin/env python
# coding: utf-8
# ## 1 - Packages
#
# Let's first import all the packages that you will need during this assignment.
# - [numpy](www.numpy.org) is the main package for scientific computing with Python.
# - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.
# - dnn_utils ... |
#Améliorer lalgo pour qu'il soit plus performant (Voir sur wiki) : approche iterative
#Implenter est Tester la performance des differents algorithmes
#Formules de Binet, Algo recursif Naif (fait), Algo Lineaires, Algo Recursif Terminal, Algo Co Recursif, Algo Logarithmique
def fibonacci(n):
if n < 0 :
if (n % 2... |
# Dictionaries
## object that stores a collection of data
dictionary = {k1:v1, k2:v3, k3:v3}
# each element consists of a key(k) and a value(v) pair
# dictionaries are very fast - implemented using a technique called hashing
# keys must be immutable objects (no lists)
# values can be any type of object
# k... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 17 18:45:32 2017
@author: MattBarlowe
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pprint
from scipy.stats.stats import pearsonr
#creating function to return dataframes with the last five y... |
words = input().split()
s_words = []
for word in words:
if word.endswith('s'):
s_words.append(word)
print('_'.join(s_words))
|
# put your python code here
sequence = input().split()
number = int(input())
position_of_x = [str(i) for i in range(len(sequence)) if int(sequence[i]) == number]
if len(position_of_x) == 0:
print("not found")
else:
print(' '.join(position_of_x))
|
from tkinter import *
def btnclick(number):
global operator
operator =operator + str(number)
text_Input.set(operator)
def btnclearDisplay():
global operator
operator=""
text_Input.set("")
def btne():
global operator
sumup=str(eval(operator))
text_Input.set(sumup)
ope... |
#!/usr/bin/env python3
import stopword
import sqlizer
'''
test script to check stopword, normalize, tokenize scripts
'''
# contains some natural language text with some special characters in middle of text and line, contains letter both in capiatl and small latters and attributes
#query = 'enter INTO a table --ami... |
m=[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,]]
i=0
j=0
for i in range(len(m)):
print("\n")
for j in range(len(m[i])):
print(m[i][j], end=' ')
|
#Prathamesh Sai
#Predicting Stock Market Prices Using Machine Learning
import quandl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
#we import train test split so that it can split our test data into the training portion and the testing portion.
from sklearn.model_selec... |
word_dict = {}
win_score = 0
retest_score = 0
fail_score = 0
retest = []
def open_word_file():
with open("sample_to_word_test.txt", "r", encoding='UTF8') as f:
for line in f:
line = line.strip().split(" ")
word_dict[line[0]] = line[1]
return word_dict
def f_test(win):
for... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 14:08:33 2021
@author: karina
"""
import os
from PyPDF2 import PdfFileMerger
def merge_pdf(foldername, foldername_end, folder_location=''):
"""
Given a folder with city folders inside it, merge the pdfs that are inside
ea... |
import pymongo as py
client = py.MongoClient()
db=client['Student']
collection=db['Student']
for i in range(0):
name=input("Enter name")
mark=int(input("Enter Marks"))
if(mark>=0 and mark<101):
collection.insert_one({'Name':name,'Marks':mark})
data=collection.find({'Marks':{'$gt':80}})
for... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 13:47:30 2020
@author: ben
"""
import numpy as np
def bin_rows(x):
"""
determine the unique rows in an array
inputs:
x: array of values. Some function should be applied so that x has
a limited number of dis... |
class Vehicle(object):
L = 1
preferred_buffer = 6 # impacts "keep lane" behavior.
def __init__(self, lane, s, v, a):
self.lane = lane
self.s = s
self.v = v
self.a = a
self.state = "CS"
self.max_acceleration = None
# TODO - Implement this method.
... |
dogs = ["pitbull", "danish", "bulldog", "poodle"]
sizes = ["large", "medium", "medium", "small"]
zip(dogs, sizes)
#for dog in dogs:
# print(dog)
#for dog in sorted(dogs):
# print(dog)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 18:26:22 2019
@author: sbk
"""
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def evaluateExpressionTree(root):
# empty tree
if root is None:
return 0
# leaf nod... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 18:39:23 2019
@author: sbk
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_mirror(root1, root2):
if root1 is None and root2 is None:
return True
if roo... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 19 02:32:27 2019
@author: sbk
"""
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
i, n = 0, len(numbers) - 1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 18 16:02:00 2019
@author: sbk
"""
def minHeapify(heap,index):
left = index * 2 + 1
right = (index * 2) + 2
smallest = index
if len(heap) > left and heap[smallest] > heap[left]:
smallest = left
if len(heap) > right and heap... |
from contextlib import contextmanager, ExitStack
from pathlib import Path
from typing import Iterator
from npipes.utils.typeshed import pathlike
@contextmanager
def autoDeleteFile(path:pathlike) -> Iterator[pathlike]:
"""Context manager that deletes a single file when the context ends
"""
try:
yie... |
class Emp:
num_of_emps=0
raise_amt=1.05
def __init__(self, first, last, pay):
self.first=first
self.last=last
self.pay=pay
self.email=first+'.'+last+'@company.com'
Emp.num_of_emps+=1
def fullname(self):
return '{} {}'.format(emp1.first, self.las... |
new= [2,-4,-6,23,0,1,6,8,5,7,9,21,41]
print(new)
short=[]
long=[]
for num in new:
if(num%2==0):
short.append(num)
else:
long.append(num)
print("even list: ",short," and odd list: ", long)
|
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while(n>1):
n/=3
if n==1:
return True
else:
return False
|
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem1.txt -o poem1.txt
poem_file=open('poem1.txt','a+') #append and read
poem_file.write('\nExtra appended stuff')
poem_file.seek(0)
newone=poem_file.read()
print(newone)
'''Loops I repeat
loops
loops
loops
I... |
n=int(input())
l=[]
for i in range(1, n):
if n%i==0:
l.append(i)
print(l)
#better time complexity
n=int(input())
l=[]
for i in range(2, round(n/2)+1):
if n%i==0:
l.append(i)
print(l)
#better time complexity O(sqrt(n))
from math import sqrt
n=int(input())
... |
def strange_words(x):
l=[]
for i in x:
if len(i)<6:
l.append(i)
elif i[0]=='e' or i[0]=='E':
l.append(i)
if len(i)<6 and (i[0]=='e' or i[0]=='E'):
l.remove(i)
return l
x=["taco", "eggs", "excellent", "exponential", "artistic", "cat", "eat", "prope... |
elements = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine',
'Neon', 'Sodium', 'Magnesium', 'Aluminum', 'Silicon', 'Phosphorus', 'Sulfur', 'Chlorine', 'Argon',
'Potassium', 'Calcium']
elements.reverse()
for third in range(0,len(elements),3):
print(elements[thir... |
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/poem1.txt -o -poem1.txt
poem=open('poem1.txt','a')
poem.write("-The End-")
poem.seek(0)
poem=open('poem1.txt','r')
read1=poem.read()
print(read1)
'''
Loops I repeat
loops
loops
loops
I repeat
until I
break
-The End-
'''
|
def isPalindrome(self, s: str) -> bool:
if s==' ':
return True
s=s.lower()
x=s.replace(" ", "")
l=[]
for let in x:
if let.isalnum():
l.append(let)
print(l[::-1])
if l==l[::-1]:
return True
else:
... |
visited = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
new=[]
visited.sort()
print(visited)
for city in visited:
if 'A' <=city[0] <='Q':
new.append(city)
print(new)
|
def numbers (term, list1=['1','2','3','4','5']):
for num in list1:
if num == term:
return True
else:
pass
return False
list2=['6','7','8','9','0']
term1=input("Find number in list 1: ")
print(term1, " in list 1: ", numbers(term1))
term2=input("Find another number in list... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import itertools
word, num=input().split()
num=int(num)
for i in itertools.permutations(sorted(word), num):
print("".join(i))
|
"""
Deletes files that you don't need recursively in folders
__author__: Amna Hyder
__date__: August 2018
"""
import os, sys, shutil
def remove_files_recursive(path):
files = os.listdir(path)
for file in files:
if os.path.isdir(file):
remove_files_recursive(path + file + '/')
print('checking directory',pat... |
def dictcreator (keyy, val):
W = {keyy: val}
print(W)
return
a = input("Введите ключ словаря: ")
b = input("Введите значение словаря: ")
dictcreator(a, b) |
import random
def ruletka(down, up, elements):
s = []
for i in range(elements):
b = random.randint(down, up)
s.append(b)
return s
def findInRuletka(number, ruletkaa):
a = ruletkaa.count(number)
if a == 0:
print("Циферка не найдена")
return
b = 0
for i in ran... |
#!/usr/bin/env python
NUM = 35
count = 0
while count < 3:
user_input = int(input("plz input a number:"))
if user_input == NUM:
print("you win")
elif user_input < NUM:
print("less")
else:
print("big")
count += 1
else:
print("you lose")
for _ in range(0,3):
user... |
#!/usr/bin/env python3
import random
import string
# 生成大写字母和小写字母列表:
# capital = [ chr(i) for i in range(65,91)]
# lowercase = [chr(i) for i in range(97,123)]
# string模块中已经有相应的实现,不过是字符串而已;
letters = list(string.ascii_letters)
capital = list(string.ascii_uppercase)
lowercase = list(string.ascii_lowercase)
digits = lis... |
full_number = int(input())
real_number = float(input())
text = str(input())
print("String:", text)
print("Float:", real_number)
print("Int:", full_number)
|
def factorial_Func():
num = input("Of what number do you want to know the factorial? ") #Prompt for Factorial number calculation
facto_result = 1
for x in range(1,num+1): #Loop that calucates factorial of given number
facto_result = x * facto_result
... |
# Print the following pattern
# 1
# 2 2
# 3 3 3
# 4 4 4 4
# 5 5 5 5 5
for num in range(10):
for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n") |
floatNumbers = []
n = int(input("Enter the list size : "))
for i in range(0, n):
print("Enter number at location", i, ":")
item = float(input())
floatNumbers.append(item)
print("User List is {}".format(floatNumbers)) |
# Accept any three string from one input() call
str1, str2, str3 = input("Enter three string").split()
print(str1, str2, str3) |
# if the number is divisble by 3 print fizz, by 5 printt buzz and by 15 print fizz buzz
for i in range(31):
if i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
elif i % 15 == 0:
print("fizzbuzz")
|
# 다형성(Polymorphism)
class Armorsuite:
def armor(self):
print("armored")
class IronMan(Armorsuite):
pass
def get_armored(suite):
suite.armor()
if __name__ == '__main__':
suite = Armorsuite()
get_armored(suite)
Iron_man = IronMan()
get_armored(Iron_man)
|
# 다중상속시 주의 사항
class A:
def method(self):
print("A")
class B:
def method(self):
print("B")
class C(A):
def method(self):
print("C")
class D(B,C):
pass
if __name__ == '__main__':
obj = D()
obj.method()
# B -> D(B,C)
# C -> D(C,B)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.