text stringlengths 37 1.41M |
|---|
#1번, B835193 석채원
interest = float(input("이자율을 입력하시오:"))
target = float(input("목표배율을 입력하시오:"))
#initialize year
year =0
initmoney=money=10 #any number is fine, since we deal with ratio
while 1:
money=money+(money*interest)
year+=1
if(money>=initmoney*target):
break;
print("이자율이 %g 일 때 원금의... |
lst1 = [2, 5, 9, 6, 9, 3, 8, 9, 7, 1]
for i, v in enumerate(lst1):
# print(i, ":", v)
if lst1.count(v) > 1:
print(v)
break;
for i in (lst1):
print(i)
if(i > 1):
print("r:", i)
print("---------------")
for x in range(1, 6):
print(x)
print("---------------")
lst2 = ["sun", ... |
'''
287. Find the Duplicate Number
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one duplicate number in nums, return this duplicate number.
Follow-ups:
How can we prove that at least one duplicate number must exist in nums?
Can you sol... |
# [ < expression > for < element > in < iterable > ]
# There's also an optional 'if' condition:
# [ < expression > for < element > in < iterable > if < condition > ]
squares = [x * x for x in (1, 2, 3, 4)]
print(squares)
# Get a list of uppercase characters from a string
s1 = [s.upper() for s in "Hello World"]
print(... |
import os
f = open("./file1.txt", "r")
print(f.read())
print(f.read(200))
print(f.readline())
for x in f:
print(x)
f.close()
f = open("./file2.txt", "a")
f.write("Now the file has more content!")
f.close()
# open and read the file after the appending:
f = open("./file2.txt", "r")
print(f.read())
f = open("./... |
class Solution:
def permute(self, nums):
res = []
def permuteHelper(start):
if start == len(nums) - 1:
res.append(nums[:])
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start]
permuteHelper(start + 1)
nums[start], nums[i] = nums[i... |
user_input = input("Enter text: ")
reversed_input = user_input[-1::-1]
if user_input == reversed_input:
print("Palindrome")
else:
print("Not a palindrome")
|
# List Comprehensions
'''
Let's learn about list comprehensions!
You are given three integers x, y, z and representing the dimensions of a cuboid along with an integer n.
Print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k
is not equal to n. Here, 0 <= i <= x; 0 <= j<= ... |
class Hero(object):
def __init__(self, name = "Incognito"):
self.name = name
self.health = 20
self.power = 5
self.max_health = self.health
self.xp = 0 #experience points
self.level = 1
self.gold = 0
def check_level(self):
if self.xp > 3:
self.level = 2
self.level_up()
def level_up(self):
s... |
name = input("what's your name? ")
if len(name) < 3:
print("the name must have at least three characters long")
elif len(name) > 50:
print("the name is too long, can be only a maximum fifty characters long")
else:
print("name looks good!")
|
has_high_income = True
has_good_credit = False
has_criminal_record = False
if has_high_income and has_good_credit and not has_criminal_record:
print("eligible for loan")
elif has_high_income or has_good_credit and not has_criminal_record:
print("need more analisys")
else:
print("ineligible for loan")
|
names = ["John", "Bob", "Mosh", "Sarah", "Mary"]
print(names[0])
print(names[-1])
print(names[2:])
print(names[2:5])
names[0] = "David"
print(names[0])
|
import pandas as pd
import numpy as np
'''items = ['pen', 'pencil', 'sharpner', 'eraser', 'scale']
Jan_Sales = [100,109,45,33,23]
Feb_Sales = [18,88,102,87,78]
Mar_Sales = [121,45,65,82,95]
Apr_Sales = [78,69,89,83,98]
May_Sales = [36,87,69,98,43]
All_Sales = np.array([Jan_Sales,Feb_Sales,Mar_Sales,Apr_Sales,Ma... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def display(a):
while a:
print a.val,
a=a.next
class Solution:
# @param A : head node of linked list
# @param B : head node of linked list
# @return the head node... |
class Solution:
def fractionToDecimal(self, n, d):
if n == 0: return "0"
if d == 0: return ""
ans = ""
if(((n < 0)^(d < 0)) > 0): ans = ans + "-"
n = abs(n)
d = abs(d)
ans = ans + str(n/d)
r = (n%d)*10
print r,n,d,ans
if( r == 0): return a... |
#-*- coding: UTF-8 -*-
def HelloWorld():
# Faça um código que apresente "Hello World" na tela
print("Hello World")
def BemVindo():
# Faça um código que solicite nome, sobrenome e idade do usuário.
# Depois dê uma mensagem de boas-vindas
# Verifique se ele tem menos ou mais de 18 anos
nome = ... |
from random import randint
print(100)
print('1 2 3 4 5 6 7 8')
print('1 2 3 4 4 5 6 9')
print('1 3 2 3 4 3 5 2')
for i in range(1100, 10701, 100):
t = i
for j in range(8):
print(t % 6, end=' ')
t //= 6
print() |
# Dictionary Structure
contacts = {'Scott Rixner': '1-101-555-1234',
'Joe Warren': '1-102-555-5678',
'Jane Doe': '1-103-555-9012'}
# Value Lookup
# In order to find a phone number in the contact list,
# you simply index into the dictionary with the name you want to look up:
def lookup(contacts... |
"""
Project for Week 4 of "Python Data Analysis".
Processing CSV files with baseball stastics.
Be sure to read the project description page for further information
about the expected behavior of the program.
"""
import csv
##
## Provided code from Week 3 Project
##
def read_csv_as_list_dict(filename, separator, quo... |
'''
Baby Snakes! Learn Python through worked examples
Python 3.4.4
Create a program that prints the product of the first ten positive integers.
'''
#Start here. Set a variable X equal to the product of the numbers 1 through 10.
X = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
'''Print X. Note, this only prints the sum of ... |
grados = int (input ("Ingrese los grados de la temperatura: "))
print (" ")
print ("Ingrese el numero de la izquierda segun la operacion que desea realizar")
print ("1. Fahrenheit a Celsius"," ")
print ("2. Celsius a Fahrenheit"," ")
print ("3. Kelvin a Celsius", " ")
print (" ")
opcion = int(input("Respuesta: "))
prin... |
a = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2]
group = list()
whole = list()
start = a[0]
for ride in a:
if ride == start:
group.append(ride)
else:
whole.append(group)
start = ride
group = list()
group.append(ride)
whole.append(group)
print(whole) |
from frequently_used import manipulate
class Car(object):
def __init__(self, key):
self._id = key
self._steps = -1
self._position = [0, 0]
self._taken_rides = list()
@property
def id(self):
return self._id
@id.setter
def id(self, value):
self._id =... |
def _get_hex(string):
result = []
for item in string:
result.append(hex(ord(item))[2:])
string2 = ''
for i in result:
string2 += str(i)
return string2
class encrypt():
def __init__(self,PreStr):
self.string = PreStr
self.bit = 32
self.hexV = _get_hex(self.string)
self.HV = {'0':0,'1':1,'2':2,'3':3,'4'... |
"""
Colorize logging messages
To activate, configure logging to use an instance of ColorStreamHandler. For
convenience, the output of handlers() can be passed to basicConfig:
>>> from logging import basicConfig
>>> basicConfig(handlers=handlers())
Color choices are available as instances of Color class, and can b... |
'''
Walker program to draw a path that moves in random directions
'''
import random
import pyglet
from pyglet.shapes import Rectangle
window = pyglet.window.Window(1080, 768)
main_batch = pyglet.graphics.Batch()
x = window.width // 2
y = window.height // 2
def update(dt):
global x, y
r = random.randrang... |
"""
Read an input file and convert it to required format
"""
import os.path
import constants
class Token:
def __init__(self, word, pos):
self.word = word
self.pos = pos
def __str__(self):
return "({} {})".format(self.word, self.pos)
def __repr__(self):
return self.__str_... |
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def printAllVals(self):
runner = self.head
while (True):
# print runner value
print runner.value
if runner.next == None:
break;
... |
import random
import datetime
# min only with if/else counter
#######################
#use two loops to sort
#inner loop looks for min value in list
#if a min value is found, it stores the index
#after completion of inner loop, it swaps the min index found with the outer loop control variable (counter value)
#at each... |
import re
# import the urlopen function from the urllib2 module
from urllib2 import urlopen
# import the BeautifulSoup function from the bs4 module
from bs4 import BeautifulSoup
# import pprint to print things out in a pretty way
# import pprint
# choose the url to crawl
url = 'http://www.codingdojo.com'
# get the res... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
print('hello')
guess = 0
secret = randint(1, 10)
while guess != secret:
_x = input('Guess the number: ')
guess = int(_x)
if guess == secret:
print('You win!')
else:
if guess > secret:
print('Too high')
... |
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
#1. 데이터
x1 = np.array([[1,2,3,4,5,6,7,8,9,10], [1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.5, 1.4, 1.3],
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]) #(3, 10)
x2 = np.transp... |
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
#1. 데이터
x1 = np.array([range(100), range(301, 401), range(1, 101), range(100), range(401, 501)]) # (5, 100)
x2 = np.transpose(x1) # (100, 5)
y1 = np.array([range(711, 811), range(101, 201)]) # (2, 100)
y2 = np.... |
n =int(input())
def totalstep(vn,fn):
if(vn>fn):
return 0
if(vn==fn):
return 1
a = totalstep(vn+1,fn)
b = totalstep(vn+2,fn)
c = totalstep(vn+3,fn)
ans = a+b+c
return ans
print(totalstep(0,n))
|
from math import pi
import palettable
import numpy as np
from bokeh.io import output_file, save
from bokeh.models import LinearColorMapper, BasicTicker, PrintfTickFormatter, ColorBar, ColumnDataSource, FixedTicker
from bokeh.plotting import figure
def interactive_heatmap(df,
save_path,
ycol... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 08:54:07 2019
@author: MASTER
"""
# 1.what are the data attributes i want to glue together
# define internal representation - two int = numerator - denominator
# 2.whats the interface
# the method that im going to use to interact with instanc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 1 10:56:38 2019
@author: MASTER
"""
'''
if a procedure has only one yield statement, but that statement
will never be executed, then the procedure is not a generator.
Explanation:'''
def generator1():
if True:
yield 1
def gener... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Assume s is a string of lower case characters.
Write a program that counts up the number of vowels contained in the
string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.
For example if s = 'azcbobobegghakl', your program should print:
Number of vowels: 5
""... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 14 20:42:37 2019
@author: MASTER
"""
#CREATE A STRING OF THE LOWER CASE ALPHABET
import string
alphabet_in_lower_case = string.ascii_lowercase
print(alphabet_in_lower_case)
####
''.join(chr(i) for i in (range(ord('a'), 26 + ord('a'))))
''.jo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 31 21:59:55 2019
@author: MASTER
"""
# recursive
def genPrimes(n):
p = 2
while p <= n:
next = p
yield p
prime_found = False
while not prime_found:
p+=1
if all(p%i !=0 for i in genPrim... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 11:26:36 2019
@author: MASTER
"""
#HOW CAN WE DISPLAY THE VALUES RETURNED?
#What if we want to store the values returned
#by the function call?
#there is a new syntax that will allow you to store
#each element in the tuple into its correspondi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 19:40:48 2019
@author: MASTER
"""
class Dunder_demo:
def __init__(self, _x=0):
self.x = 2
self._x = 3
self.__x = 4
self.__x__ = 5
d = Dunder_demo(5)
print(d) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob'
occurs in s. For example, if s = 'azcbobobegghakl', then your program
should print:
Number of times bob occurs is: 2
"""
s = 'azcbobobegghaklbob'
count... |
# FLOATS & FRACTIONS
# HOW WE COULD CONVERT A DECIMAL INT INTO A BINARY REPRESENTATIONS
num = 3
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
print(result)
while num > 0:
result = str(num % 2) + result
num = num//2
print(num)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# squaring by repetitive addition
x = 3
ans = 0
itersleft = x
while (itersleft != 0):
ans += x
itersleft -=1
print(str(x) + '*' + str(x) + '=' + str(ans)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 16:36:32 2019
@author: MASTER
"""
#when no key is provided, sort uses exclusively the < operator
class A:
def __init__(self,a):
self.a = a
def __lt__(self,other):
return self.a < other.a
def __repr__(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 21 10:58:37 2019
@author: MASTER
"""
#write function that reads binary file and return data
#measure time required
# this is something you might do if you are running a clour service
#that build users buy time used
# we will be logging the resul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 31 22:24:22 2019
@author: MASTER
"""
def genPrimes():
p = 1
primes = []
while True:
p += 2
if all(p%2 for i in primes):
primes += [p]
yield p
p = genPrimes()
print(p.__next__())
prin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 20:10:11 2019
@author: MASTER
"""
#CONVERT LIST TO STRING & BACK
# SOME PROCESSING ON LIST - STRING
s = "I < 3cs"
list(s)
print(list(s))
s.split('<')
print(s.split('<'))
L = ['a', 'b', 'c']
''.join(L)
print(''.join(L))
'_'.join(L)
print('_'.join... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = 'azcbobobegghakl'
#one line Elizabeth
print('Longest substring in alphabetical order is:',
max([s[i:j] for i in range(len(s)-1) for j in range(i+1, len(s)+1) if s[i:j] == ''.join(sorted(s[i:j]))], key=len)) |
'''
Write code to convert any number to its binary form
and print out the summary
'''
num = 19
str_num = str(num)
is_decimal = '.' in str_num
is_negative = num < 0
if is_negative:
num = abs(num)
if is_decimal:
decimal_num = num - int(num)
decimal_summary = '.'
while True:
decimal_num... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 16:35:47 2019
@author: MASTER
"""
# ODDTUPLES
# Write a procedure called oddTuples, which takes a tuple as input,
#and returns a new tuple as output, where every other element of the
#input tuple is copied, starting with the first one. So if t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 12:55:05 2019
@author: MASTER
"""
class Shape:
def __init__(self, x, y):
self.x = x
self.y =y
description = "This shape has not been described yet"
author = " Nobody has claimed to make this shape yet"
def area(s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 11:30:17 2018
@author: MASTER
"""
#ways to do decimal-binary conversions using Python's built-in functions like so:
x = "10001"
c = int(x, 2)
print(c)
x = 11
c = (bin(x).replace("0b", ""))
print(c)
x = 0.5
c = (bin(int(x)).replace("... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 4 17:29:10 2019
@author: MASTER
"""
from math import*
# A regular polygon has n number of sides. Each side has length s.
#
# The perimeter of a polygon is: length of the boundary of the polygon
# Write a function called polysum that takes 2 argume... |
#coding=utf8
def print_2d_array(array_2d , x_margin=3) :
'''
For adjacent matrix DEBUG
if every row or col has one 1 , so the graph is connected !
And for Undirected Connected Graph , it is a symmetric matrix (对称矩阵) , that is A_{ij} = A{ji}
'''
if len(array_2d) == 0 : return
formated_st... |
print("CALCULAR A AREA DE UM RETANGULO:")
B = input("Digite a base:")
H = input(" Digite a altura:")
A = int(B) * int(H)
print("A área do retângulo é: %d" %A) |
# CTI-110
# P3HW2 - Distance Traveled
# Allan Rodriguez-Aguirre
# 03/25/21
first_num = float(input('Enter car\'s speed: '))
sec_num = float(input('Enter time traveled: '))
product = first_num * sec_num
def main():
print('Speed entered:', first_num)
print('Time entered:', sec_num)
print()
... |
#print('hello world')
user=input("say something! ")
#upper('hello')
print(user.swapcase())
print(user.upper())
user =user.upper()
#user=input("say soething! ")
user=input("how are you?" )
mood=input("how you feel?" )
print(mood.upper())
|
dna_source = input()
rna = ''
for base in dna_source:
if base == 'T':
rna += 'U'
else:
rna += base
print(rna)
|
#!/usr/bin/env python3
from functools import lru_cache
from seedcount import start
doubles = ["ae",
"ro",
"is",
"tn",
"lc",
"up",
"dm",
"bg",
"hf",
"wv",
"ky",
"xj",
"zq",
"_"]
#in how many words is (first index) exactly (2nd index)-times
reverse_count = {double:{i:0 for i in range(0,5)} for double in doubles}
wit... |
class Animals:
def __init__(self):
self.type = "animals"
print 'animals 1'
def __init__(self,name='AnimalsName',type='AnimalsType'):
self.name = name
self.type = type
print 'animals 2'
def __init__(self,name):
self.type = "animals"
self.name = name
... |
from collections import defaultdict
class TrieNode(object):
def __init__(self):
self.nodes = defaultdict(TrieNode)
self.isword = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(word):
curr = self.root
for char in word:
curr = curr.nodes[char]
curr.isword = True
def s... |
import random
import math
class Montecarlo:
cantidadPuntos = 1000000000
def ejecutar(self):
cantidadAdentro = 0
for x in xrange(0, self.cantidadPuntos):
x = random.random()
y = random.random()
distancia = math.sqrt( math.pow(x,2) + math.pow(y, 2) )
#print distancia
if distancia <= 1 :
... |
from bs4 import BeautifulSoup
import nltk
import requests
import re
# Runs through the code of a website and pulls out the specified meta tags and other tags and their content. C
url = raw_input("Enter a website url to scrape:")
r = requests.get("http://"+url)
website = r.text
soup = BeautifulSoup(website,"lxml") ... |
#########################################################################################################
# Write a program which contains filter(), map() and reduce() in it. Python application which
# contains one list of numbers. List contains the numbers which are accepted from user. Filter
# should filter out all s... |
#########################################################################################################
# Write a recursive program which display below pattern.
# Input : 5
# Output : * * * * *
# Author : Annaso Chavan
###################################################################################################... |
#####################################################################
# Write a program which accept one number from user and return its factorial.
# Input : 5 Output : 120
# Author : Annaso Chavan
#####################################################################
# calculate factorial of number
def FactorialNum(n... |
#####################################################################
# Write a program which accept one number and display below pattern.
# Input : 5
# Output : * * * * *
# * * * *
# * * *
# * *
# *
# Author : Annaso Chavan
#####################################################################
# f... |
#########################################################################################################
# 1.Write a program which contains one class named as Demo. Demo class contains two instance variables as no1 ,no2.
# That class contains one class variable as Value. There are two instance methods of class as Fun ... |
def swap_case(s):
ss=''
for a in s:
if a.islower():
a=a.upper()
ss=ss+a
elif a.isupper():
a=a.lower()
ss=ss+a
else:
ss=ss+a
return ss
if __name__ == '__main__':
|
mark = int(input("Mark:"))
if mark >= 9:
print("Excellent")
elif mark >= 7:
print("Very good!")
elif mark >= 6:
print("Good!")
elif mark >=5:
print("Enough!")
else:
print("Fail!!")
|
# funciton showing triangle numbers
#xn = n(n+1)/2
#desired triangle sequence marker number will be n
import math
n = int(raw_input("Find amount of dots for which sequence marker?"))
def total_dots(n):
print n*(n+1)/2
total_dots(n)
|
num=list()
lim=input("Enter the number of elements you want")
print("Enter the numbers")
for i in range(int(lim)):
ele=input("Number:")
num.append(int(ele))
n=int(input("Enter the number to be searched for"))
l=0
h=len(num)
flag=False
while l<=h:
mid=(l+h)//2
if num[mid]==n:
print("Number fo... |
for _ in range(int(input())):
student_needstudent= [int(x) for x in input().split()]
student = student_needstudent[0]
needstudent = student_needstudent[1]
time = [x for x in input().split() if int(x) <= 0]
if len(time) < needstudent:
print("YES")
else:
print("NO")
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Assignment 02 | Task01: Write a program which takes 5 inputs from user for different subject’s
#marks, total it and generate mark sheet using grades
print("-----------------Enter Marks For 5 Subjects out of 100------------------------")
sub1=int(input("English:"))
su... |
#Ques 3.Write a Python program to convert a tuple to a string.
t= ('p', 'y', 't', 'h', 'o', 'n')
str=''.join(t)
print(str) |
#We can send our turtles out and have them 'stamp' the canvas with their shapes. Use .stamp() on the end of their name to do this.
#Yes you can change the color of the window!
import turtle
window = turtle.Screen()
window.bgcolor("yellow")
tina = turtle.Turtle()
molly = turtle.Turtle()
george = turtle.Turtle()
wilson... |
####### The built-in iter method can be used to build iterator objects,
# while the next method can be used to gradually iterate over their content:
my_iter = iter([1, 2, 3])
print (next(my_iter))
print (next(my_iter))
print (next(my_iter))
my_iter = iter([4,5])
print (next(my_iter))
my_iter = iter([1, 2, ... |
#remove list l2 from list l1
#use remove() function -- delete elemnt of l2 from l1
def removelist() :
l1 = [1, 4, 9, 10, 23]
l2 = [4, 9]
l1.remove(l2[0])
l1.remove(l2[1])
return l1
l1 = removelist()
print (l1)
####### using for loop ######
def removeList() :
l1 = [1, 4, 9, 10, 23]
l... |
# change case of given string
def changeCase(s) :
result1 = s.upper()
result2 = result1.lower()
result3 = s.lower()
return(result1,result2,result3)
print(changeCase("Pooja Mahajan"))
|
## Implement a calculateAvg function that receives the ages dictionary as a parameter,
# and returns the average age of the students.
def calculateAvg(ages):
length=len(ages) # len(dictionary) to calculate the length of dictionary,
average = sum(ages.values())/length # sum/length
#print (length)
ret... |
## Given a lengthDictionary function that takes Students dictionary as a parameter,
# find how many students are in the dictionary.
def lengthDictionary(Students):
return len(Students)
Students = {
"Peter": 10,
"Isabel": 11,
"Anna": 9,
"Thomas": 10,
"Bob": 10,
"Joseph": 11,
"Maria... |
# Multiple Turtle
# You can make more than one turtle. Just give them different names! You can then make them do different things
# or give them different colors.
import turtle
pooja=turtle.Turtle()
gaurav=turtle.Turtle()
pooja.color("Red")
gaurav.color("Blue")
pooja.forward(100)
gaurav.left(40)
gaurav.forward(10... |
### print even - odd number in descending number
def printEvenOdd(n):
while(n > 0):
if (n % 2 == 0):
print ("Even number:",n)
else:
print ("Odd number:",n)
n = n - 1
printEvenOdd(10) |
## check for number is even
def is_even(number):
if(number%2==0):
#print("number is even")
return True
else:
#print("Number is odd(Not even")
return False
print(is_even(3))
#function to check that our code is correct or not
def test_is_even():
assert is_even(2)==True
... |
# find index in given string e.g. "aaabbbccc"
def findIndex(s):
index1 = s.find("b")
index2 = s.find("ccc")
print(index1,index2)
#return(index1,index2)
findIndex("aaabbbccc")
#print(findIndex("aaabbbccc"))
|
# list.append(x) - Добавляет элемент в конец списка
# list.extend(L) - Расширяет список list, добавляя в конец все элементы списка L
# list.insert(i, x) - Вставляет на i-ый элемент значение x
# list.remove(x) - Удаляет первый элемент в списке, имеющий значение x. ValueError, если такого элемента не существует
# list.po... |
# 1. Дан список. Получите новый список, в котором каждое значение будет удвоено:
# [1, 2, 3] --> [2, 4, 6]
l = [1, 2, 3]
l1 = [i * 2 for i in l1]
print(l3)
# 2. Дан список. Возведите в квадрат каждый из его элементов и получите сумму всех полученных квадратов:
# [1, 2, 3] --> 14 --> 1^2 + 2^2 + 3^2 = 14
l2 = [1, 2, ... |
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def test(self):
pass
def test1(self):
# this needs to be here not in Subclass1 if it's to be implemented in Subclass2
pass
class Subclass1(Base):
def test(self):
self.test1()
print('test')
... |
# # class
# class Car():
# def __init__(self, make, model, color):
# self.make = make
# self.model = model
# self.color = color
# self.gas = 100
# def __str__(self):
# return "{}, {}, {}".format(self.make, self.model, self.color)
# def drive(self):
# self.g... |
import numpy as np
import sys
# first we will generate num_trial samples
num_trial = int(input("Enter num_trial:"))
X = np.random.rand(num_trial)
#defining strings a,b,c,d.
[a,b,c,d]=["a","b","c","d"]
pa = 0.010239712433255
#pa= float(input("Enter probability of a:")) we can also use this to input our pa from termin... |
# coding: utf-8
# In[2]:
def set_a():
a = 10
print 'The value of a:', a
# In[3]:
set_a()
# In[7]:
a = 20
print 'Initially, the value of a:', a
set_a()
print 'finally, the value of a:', a
# In[8]:
def scoped (first, second):
third = second + second - first
return third
first = 10
second = 11
... |
year = int( input() )
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print('윤년')
else:
print('평년')
else:
print('윤년')
else:
print('평년')
|
n = int(input("입력 횟수: "))
if n > 0:
maximum = int(input("값: "))
for i in range(n-1):
temp = int(input("값: "))
if temp > maximum:
maximum = temp
print("최댓값:", maximum)
|
num1 = int( input() )
num2 = int( input() )
if num1 > 0:
if num2 > 0:
print(num1, num2)
|
qustn = str( input('give a string: ') )
print('your string is:', qustn)
|
name = str( input('name: ') )
age = int( input('age: ') )
weight = float( input('weight: ') )
print('제 이름은', name, '입니다.')
print('나이는', age, '이고, 체중은', weight, '입니다.')
|
import turtle
import random
def screenLeftClick(x, y):
# apply random
r = random.random()
g = random.random()
b = random.random()
turtle.pencolor((r, g, b))
turtle.pendown()
turtle.goto(x, y)
def screenRightClick(x, y):
turtle.penup()
turtle.goto(x, y)
psize = 5
tsize = random.randrange(1, 5)
turtle.titl... |
num1 = int( input() )
if num1 > 5:
print('첫째')
if num1 > 3:
print('둘째')
if num1 > 1:
print('셋째')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.