text
stringlengths
37
1.41M
import collections ''' Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is ...
class Solution: def containsDuplicate(self, nums): nLen = len(nums) if nLen <= 1: return False appears = set() for n in nums: if n in appears: return True else: appears.add(n) return False ...
# -*- coding: utf-8 -*- """ Utility functions. """ from datetime import datetime def generate_json(id, encoded_image, filename): """Generate a dictionary for image with given id, filename and encoded image as base64 bytes object. Return dictionary that is easily converted to json. """ date_upl...
''' Taha Ali ICS4UR Ms. Pais March 29, 2019 The following block of code runs the animation for the game, which is seen after clicking the start button on the main menu. ''' import pygame from pygame.locals import * import sys import os from os import path import pygame,random,sys,time,os, webbrowser from os im...
# -*- coding: utf-8 -*- """ Created on Tue Mar 23 16:23:44 2021 @author: JABIR """ import math def Area(radius): area = math.pi * radius ** 2 return area def Circumference(radius): circumference = 2 * math.pi ** radius return circumference
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 实现lru算法(最近最少使用算法) ''' import collections from functools import lru_cache class LRUCache(object): ''' function: 利用collections.OrderedDict 数据类型实现 最近最少使用算法 OrderedDict 有一个特殊的方法 popitem(last=False) 即实现队列,弹出最先插入的元素 当last = True ...
# COMMON METHODS # # LISTS # [1, 2, 3].pop() # [1, 2] and it returns 3 [1, 2, 3].append(4) # [1, 2, 3, 4] [1, 2, 3].remove(2) # [1, 3] [1, 2, 3].index(3) # 2 [1, 2, 3].extend([4, 5]) # [1, 2, 3, 4, 5] [1, 2, 3].clear() # [] [1, 3, 3].count(3) # 2 [1, 2, 3].in...
for numbers in range(1, 101): if (numbers % 3 == 0 and numbers % 5 != 0): print('pie') elif (numbers % 5 == 0 and numbers % 3 != 0): print('thong') elif (numbers % 3 == 0 and numbers % 5 ==0): print('piethong') else: print(numbers)
classes bring functions and data together unlike functions and variables classes use uppercase (start with capital letters e.g. WonderDog) # class Dog: # animal_type = "canine" # # # Initialisation # def __init__(self, name, colour): # self.name = name # self.colour = colour # self.legs ...
# a for loop iterates through an iterable # a while loop will run forever # as long as a condition is True # x = 1 # while x < 10: # print(f"x is currently {x}") # x += 1 # if x == 4: # break # print(f"x is now {x}") # x += 1 # this will loop forever dont click run, - because x is always l...
from calculator import SimpleCalculator import unittest class CalculatorTests(unittest.TestCase): calc = SimpleCalculator() def test_add(self): self.assertEqual(self.calc.add(2, 7), 9) self.assertEqual(self.calc.add(-5, -20), -25) def test_subtract(self): self.assertEqual(self.ca...
# % = modulo =the remainder - 15 % 3 == 0, 17 % 3 == 2 #fizzbuzz game # FizzbuzzPrint every number from 1 to 100 # If divisible by 3, print Fizz instead # If divisible by 5, print Buzz instead # If both? FizzBuzz! for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: print("Fizzbuzz!") ...
Dictionaries Dictionary = a collection of Key-Value Pairs, only can look up key first then the value like a real life dictionary we seperate key value pairs with commas with pycharm we can't have duplicate keys # about_me = { # "name": "Zeeshan", # "age": 22, # "favourite food": "Pizza", # "job": "SRE...
for i in range(1,6,1): for j in range(1,6,1): if i==1 or i==5 or j==1 or j==5 or i==3 or j==3: print "*", else: print " ", print ""
import numpy as n a=n.array([[1,2,3],[4,5,6]]) b=n.array([[1,1,1],[2,2,2]]) for i in range(0,2,1): for j in range(0,3,1): a[i,j]=a[i,j]+b[i,j] print for i in range(0,2,1): for j in range(0,3,1): print a[i,j], print
class Books: def __init__(self, book_title, book_author, book_isbn, book_year): self.book_title = book_title self.book_author = book_author self.book_isbn = book_isbn self.book_year = book_year def add_book(self,book): print(self.book_author)
# Απόσταση = Ταχύτητα * Χρόνος taxitita = float(input('Δώσε την ταχύτητα του οχήματος (σε km/h): ')) print() ora = int(input('Δώσε τον αριθμό των ωρών που έχει ταξιδέψει: ')) print() print('Ώρα\t| Διανυθείσα Απόσταση') print('-----------------------------') for x in range(1, ora+1): apostasi = float(taxit...
# Εθνικός φόρος 4% και Δημοτικός φόρος 2% ETHNIKOS_FOROS = 0.04 DIMOTIKOS_FOROS = 0.02 def ektelesi(): buy_cost = kostos_agoras() ethnikos_foros = float(buy_cost * ETHNIKOS_FOROS) dimotikos_foros = float(buy_cost * DIMOTIKOS_FOROS) synolikos_foros = float(ethnikos_foros + dimotikos_foros) ...
# Θερμιδες λίπους = γραμμάρια λίπους * 9 # Θερμ΄ίδες από υδατάνθρακες = γραμμάρια υδατανθράκων * 4 def ektelesi(): print('Το πρόγραμμα σας ζητάει τον αριθμό των γραμμαρίων λίπους και ' 'υδατανθράκων που καταναλώνετε την ημέρα, και υπολογίζει τον ' 'αριθμό των θερμίδων, που προέρχονται α...
def main(): numbers_entry = ekxorisi() ypologismos(numbers_entry) def ekxorisi(): lista = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] count = 1 count2 = 0 lista2 = [] while count != 0 : for x in range(3): for y in range(3): a...
# 1 πόδι = 12 ίντσες def ektelesi(): foot_number = arithmos_podion() calculation = ypologismos(foot_number) ektyposi(calculation) def arithmos_podion(): podia = int(input('Δώσε τον αριθμό ποδιών που θέλεις να υπολογίσεις σε ίντσες: ')) print() return podia def ypologismos(foot...
# Δεχετε δύο τυχαιες ακέραιες τιμές και επιστρέφει την μεγαλύτερη import random def ektelesi(): num1, num2 = eisodos_arithmon() maximum(num1, num2) def eisodos_arithmon(): for x in range(2): arithmos = random.randint(1, 100) # εισάγει τους τυχαίους αριθμούς if x == 1: ...
#ΑΣΚΗΣΗ 6 CLASSES import save_data import menu_choices SEARCH = 1 ADD = 2 CHANGE = 3 DELETE = 4 EXIT = 5 def main(): #ΑΣΚΗΣΗ 4 #obj1 = Employee('Susan Meyers', 47899, 'Accounting', 'Vice Precident') #obj2 = Employee('Mark Jones', 39119, 'IT', 'Programmer') #obj3 = Employee('Joy Rogers', 81774, 'Manifa...
def main(): num = number() convert_num(num) def convert_num(num): num = num.upper() phone_num = '' for nm in num: if nm == "A" or nm == 'B' or nm == 'C': phone_num = phone_num + '2' elif nm == 'D' or nm == 'E' or nm == 'F': phone_num = phone_num + ...
from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split from sklearn.externals import joblib import PythonLab.car_models as cm import PythonLab.car_data_preprocessing as cdp def create_mlp(name, per): data, target = cdp.hot_feature, cdp.target # 获得原始数据转变成的数值信...
# Napisz program, który pyta o 3 parametry i przedstawia postać równania # kwadratowego z tymi parametrami. # Podaj a: 2 # Podaj b: 3 # Podaj c: 4 # y = 2 x^2+ 3 x + 4 # • Rozbuduj program tak by obliczał DELTĘ # Podaj a: 2 # Podaj b: 6 # Podaj c: 1 # y = 2 x^2+ 6 x + 1 # Delta wynosi: 28 stra = input("Podaj A równani...
# Napisz program, który podany przez użytkownika ciąg znaków szyfruje przy # użyciu szyfru Cezara i wyświetla zaszyfrowany tekst. string = input("Podaj string do zaszycezarowania ") string2 = '' for letter in string: string2 += chr(ord(letter) + 3) print("Zaszycezarowane: " + string2) #to rozwiazanie jest SŁABE!...
A = int(input()) for x in range(1, A+1): a,b = map(int, input().split()) if (b == 0): print("divisao impossivel") else: media = a/b print(media)
total = float(0) for x in range (int(input())): n1, n2 = list(map(int,input().split())) if(n1 == 1001): total+= 1.50 * n2 if(n1 == 1002): total+= 2.50 * n2 if(n1 == 1003): total+= 3.50 * n2 if(n1 == 1004): total+= 4.50 * n2 if(n1 == 1005): total+= 5.50 * n2 print('%0.2f'%total)
for x in range (int(input())): A = int(input()) if(A > 8000): print("Mais de 8000!") else: print("Inseto!")
A = input().split("/") d,m,a = A print("{}/{}/{}".format(m, d, a)) print("{}/{}/{}".format(a, m, d)) print("{}-{}-{}".format(d, m, a))
''' You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), If the current building's height is...
''' ou are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a con...
''' Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string. ''' class Solution: def minDistance(self, word1: str, word2: str) -> int: n = len(word1) + 1 m = len(word2) + 1...
''' Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decr...
def merge(arr1, arr2): i = 0 j = 0 final_arr = [] while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: final_arr.append(arr1[i]) i += 1 else: final_arr.append(arr2[j]) j += 1 while j < len(arr2): final_arr.append(arr2...
# 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? nums = [4,3,2,7,8,2,3,1] from collections import Counter count = Counter() res = [] ...
# Given a collection of intervals, merge all overlapping intervals. #intuition is: first, we need to sort the interval #when compared 2 intervals, if the second index of the first interval #is greater than the first index of the second interval => overlapping #we can update the second index of the first interval to be...
# Given an array of integers and an integer k, you need to find # the total number of continuous subarrays whose sum equals to k. nums = [3,4,7,2,-3,1,4,2,1] k = 7 # prefix sum and a dictionary to keep track # see https://www.youtube.com/watch?v=bqN9yB0vF08 for explanation check = {0:1} counter = 0 preSum = 0 #intui...
s = '([)))' mymap = {')':'(', ']':'[', '}':'{'} #make a map for easier look up. The reason you want the close parentheses to be #the key is to look up the value and check against the last item in the stack stack = [] #make an empty stack for char in s: #go through each character of...
#Given a non-empty array of integers, every element appears twice except for one. # Find that single one. nums = [4,1,2,1,2] hmap = {} for i, num in enumerate(nums): if num in hmap: hmap[num] += 1 else: hmap[num] = 1 for num in hmap: if hmap[num] == 1: print(num) #%% # XOR appro...
#Given an array nums of integers, return how many of them contain an even number of digits. def findNumbers(nums): even = 0 for i in nums: counter = 0 while i > 0: i = int(i / 10) #how many times you can divide a number by 10 before it hits counter += 1 if counte...
# Given two strings s and t, determine if they are isomorphic. # Two strings are isomorphic if the characters in s can be replaced to get t. # All occurrences of a character must be replaced with another character while preserving the order of characters. # No two characters may map to the same character but a characte...
st = 'XCIV' roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1} # make a map for easy look up sum = 0 for i in range(0,len(st)-1): if roman[st[i]] < roman[st[i+1]]: #if the letter with lower value is in the previous position, then we subtract it sum -= roman[st[i]] else: sum +...
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. # An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. # You may assume all four edges of the grid are all surrounded by water. #DFS #the intuition is that when you search for an islan...
# Write an algorithm to determine if a number n is "happy". # # A happy number is a number defined by the following process: # Starting with any positive integer, replace the number by the sum of the squares of its digits, # and repeat the process until the number equals 1 (where it will stay), # or it loops endlessly ...
# Given a string s consists of upper/lower-case alphabets and empty space characters ' ', # return the length of last word (last word means the last appearing word if we loop from left to right) # in the string. If the last word does not exist, return 0. # Note: A word is defined as a maximal substring consisting of no...
# #Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # You may assume all the characters consist of printable ascii characters. s = ["H","a"...
import sys input = sys.stdin.readline while True: a, b = map(int, input().split()) if a == 0 and b == 0: break else: c = b // a d = a // b if b % a == 0 and a * c == b: print("factor") elif a % b == 0 and b * d == a: print("multiple") ...
import sys input = sys.stdin.readline burger = 2000 beverage = 2000 for _ in range(3): price = int(input()) if burger >= price: burger = price for _ in range(2): price = int(input()) if beverage >= price: beverage = price print(burger + beverage - 50)
from abc import abstractmethod class Bird: fly = True def noise(self): print("Birdnoise") babies = 0 def reproduce(self): slef.babies += 1 def children(self): return self.babies @abstractmethod def eat(self): pass extinct = False class Owl(Bird): ...
from abc import abstractmethod # again, intentionaly over engineered into a single class class Mountains: def __init__(self, peakList): self.peakList = peakList self.pathList = [] self.currentPos = 0 def find_path(self): self.find_next(True) while self.currentPos < le...
x=int(input()) z=1 while(x!=0): z=x*z x=x-1 print(z)
import zipfile def reading_file_custom(): extract_input = input("\nWould you like to read the text in the file that you just created and compressed? [Yes/No] ") extract_input_lower = extract_input.lower() if extract_input_lower == "yes": user_file_read = input("What text file would you li...
import zipfile def zipping_file_predef(): zip_input = input("\nWould you like to zip the text file, which includes the word sentence and positions, so that it takes up less space? [Yes/No] ") zip_input_lower = zip_input.lower() if zip_input_lower == "yes": zipname_input = input("What woul...
import pandas as pd import numpy as np array = np.array([[1,8,3],[5,6,7]]) dataframe = pd.DataFrame(array, index= ['a','b'], columns = list('123')) print(dataframe) #suma de columnas dataframe.sum() #para sumar por filas dataframe.sum(axis=1) #El minimo valor es dataframe.min() #el valor maximo dataframe.max() #co...
import pandas as pd import numpy as np lista_valores = np.arange(25).reshape(5,5) print(lista_valores) lista_indices = ['i1','i2','i3','i4','i5'] lista_columnas = ['c1','c2','c3','c4','c5'] dataframe = pd.DataFrame(lista_valores, index=lista_indices, columns=lista_columnas) print(dataframe) #para traer una column...
# search texto = "Hola, mi nombre es Daniel" import re #Permite buscar una cadena de variables, devuelve un objeto tipo Match resultado = re.search("nombre", texto) re.search("Daniel$", texto) #con el signo dolar buscará la última palabra de la cadena re.search("^Hola", texto)#Buscara por la primera palabra de la ca...
#Esto crea el fichero fichero = open("fichero_para_grabar.txt","wt")# la W es de : write. Y la T es de: text texto_del_fichero = "Hola, esta es la linea que vamos a grabar en el fichero de texto" #con el metodo write guardamos el texto dentro del fichero fichero.write(texto_del_fichero) fichero.close()
#Es como un array pero esta indexado por unos valores import pandas as pd serie1 = pd.Series([3,5,7]) print(serie1[1]) asignaturas = ['matematicas', 'historia', 'fisica', 'literatura'] notas = [8,6,9,7] serie_notas_daniel = pd.Series(notas, index= asignaturas) print(serie_notas_daniel) print(serie_notas_daniel['...
import pandas as pd import numpy as np lista_valores = {'clave1':['x','x','y','y','z'], 'clave2':['a','b','a','b','a'], 'datos1':np.random.rand(5), 'datos2':np.random.rand(5)} print(lista_valores) dataframe = pd.DataFrame(lista_valores) print(dataframe) #queremos c...
import pandas as pd import numpy as np np.arange(3) serie = pd.Series(np.arange(4), index=['a','b','c','d']) #print(serie) #así se elimina un elmento de una serie #print(serie.drop('c')) #reshape dice las columnas y filas que tendrá lista_valores0 = np.arange(9).reshape(3,3) print(lista_valores0) lista_filas= [...
""" Demonstration of Runge's phenomenon. """ USE_CHEB = True import matplotlib.pyplot as plt from scipy.interpolate import barycentric_interpolate import numpy as np def runge_fn(x): "Runge's function" return 1/(1 + 25*x**2) # fine grid for plotting x_fine = np.linspace(-1, 1, 1000) # draw the true function...
from typing import List import sys # URL: # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ # Question: # Say you have an array for which the ith element is the price of a given stock on day i. # If you were only permitted to complete at most one transaction # (i.e., buy one and sell one share of the ...
import math from collections import deque from typing import List import collections from ListNode import ListNode # URL: # https://leetcode.com/problems/add-two-numbers/ # Question: # You are given two non-empty linked lists representing two non-negative integers. # The digits are stored in reverse order, and each o...
from typing import List # URL: # https://leetcode.com/problems/reorder-data-in-log-files/ # Question: # You have an array of logs. Each log is a space delimited string of words. # For each log, the first word in each log is an alphanumeric identifier. Then, either: # Each word after the identifier will consist onl...
if(False): print("Birinci durum") elif(True): print("İkinci durum") a = int(input("Birinci sayıyı giriniz : ")) b = int(input("İkinci sayıyı giriniz : ")) c = int(input("1.Toplama 2. Çıkarma 3.Çarpma 4.Bölme : ")) def topla(x,y): return(x+y) def cikar(x,y): return(x-y) def carpma(x,y): return(x*y) def bolme(x,y...
import time from Hangman_Phases import Phases import random # Functions&Classes class Functions: #Variables def starter_variables(self): self.play_again = True self.letter_index = 100 # Introduction def introduction(self): print("\n\n" + '*' * 37 + " Hangman " + '*' * 37 + "\...
from itertools import chain MORSE_ALPHABET = { 'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-'...
def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return list a=input() la=a[-1] eve=[] ans=0 nil=0 for _ in a: if(int(_)%2==0): eve.append(_) if(len(eve)==0): print(-1) else: for _ in range(len(a)): if(int(a[_])%2==0): nil=_ ...
counter =0 lotto =[2, 23, 41, 53, 63, 11] print ("The Lotto Numbers are " + str(lotto)[1:-1]) user = [0,0,0,0,0,0] def no_duplicates(user,num): for x in range(0,6): if(user[x] == num): return True for x in range(0,6): while True: try: num =int(input("Lotto Number: \n")...
# Eric Chiu # Client-Server Chat implemented using python's socket module # Client side of chat # Type /q to end the chat import socket addr = '127.0.0.1' port = 5000 # establishes server on specified host and port client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((addr, port)) print(f'Y...
#recursion: ex: def is_even(x): if x==0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) #is_even(5)---------False #is_even(4)----------True # is_odd(6)--------False
#continue statement for num in range(2,10): if num%2==0: print num,'is even number' continue #using else condition(continue or else) print num,'is odd number'
from __future__ import print_function import tkMessageBox class Languages: #def __init__(self, python,java): #self.python = python #self.java = java def PythonQuestions(self): tkMessageBox.showinfo(title="Python Questions", message="Are you ready, will be Start...
def questions(): global Questions global ans Questions={"python": {1:"1. python is a ? \n a.Development environment\n b.Programming language \n c.Set of editing tools ", 2:"2. Which of these statements is true \n a.CPython is an implementation of python\n b.Pyhon cod...
import tkMessageBox def questions(): global Questions global ans Questions={"python": {1:"1. python is a ? \n a.Development environment\n b.Programming language \n c.Set of editing tools ", 2:"2. Which of these statements is true \n a.CPython is an implementation of...
import questions import tkMessageBox def Quiz(subject): total=10 correct=0 wrong=0 print subject global questions for i in range(len(questions.Questions.get(subject))): print questions.Questions.get(subject).get(i+1) answer=raw_input("Enter the answer: ") ...
#Mutable Data + Iteration: Sorting out Artists def numMatches( list1, list2 ): '''return the number of elements that match between two sorted lists''' matches = 0 i = 0 j = 0 while i < len(list1) and j < len(list2): if list1[i] == list2[j]: matches += 1 i += 1 ...
Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "copyright", "credits" or "license()" for more information. >>> RESTART: /home/linuxuser/Desktop/python/Assessment/Assessment/submit_interviewTest/Interview_Online_Test/InterviewTestApplication.py LETS START THE PYTHON QUE...
#coding:utf-8 """ opencv形态学边缘检测 """ import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('images/figure_2.png',0) cv2.imshow('original img',img) #定义一个3*3的十字形结构元素 kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3)) #图像膨胀 dilated = cv2.dilate(img,kernel) #图像腐蚀 eroded = ...
#coding:utf-8 """ 输入一个整数n,求从1到n这n个正数中,1出现的次数。例如:输入12,出现一的数字有1,10,11,12共有5个1,则输出5. """ def count_number_one(n): count = 0 for i in range(n+1): while i: if i % 10 == 1: count += 1 i = i/10 return count print(count_number_one(12))
#coding:utf-8 """ 没有加法运算符的加法实现, 没有减法运算符实现减法运算 """ def plus_nums(a,b): if a == 0: return b elif b == 0 : return a else: xor_ab = a^b and_right = (a&b) << 1 return plus_nums(xor_ab,and_right) def sub_nums(a,b): if a == b: return 0 else: inverse_b = plus_nums(~b,1) return plus_nums(a,inverse_b) pri...
#coding:utf-8 """ 两个队列实现栈 """ class Stack(object): def __init__(self): self.q1 = [] self.q2 = [] def in_stack(self,data): while self.q2: self.q1.append(self.q2.pop(0)) self.q1.append(data) print(data,'------in stack') def out_stack(self): while self.q1: self.q2.append(self.q1.pop(0)) try: ...
"""Class definitions of player-related deatils in Blackjack.""" import time from cards import Card, Shoe, Hand class Player: """ This class has a Hand of cards and the input logic for the Player. Contains info (name, credit) of Player, their Hand, and the move-making logic for the Player. Par...
tariff = str(input("Which tariff? 11 or 31:")) while tariff != "11" and tariff != "31": print("Invalid") tariff = str(input("Which tariff? 11 or 31:")) if tariff == "11": tariff = 0.244618 else: tariff = 0.136928 daily = float(input("Enter daily use in kWh: ")) days = int(input("Enter number of...
#Author: Kyo Kipp #This program simulates multiple games of Rock, Paper, Scissors #and keeps a running score of the wins, losses and ties. import random def main(): input('Welcome!\nI challenge you to a game of rock, paper, scissors.'\ ' Best of 7!\nPress Enter to begin.') #Initiali...
import os import pandas as pd import sys import csv import glob import shutil import ntpath #you don't need this function def combine_file(*file_input): list_of_data = [] # reader = [csv.reader(file_input)] #for i in reader: # df = pd.read_csv(i) # list_of_data.append(df) for file in fi...
import pandas as pd import numpy as np import matplotlib.pyplot as plt '''df3=pd.DataFrame({'AAA':[4,5,6,7], 'BBB':[10,20,30,40], 'CCC':[100,50,10,-50]}) #df3.loc[df3.AAA>=5,'BBB']=-1 #df3.loc[df3.AAA>=5,'BBB','CCC']=555 df3['logic']=np.where(df3['AAA']>5,'High','Low') print(df3) ...
def outer(x): def inner(a,b,c): return (a*x**2+b*x+c) return inner p=outer(3) print(p(4,-2,5))
# -*- coding: utf-8 -*- """ Created on Tue Jul 6 22:32:01 2021 @author: snkt8 """ fn= input("Enter Filename: ") f = fn.split(".") print ("Extension of the file is : " + f[-1])
# Пользователь вводит строку из нескольких слов, # разделённых пробелами. Вывести каждое слово с новой строки. # Строки необходимо пронумеровать. # Если в слово длинное, выводить только первые 10 букв в слове. my_list = input('Enter some words,separated by spaces: ') my_list = my_list.split(' ') cnt = 0 for i ...
from math import sqrt print("Поиск полщади треугольника по формуле Герона") print("Введите стороны треугольника:") a = float(input("Сторна а = ")) b = float(input("Сторна b = ")) c = float(input("Сторна c = ")) p = (a + b + c) / 2 s = sqrt(p * (p - a) * (p - b) * (p - c)) print("S треугольника =","%.2f" % s)
#Mathew De La Cruz def polygon (T,sides,size,c): angle=240/sides T.color(c) for times in range(sides): T.forward(size) T.left(angle)
from math import sqrt # List of primes: primes = [2, 3, 5, 7] # Truncatable primes from left and right: t_primes = [] # Number of primes truncatable from left and right: limit = 11 def isprime(n): if n < 2: return False for i in primes: if i > sqrt(n): break if n % i == 0: return False primes.append(n)...
# for12_Quiz.py # Quiz 1) a 에서 abc 가 아닌 문자는 무엇인가요? (중복제거) a = 'aybxczbcyazcaxbc' b = { s for s in a if s not in 'abc' } print(b) # [ 입력변수 if 조건 for 추출변수 in 대상 if 조건 ] # Quiz 2) 학생들의 국어점수가 70 이상이면 '합격', 아니면 '불합격' 국어점수 = {'Tom':90,'Jane':60,'Alice':70} print(국어점수) # a if 조건 else b r = { 학생이름:'합격' if 국어점수[학생이름] >=70...
# gui01.py # Python GUI --> tkinter, wxPython,PyQt # 위젯 (Button,Label,Entry,,,,) from tkinter import * def btn1Click(): text1.insert(0,text1.get()+"님 어서오세요! ") window = Tk() ################# label1 = Label(window,text="이 름") label1.grid(row=0,column=0) #label1.pack() text1 = Entry(window) text1.grid(row=0,c...
# for02.py for i in range(0,10,1): print(i) # 1 ~ 5 까지 가로방향 출력 # 1 2 3 4 5 for i in range(1,6,1): print(i,end=' '); print() # 0 ~ 10 까지 짝수만 출력 : 가로방향 for i in range(0,11,2): print(i,end=' '); print() for i in range(0,11,1): if(i%2==0): print(i,end=' ') print() num1 = [i for i in range(0,10)] st1 = "...
# for09.py a = [] # a 에 for문을 사용해서 1 ~ 10 까지 입력 # a[0] <- 1, a[9] <- 10 for i in range(0,10,1): #a[i] = i+1 <----- 얘만 error #a = a + [i+1] #a.append(i+1) # append: 원래 있던거에 element 추가 # extend: 원래 있던거에 list 추가 print(a)
# for03.py # 7단 출력 # 7 * 1 = 7 # ~~~~~ # 7 * 10 = 70 print("몇 단을 출력할까요?") j = int(input()) for i in range(1,11): print("{} * {} = {}".format(j, i, j*i))