text stringlengths 37 1.41M |
|---|
__author__ = 'GaryGoh'
def squeeze(filename):
file = open(filename, "r")
line_num = 0
preLine = ""
while True:
line = file.readline()
# To break dead loop
if line == "":
break
line_num = line_num + 1
# Compare with previous line if same as current ... |
__author__ = 'GaryGoh'
def peaks(s):
# Empty list
if not s:
return []
# Not emtpy list
# initialized ascList in order to avoid list index out of range
ascList = [s[0]]
# Similar as insertion sort, but no need to walk though the new list again
# Only compare the current element fr... |
__author__ = 'GaryGoh'
def print_dictionary(d):
# abstract keys of d and sort them
# I suppose left-justified columns of width 10 is that
# each column has 10 width from left to right.
for k in sorted(d.keys()):
print("%-10s : %-10s" % (k, d[k]))
return
d = {'sun': 'grian', 'tree': 'crann'... |
from tkinter import*
from tkinter import ttk #ttk are actually separate files in tkinter, this updates the original with improved widgets.
import random
class Application(Frame): #Frame is a previously defined class/widget designed to be a container for other widgets. Example of Cl... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 2020
@author: Daniel Hryniewski
Collatz Conjecture - Start with a number n > 1. Find the number of steps it takes to reach one using the following process:
If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1.
"""
def choice():
i = 0
... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 2020
@author: Daniel Hryniewski
Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent.
"""
def bintodec(num):
result = bin(num)
return result[2:]
def dectobin... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 6 2020
@author: Daniel Hryniewski
Sorting - Implement two types of sorting algorithms: Merge sort and bubble sort.
"""
from random import randint
def randomlist():
r = randint(5,30)
randlist = []
for i in range(1, r+1):
n = randint(... |
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
#for i in range(nums1):
# if nums1[i] == 0:
# nums[i] = None
iA = m-1
iB = n-1
iM = m+n-1... |
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
p1, p2 = 0, len(nums) - 1
p = 0
while p <= p2:
if nums[p] < 1:
nums[p], nums[p1] = nums[p1], nums[p]
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
a=collections.defaultdict(list)
def t(node,depth):
if node:
... |
def sortByBits(self, arr: List[int]) -> List[int]:
'''import collections
def count(n):
count = 0
while n != 0:
if n & 1 == 1:
count += 1
n >>= 1
return count
d = collections.defaultdict(list)
... |
class Solution:
def rotateString(self, A: str, B: str) -> bool:
n = len(A)
if n == len(B):
b = A+A
return B in b
return False
|
# 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 levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
#10) Mostrar los números pares entre 1 al 100.
# Solucion 1:
for x in range(1,101):
if(x%2==0):
print(x)
# Solucion 2:
for i in range(2,101,2):
print(i)
|
#12) Crea una lista vacía (pongamos 10 posiciones), pide sus valores y devuelve la suma y la media de los números.
lista=[]
suma=0
media=0
for i in range(1,11):
n=int(input("Digite un numero: "))
lista.append(n)
suma+=n
media=suma/len(lista)
print(lista)
print("la suma de los valores es:",suma)
print("l... |
#5) Crea una variable numérica y si esta entre 0 y 10, mostrar un mensaje indicándolo.
# Solucion 1
x=int(input("digite un numero: "))
if(0<=x<=10):
print(x,"está entre 0 y 10")
else:
print(x,"no está entre 0 y 10")
# Solucion 2:
if(x>=1 and x<=10):
print("Esta entre 0 y 10")
else:
print("No esta en ese... |
#4) De dos números, saber cual es el mayor.
x=int(input("digite un numero: "))
y=int(input("digite otro numero: "))
if(x>y):
print(x,"es el mayor")
elif (x<y):
print(y,"es el mayor")
else:
print("los numeros son iguales") |
#9) Crea una tupla con números e indica el numero con mayor valor y el que menor tenga.
tupla=(1,2,5,1,1,6,0,2,2,0,2,1)
print("El numero mayor es:",max(tupla))
print("El numero menor es:",min(tupla)) |
from copy import deepcopy
class Nod:
def __init__(self, e):
self.e = e
self.urm = None
class Lista:
def __init__(self):
self.prim = None
def creareLista():
lista = Lista()
lista.prim = creareLista_rec()
return lista
def creareLista_rec():
x = int(input("x=")... |
# 1. A client sends to the server an array of numbers. Server returns the sum of the numbers.
import socket
import struct
import sys
def tcp_client_init(ip_address, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip_address, port))
return sock
def tcp_send_int(sock, numbe... |
#เกรด 0,1,2,3,4
#ข้อมูลนำเข้า คือ คะแนนสอบ
#ประมวลผลว่าอยู่ในเกรดไหน
#พิมพ์ว่าได้เกรดไหน
score = int(input("Input your score : "))
if score >= 0 and score <= 100:
if score >= 80:
print("เกรด 4")
elif score >= 70 :
print("เกรด 3")
elif score >= 60 :
print("เกรด 2")
elif score ... |
#แปลง พศ เป็น คศ
number = int(input("ป้อน พ.ศ. "))
number2 = number-543
print("ค.ศ. = ", number2)
# print("ค.ศ. = ", number-543)
|
# if boolean expression :
# statement
#age = 15 - 20 วัยรุ่น
# 21 - 29 ผู้ใหญ่
# 30 - 39 วัยทำงาน
#and or not
age = int(input("age : "))
name = input("name : ")
if age >= 15 and age <= 20:
print("วัยรุ่น")
if age >= 21 and age <= 29 :
print("ผู้ใหญ่")
if age >= 30 and age <= 39:
print("วัยทำงาน")... |
#การเพิ่มข้อมูลเข้าไปใน list
number = [1,2,3,4,5,6] #สมาชิิกคือ 1-6
fruit = ["มะม่วง","มะนาว","มะยม"]
print("ก่อนเพิ่ม == > ", fruit)
#append() นำสมาชิกใหม่ ไปต่อท้ายเพื่อน
fruit.append("มะปราง")
fruit.append("แตงโม")
print("หลังเพิ่ม == > ", fruit)
#insert (index , สมาชิกใหม่) การแทรก
fruit.insert(1,"ทุเรียน")... |
age = int(input("ใส่อายุของคุณ : "))
if age <= 15:
if age == 15:
print("ม 3")
elif age == 14 :
print(" ม 2")
elif age == 13 :
print("ม 1")
else :
print("ประถมศึกษา")
else :
print("ม ปลาย")
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 6 17:14:38 2019
@author: Diogo
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
#2.1. Load the numpy files for data1 which have already been split into training
#data (variables xtrain and ytrain) and test data (variables xtest and ytest... |
# LAB11.py
class Node:
def __init__(self, value):
self.value = value
self.next = None
def getValue(self):
return self.value
def getNext(self):
return self.next
def setValue(self, new_value):
self.value = new_value
def setNext(self, new_next):
sel... |
import time
from selenium import webdriver
vegetables = ['Onion - 1 Kg', 'Musk Melon - 1 Kg', 'Water Melon - 1 Kg', 'Almonds - 1/4 Kg']
veggies = []
driver = webdriver.Chrome(executable_path="C:\\browser\chromedriver.exe")
driver.maximize_window()
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driv... |
from math import sqrt
num = int(input('enter how many terms you want\n'.title()))
no_of_terms_found = 1
record = 1
current_no = 2
anti_primes = [1]
divisors_of_anti_primes = [[1]]
def get_divisors(n):
divisors = []
for i in range(1,int(sqrt(n)) + 1):
if n%i == 0:
if i*... |
#!/usr/bin/env python
# Simple translation model and language model data structures
import sys
from collections import namedtuple
# A translation model is a dictionary where keys are tuples of French words
# and values are lists of (english, logprob) named tuples. For instance,
# the French phrase "que se est" has two... |
import re
VALID_EMAIL_RE = re.compile(r"^[a-z0-9._+-]+[@][a-z0-9-]+(\.[a-z0-9-]+)+$")
def validate_clean_email_string(string):
return VALID_EMAIL_RE.match(string) is not None
def clean_email_string(string):
return string.lower().strip()
# For DB models
def validate_email_field_in_db(self, key, value):
... |
def contar(dato,objetivo):
n = 0
for item in dato:
if item == objetivo:
#Encuentra coincidencia
n+=1
return n
lista =["a","a","b","c","a","d"]
cuenta = contar(lista,"a")
print(cuenta)
|
__author__ = 'Ashton'
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# Данная "обёртка" принимает любые аргументы
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print("Передали ли мне что-нибудь?:")
print(args)
print(kwargs)
# Теперь мы распаку... |
import pylev
def distance(var1, var2):
print("Doing levenstien distance for ", var1 , var2)
print("Distance should be ", pylev.levenshtein(var1, var2))
var3 = 0
var4 = 0
var5 = 0
if var1[0] == var2[0]:
var3 = var3 + 0
else:
var3 = var3 + 1
if var1[1] == var2[1]:
... |
from openpyxl import load_workbook
def worksheet_dict_reader(worksheet):
"""
A generator for the rows in a given worksheet. It maps columns on
the first row of the spreadsheet to each of the following lines
returning a dict like {
"header_column_name_1": "value_column_1",
"header_colum... |
"""Parser with declaration, expression and statements.
Typical usage example:
new_parser = Parser(cio_instance, scn_instance)
new_parser.compilation()
"""
from typing import Set
import chario
import scanner
import token
ADD_OP_SET: Set[str] = {"plus", "minus"}
MUL_OP_SET: Set[str] = {"mul", "div", "mod"}
R... |
"""
Created on 4/25/2020
@author: erosales
Description of file:
"""
from clear_log import clear
from player import Player
total_players = dict()
first_spins = []
def create_player(player_number):
player_name = input("\nPlayer %s, what is your name: " % player_number)
clear()
_spin(player_... |
i=1
while i<=100:
if i%3==0 or i%5==0:
i+=1
continue;
else:
print(i)
i+=1
|
num=int(input("Enter the number to find factorial:"))
f=1
for i in range(num,0,-1):
f=f*i
print("The factorial of given number:"+str(f))
|
# Python program to demonstrate that copy
# created using set copy is shallow
first = {'g', 'e', 'e', 'k', 's'}
second = first.copy()
# before adding
print ('before adding: ')
print ('first: ',first)
print ('second: ', second )
# Adding element to second, first does not
# change.
second.add('f')
... |
a=2
print(id(a))
print(id(2))
a=a+1
print(id(3))
print(id(a))
b=2
print(id(2))
print(id(b))
def printhello():
print("hello")
a=printhello()
print(a)
|
from array import *
a=array('i',[1,23,45,67])
pos=int(input("Enter the element position which you want to display:"))
for i in range(pos-1,3):
a[i]=a[i+1]
for i in range(3):
print(a[i])
|
name='''vanshika sikarwar is not a good girl
but she tries to be a good girl'''
age="""Her age is very small than
understanding"""
print(name)
print(age)
print("Hello,\
with \
world")
print(\
"Hello,\
world")
print(1+2\
+3+4)
print(r"vanshika sikarwar""\\")
|
n =input()
if isinstance(n, int):
print("This input is of type integer")
elif isinstance(n, float):
print("This input is of type float")
elif isinstance(n, str):
print("This input is of type string")
else:
print("This is something else")
|
t=int(input())
while t!=0:
string=input()
print(string.replace('a',"xxx"))
|
#create a function to find if a number is prime or not.
def is_prime(num):
if num == 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
#create a function to find median of two sorted lists in O(logn) time.
def find_median(list1, list2):
if ... |
# Python program to remove duplicate elements in list
lst = [1,2,3,4,4,5,6,6,6,7,8,9,9,9,9,10]
new_lst = []
for i in lst:
if i not in new_lst:
new_lst.append(i)
print(" Original list --> ",lst)
print(" List after removing duplicate elements -->",new_lst) |
size = int(input("Enter the size of queue : "))
Queue = []
def insert():
if len(Queue) < size:
element1 = input("Enter the element to insert:")
Queue.append(element1)
print("Queue : ", Queue)
else:
print("Queue is full!!")
def delete():
if len(Queue) <= 0:
print(... |
class Vehicle:
def car(self, company, color):
self.company = company
self.color = color
print("Car details : ", self.company, self.color)
def bike(self):
print()
ve = Vehicle()
ve.car('BMW', ", Black")
#ve.bike()
|
salary = float(input("Enter your salary:"))
service = float(input("Enter the total years of service:"))
bonus = float((5/100)*salary)
if(service>=5):
print("your net bonus amount is ",salary+bonus)
else:
print("Bonus not applicable!!") |
num1 = int(input("Enter num 1: "))
num2 = int(input("Enter num 2: "))
print(num1, "*", num2, "=", num1*num2) |
# person child parent student
# child and parent inherit person
# student class inherit child
class Person:
def per(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
print(self.name, self.age, self.gender)
class Parent(Person):
def par(self, job,... |
# remove special characters
string="H,el;l,o W::or?ld"
s_char=",<.>/?;:"
n_string=""
# for i in string:
# if i in s_char:
# continue
# else:
# n_string+=i
for i in string:
if i not in s_char:
n_string+=i
print(n_string) |
# Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b
import re
n = input("Enter string : ")
x = '(^a[\w\W]*b)$'
match = re.fullmatch(x,n)
if match :
print("Valid")
else:
print("Invalid")
|
# starting with a and ending with b
import re
n = input("Enter string : ")
x = '(^a[\w\W]*b)$'
match = re.fullmatch(x,n)
if match is not None:
print("Valid")
else:
print("Invalid")
|
# LAMBDA
# Addition using lambda
add = lambda num1,num2:num1+num2
print("Addition: ",add(1,2))
sub = lambda num1,num2:num1-num2
print("Subtraction: ",sub(10,2.3))
mul = lambda num1,num2:num1*num1
print("Multiplication:", mul(5,4))
div = lambda num1,num2:num1/num2
print("Division: ",div(5,2))
|
lst = [1,"Joel",2,'j',3,4,5,6,7,8,9,10]
search = (input("Enter an element to search : "))
if search in lst:
print("Element found !!")
else:
print("Element not found!!")
|
EMPLOYEE = {'ID': "1001", "Name": 'Joel', "Designation": "Dev", "Salary": 20000}
# Print emp name
print("EMP Name : ", EMPLOYEE['Name'])
# company : name
if 'COMP' not in EMPLOYEE:
EMPLOYEE['COMP'] = 'Google'
print(EMPLOYEE)
# Salary + 5000
EMPLOYEE['Salary'] += 5000
# Print
for i in EMPLOYEE:
prin... |
# whileloop
# syntax:
# initialization
# while(condition)
# statement
# inc or decr
i=1
while(i<=10):
print("Hi")
i+=1 |
# single inheritance
class Person: # parent class / base class / super class
def details(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def print(self):
print(self.name, self.age, self.gender)
class Student(Person): # child class / sub clas... |
# List slicing
# lst[upper limit:lowerlimit]
# from upper limit to lower limit-1
lst = [0,1,2,3,4,5,6]
print(len(lst))
# print(lst[:])
# print(lst[1:])
# print(lst[:9])
print(lst[3:-4]) |
import pygame
import math
import random
import sys
#colours to be used in game
Green = (50,205 ,50)
Ivory = (255,255,240)
Blue = (0,0,255)
Red = (255,0,0)
Purple = (255,0,255)
Grey = (190,190,190)
Black = (0,0,0)
White = (255, 255, 255)
Yellow = (255, 255, 0)
Orange = (255, 165, 0)
#screen width and height
WIDTH =... |
# names = ["sahil","shripad","Dudwadkar","mr.dude"]
# for item in names:
# print(item)
# [syntax] --- For loop
# for i in range(10):
# print(f"Hello World {i}")
#sum from 1 to 10
# total = 0
# for i in range(1,11):
# total = total + i
# print(total)
# user input
num = int(input("Enter a number :"))
... |
# Print string last character with function
# def last_char(name):
# return name[-2]
# print(last_char("sahil"))
# ------------------------------------------------------------------------
# Even or odd
# def odd_even(num):
# if num%2==0:
# return "even"
# return "odd"
# num = int(input("Enter a ... |
# def fibo(num):
# a=0
# b=1
# if num == 1:
# print(a)
# elif num == 2:
# print(b)
# else:
# # print(a,b , end = " ")
# for i in range(num-2):
# c=a+b
# a=b
# b=c
# print(b,end = " ")
# fibo(10)
# -----------------------... |
# set1 = {11,12,13,14}
# print(set1)
# Print set with for loop
# for i in set1:
# print(i)
# print null set
# set1 = set({})
# print(set1)
# add method for adding elements in set
# set1 = {11,12,13,14}
# print(set1)
# set1.add(66)
# print(set1)
# update() method -- for adding one more value in set
# set1 = {... |
number_one = float(input("Enter first number"))
number_two = float(input("Enter second number"))
total = number_one + number_two
print(total)
# num1 = str(4)
# num2 = float("20")
# num3 = int("50")
# print(num2 + num3) |
# 73_factorial_using_while.py
n = 5
factorial = 1
i = n
while(i > 0):
factorial = factorial * i
i = i - 1
print(f"{n}! = {factorial}")
|
# 24_conditional_operators.py
'''
== Equal to
!= Not equal to
< less than
<=less than or equal to
> greater than
>= greater than or equal to
'''
print('10 == 10', 10 == 10)
print('10 == 11', 10 == 11)
print('15 != 15', 15 != 15)
print('15 != 25', 15 != 25)
print('20 < 30', 20 < 30)
print('20 < 10', 20 < 10)
|
# 109_max_number_in_a_list.py
import math
my_list = [
34, 5, 77, 87, 556, 99, 98, 347, 33, 232
]
max = -math.inf
for num in my_list:
if(num > max):
max = num
print('Max = ', max)
|
# 52_range_with_steps.py
n = 10
print("Starting at 0\nStep: 2")
for i in range(0, n, 2):
print(i)
print("Starting at 1\nStep: 2")
for i in range(1, n, 2):
print(i)
print("Starting at 5\nStep: 2")
for i in range(5, n, 2):
print(i)
"""[output]
Starting at 0
Step: 2
0
2
4
6
8
Starting at 1
Step: 2
1
3
5
7
9... |
# 28_max_of_three_numbers.py
print("---- Max of three numbers ----")
a = int(input("Enter first number : "))
b = int(input("Enter second number: "))
c = int(input("Enter third number : "))
if(a > b):
# a is max
if(a > c):
print("Max: ", a)
else:
print("Max: ", c)
else:
# b is max
if... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import copy
import itertools
def get_maximums(numbers):
max_liste = []
for liste in numbers:
max_liste.append(max(liste))
return max_liste
def join_integers(numbers):
return int(''.join([str(elem) for elem in numbers]))
def generate_prime_numbers(lim... |
import pickle
from course import Course
from student import Student
from edge import Edge
# the purpose of this script is to create the edges for the graph
# using data from the .pickle file of students
data = open('./data/students.pickle', 'rb')
students = pickle.load(data)
data.close()
data = open('./data/studen... |
num1=input("Enter first Numb: ")
num2=input("Enter Second Numb: ")
num3=input("Enter Third Numb: ")
#num=(int(num1)+int(num2)+int(num3))/3
print(f"Average of given numbers: {(int(num1)+int(num2)+int(num3))/3}")
name="Sandeep"
print(name[0:])
|
# Some functions of Strings
hello = "my name is Hardik"
standard = "I am in eleventh standard."
print(hello + standard)
# 1. Len
print(len(hello))
# 2. endswith
print(hello.endswith('Hardik'))
# 3. capitalize
print(hello.capitalize())
# 4. count
print(hello.count('a'))
# 5. replace
print(... |
"""
Iterators and generators
"""
MAX_SEQ = 42
def fibonacci_generator():
index = 2
first = 0
second = 1
if MAX_SEQ == 1:
yield first
elif MAX_SEQ == 2:
yield second
else:
while index < MAX_SEQ:
third = first + second
first = second
s... |
# original autor: maksim32
# Rewrite to Python 3: Code0N
# Original date: 2017-09-10
# Rewrite date: 02.04.2021
import sys
g_alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюяABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ,."
def Trisemus(key, strval, action):
keyword, (height... |
'__author__'=='deepak Singh Mehta(learning graphs)) '
#problem :- https://www.hackerrank.com/challenges/journey-to-the-moon
#theory:- Set-Disjoint
if __name__=='__main__':
n, m = map(int, input().split())
lis_of_sets = []
for i in range(m):
a,b = map(int, input().split())
indices = []
... |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from collections import Counter
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import random
''''
Handle Data: Open the dataset from CSV and split into test/train datasets.
Similarity: Calculate the d... |
a=input'Enter the number to check'
while (a=<1000):
def reverse(s):
return s[::-1]
def isPalindrome(s):
rev = reverse(s)
if (s == rev):
return yes
return no
|
s1 = input("Please enter a word:")
s2 = input("Please enter another word:")
for i in range(0, len(s1), 1):
if i in range (0, len(s2), 1):
print("its anagram")
|
# 1051
a = float(input())
if a>=0.00 and a<=2000:
print("Isento")
elif a>=2000.01 and a<= 3000:
tax = (a-2000)*0.08
print("R$ %.2f"%tax)
elif a>=3000.01 and a<=4500:
tax=(1000*0.08)+((a-3000)*.18)
print("R$ %.2f"%tax)
elif a>=4500.01:
tax=(1000*0.08)+(1500*.18)+((a-4500)*.28)
... |
# 1040
value=input().split(" ")
n1,n2,n3,n4 = value
avg = ((2*float(n1)) + (3*float(n2)) + (4*float(n3)) + (1*float(n4))) / (2+3+4+1)
print("Media: %.1f"%avg)
if avg>=7:
print("Aluno aprovado.")
elif avg<5:
print("Aluno reprovado.")
else:
print("Aluno em exame.")
exam=float(input())
... |
# 1044
value = input().split(" ")
a,b = value
if int(b)%int(a) == 0:
print("Sao Multiplos")
else:
print("Nao sao Multiplos") |
# 1035
value=input().split(" ")
A,B,C,D = value
if int(B)>int(C) and int(D)>int(A):
if (int(C)+int(D))>(int(A)+int(B)):
if int(C)>0 and int(D)>0:
if int(A)%2==0:
print("Valores aceitos")
else:
print("Valores nao aceitos")
else:
... |
# 1036
value = input().split(" ")
a,b,c = value
if float(a)!=0:
if (float(b)**2 - (4*float(a)*float(c)))>=0:
R1 = (-float(b)+(float(b)**2 - (4*float(a)*float(c)))**0.5)/(2*float(a))
R2 = (-float(b)-(float(b)**2 - (4*float(a)*float(c)))**0.5)/(2*float(a))
print("R1 = %.5f"%R1)
... |
# 1098 (5% wrong on i = 2)
i = float(0)
j = float(1)
while i<=2:
print(i,j)
if i.is_integer() or j.is_integer():
print("I={:.0f} J={:.0f}".format(i,j))
print("I={:.0f} J={:.0f}".format(i,j+1))
print("I={:.0f} J={:.0f}".format(i,j+2))
else:
print("I={} J={}".format(round(i,1),round(j... |
largest = None
smallest = None
while True:
try:
num = raw_input("Enter a number: ")
if num == "done":
break
#print (num)
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
prin... |
#1-1
for i in range(5,0,-1):
print('☆'*i)
#1-2
for i in range(1,6):
print(' '*(6-i)+'*'*(2*i-1))
#2
num=int(input('숫자 입력 : '))
while True:
if num == 7 :
print('{0} 입력! 종료!'.format(num))
break
else :
num=int(input('다시 입력 :'))
#3
money=10000
charge=2000
song=0
while True:
if ... |
# append mode를 사용하여 파일끝에 추가
f = open('test2.txt','a',encoding='utf-8')
data = '\n\nPython programming'
f.write(data)
f.close()
# 읽기모드로 파일을 열어서 내용 출력(파일 수정 + 읽기)
f = open('test2.txt','a',encoding='utf-8')
data = '\nR programming\n'
f.write(data)
f = open('test2.txt','r',encoding='utf-8')
print(f.read())
f.close()
... |
# 클래스 상속 실습
# 슈퍼클래스: 사람 클래스 person <- 서브클래스 : 학생클래스 student
class Person:
def __init__(self,age,sex,name):
self.age=age
self.name=name
self.sex=sex
def greeting(self):
print('안녕하세요')
class Student(Person):
# 학교, 학과, 학번, 공부하다(), 시험보다()
def __init__(self,age,sex,name,sch... |
#문자열의 기본 형식과 이해
crawling='Data crawling is fun.'
parsing = 'Data parsing is also fun'
print(type(crawling))
print(type(parsing))
'''
PI = 3.1414
r=10
result = ('반지름 ' + str(PI) + '인 원의 넓이는'+str(PI*r*r))
print(result)
print('hello ' * 3)
'''
#slicing : 문자의 일부분을 추출
print(crawling[0])
print(crawling[-1])
print(crawling[... |
#1~100까지의 정수중 3의배수
'''
n=1
sum=0
while n <= 100:
if n%3 == 0:
sum+=n
n+=1
print('1부터 100까지의 합은 {0}'.format(sum))
'''
n=0
sum=0
while n <= 100:
sum += n
n+=3
print('1부터 100까지의 합은 {0}'.format(sum)) |
#생성된 file.txt파일은 빈 파일
# f=open('file1.txt','w')
# f.close()
# 경로 수정 : 디렉토리가 존재하지 않은 경로
# f=open('c:/python/file1.txt','w')
# f.close()
#f=open('file1.txt','w')
#FileNotFoundError: [Errno 2] No such file or directory: 'c:/python/file1.txt'
#상대경로 표현
f=open('../file.txt','w')
f.close()
#/python study/pythonstudy/16_file... |
#리스트의 요소를 제거 : remove() pop()
#remove(삭제하려는값) : 가장 첫번째 만나는 값을 삭제
n=[1,2,3,4,5,3,4,-1,-5,10]
n.remove(3)
print(n)
cnt=n.count(3)
print(cnt)
#pop() : 맨 마지막 값을 삭제하지만 pop(index) : index위치의 값을 삭제후 반환
data=n.pop(4)
print(n)
print(data) |
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
ar = self.length * self.width
print(ar)
def perimeter(self):
peri = 2 * (self.length + self.width)
print(peri)
class Square(Rectangle):
def __i... |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
# Subclass QMainWindow to customise your application's main buttons
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("My second try on PyQ... |
from validate_email import validate_email
def validate_list_with_searchString(listitem, searchString):
print("Length of list search: " + str(listitem.count(searchString)))
print("Length of List: " + str(len(listitem)))
if listitem.count(searchString) == len(listitem):
print("list length is equal")
... |
# add dic
a = {1: 'a'}
print("\na dictionary: {0}".format(a))
a[2] = 'b'
print("add a[2] = b: {0}".format(a))
a['name'] = 'pooh'
print("add a['name'] = 'pooh': {0}".format(a))
a[3] = [1, 2, 3]
print("add a[3] = [1, 2, 3]: {0}".format(a))
# delete dictionary
del a[1]
print("\ndelete dictionary a[1]: {0}".format(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.