text stringlengths 37 1.41M |
|---|
# Log analyser for some digital cinema projectors
# ver.0.00.00.12
# written by Samvel
from typing import Set
print('Hello, my friend! I\'m lazy application, so put the unpacked logs into application\'s path')
logfile = open('ProjectorLog.txt', 'r') # opening of standard ProjectorLog file
logfilecontent = l... |
#Manthan Gajjar
# A List is a collection which is ordered and changeable. Allows duplicate members.
numbers = [1,3,4,5,6,7,12,445]
print(numbers)
#using Constructors
numbers1 = list((1,2,4,5,6,7))
print(numbers1)
fruits = ["Apples", "Oranges", "Grapes", 5]
print(fruits)
#Get Specific value from Index
print(fruits[2... |
# for n in range(2,10):
# for i in range(2,n):
# if n % i == 0:
# print(n,"equal", i, "*" ,(n//i))
# break
# else:
# print( n ,"is a prime")
for i in range(1,10):
if i%2==0:
print(i,"prime")
continue
print("ma")
while True:
pass
prin... |
'''########################################################'''
'''########################################################'''
'''########################################################'''
'''Hands On'''
# Take your street address and make it a list variable myaddress
# where each token is an element.
# What would ... |
def poweroftwo(num):
return (num & (num - 1)) == 0
print poweroftwo(8)
print poweroftwo(7)
8 = 1 0 0 0
7 = 0 1 1 1
-----------
& = 0 0 0 0 |
def bitsort(input):
l, u = 0, (len(input) - 1)
while(l < u):
if input[l] == 1:
if input[u] == 0:
input[l] ^= 1
input[u] ^= 1
l += 1
u -= 1
else:
l += 1
return input
print bitsort([0,1,1,0,1,0,1,0,0,1,1,1,0]) |
#!/usr/bin/env python
# encoding: utf-8
"""
node.py - Node Class of every node (square) on grid (screen)
~ Daniel Cortild, 30 July 2021
"""
import pygame
from constants import *
class Node:
""" Node Class, represents each node (square) on the grid (screen) """
def __init__(self, row, col, width, total_rows):
... |
from collections import Counter
def friends_of_friend_ids_bad(user):
#"foaf" acrônimo friend of a friend
return [foaf["id"]
for friend in user["friends"] #para cada amigo de usuário
for foaf in friend["friends"]] #para acada _their_friends
def not_the_same(user, other_user):
# doi... |
import random
def difficultyAttempts(Attempts):
ans=random.randint(1,100)
for i in range(Attempts,0,-1):
print(f"You have {i} attempts remaining to gess the number.")
guess=int(input("Make a Guess: "))
if guess==ans:
print(f"Correct {guess}")
break
... |
"""Quiz."""
def score_quiz(score):
"""Score the quiz based on answers."""
O = 8 + score[5] - score[10] + score[15] - score[20] + score[25] - score[30] + score[35] + score[40] + score[45] + score[50]
C = 14 + score[3] - score[8] + score[13] - score[18] + score[23] - score[28] + score[33] - score[38] + scor... |
# 有A,B两个人随机随机生成一个1-10范围的数字进行比大小,谁大谁赢。共比较100000次,分别计算出A,B的胜率和平局的次数。
# 1.导入随机生成数字范围的包,并编写代码。
import random
# 2.循环比较100000次,再分别定义三个变量记录针对 A,B赢的次数和平局次数做记录
i = 0
A_win = 0
B_win = 0
tie = 0
while i < 100000:
player_A = random.randint(1, 10)
player_B = random.randint(1, 10)
if player_A > player_B:
... |
#Function to get volume of cube
def volume(l):
#check if input is a float
try:
floatL = float(l)
#if not, return error
except ValueError:
return -1
#if length is negative, return error
if l <= 0:
return -1
#Find and return volume
vol = l*l*l
return vol
|
#Создание класса
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + ' is now sitting.')
def roll_over(self):
print(self.name.title() + ' rolled over!')
#Создание экземпляра класса
my_dog = Dog('willie', 6)
... |
#Обработка исключения ZeroDivisionError
try:
print(5/0)
except ZeroDivisionError:
print("\nYou can't divide by zero!")
print('---')
#Использование исключений для предотвращения аварийного завершения программы
#Блок else
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:... |
# Base python
from typing import Tuple, List
# Extended Python
import png
class Warehouse:
"""A small utility class to hold information about the warehouse we are opperating in"""
def __init__(self, file_path: str):
if ".txt" in file_path:
self.occupancy_grid, self.bases = self.load_wareh... |
"""
** Here be DRAGONS **
ce code n'est pas du code pour débutant en python si son usage est simple la compréhension de son fonctionnement nécessite
une très bonne connaissance de python.
Par contre, son usage et son extension pour de nouvelles présentation ou de nouveau fragments de XML, devrait être 'simple' :
Si v... |
# print() 打印 字符串要用''或""括起来
# print('hello world')
# input() 输入
# format 增强的格式化字符 串函数
# "苹果的的钱是:{};葡萄的钱是:{}总花费:{}" .format(apple , grape ,total)
# print (f'{a}') f 是格式化,跟大括号可以输入变量
# 变量 :代表某个值的名称
# 变量名命规范
# 1.标识符的第一个字符必须是字表表中的字线(大写戒小写)或者一下下划线
# 2.标识符的其他以由字母(大写或小写),下划线 "_" ,或 数字0-9组成
# 3.标识符名称是对大小写敏感的
# apple_... |
aNewFile = input("Do You Need To Create A New File?")
print("1 to create new file")
print("2 to read a file")
if aNewFile == 1:
p = open("DinerList.txt", "w")
elif aNewFile == 2:
p = open("DinerList.txt", "r")
print(p.read())
else
p =
|
### iris
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 13:55:13 2020
@author: Gan
"""
### Step 1. Import the necessary libraries
import pandas as pd
import numpy as np
### Step 2. Import the dataset from this [address](https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data)
url = '... |
#----binary search----
def search(ar,item):
beg=0
last=len(ar)-1
while beg<=last:
mid=int((beg+last)/2)
if item==ar[mid]:
return mid
elif item<ar[mid]:
last=mid-1
elif item>ar[mid]:
beg=mid+1
else:
return False
... |
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
... |
"""
Some tools to work on matrices
"""
import numpy as np
def check_zero_matrix(mat_list):
"""
Return the list of matrices ids which are non empty
:param mat_list: List of matrices, usually covariance matrices
:return: list of ids of non empty matrices
"""
non_zero_list = []
for i in r... |
n = int(input('Digite um número para ver sua tabuada: '))
print('-'*10)
print(f'{n:2} x 1 = {n * 1}') # n:2 empurra dois pixels pro lado
print(f'{n:2} x 2 = {n * 2}')
print(f'{n:2} x 3 = {n * 3}')
print(f'{n:2} x 4 = {n * 4}')
print(f'{n:2} x 5 = {n * 5}')
print(f'{n:2} x 6 = {n * 6}')
print(f'{n:2} x 7 = {n * 7}')
p... |
larg = float(input('Largura da parede: '))
alt = float(input('Altura da parede: '))
area = larg * alt
litros = area / 2 # a cada 2m², preciso de 1l de tinta #
print(f'Sua parede tem as dimensões de {larg} x {alt} e uma área de {area}m².')
print(f'Você precisará de {litros}l de tinta.')
|
# Faça um programa que leia um ângulo qualquer
# e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
import math
angulo = float(input('Digite o ângulo que deseja: '))
seno = math.sin(math.radians(angulo)) # pega o angulo, converte em radiano e por fim pega o seno dele
cos = math.cos(math.radians(angulo... |
val = int(input("enter a number: "))
if val / 10 == 0 and val / 20 == 0:
print ('yes')
else:
print('false') |
__author__ = "lfs"
from base import MapBase
class BSTMap(MapBase):
class _Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
def __str__(self):
return "Key: {}, Value: {}".f... |
dict1 = {
"tony":7777,
"lili":8888
}
dict2 = {
"tom":9999
}
dict3 = {**dict1,**dict2} #关键!!! **为解包字典操作
for i,j in dict3.items():
print(i,j)
list1 = ['tony']
list2 = ['tom']
list3 = [*list1,*list2] #* 可解包 数组 元组
print(list3)
#------------------
name = "Tony Jin"
first... |
def read_input(file):
f = open(file,'r')
unsorted_list = [int(line) for line in f]
f.close()
return unsorted_list
def pivot1(unsorted_list,start_index,end_index):
return start_index
def pivot2(unsorted_list,start_index,end_index):
cum_sum = 0
for i in range(start_index,end_index+1):
... |
#!/bin/python
# part 1 of a tutorial on user auth with a db
from pathlib import Path
import csv, sqlite3
import sys, time, traceback
USERS_DB = Path("users.db")
USERS_DB_TABLE_NAME = "users"
CSV_FILE = "sample_user_accounts.csv"
db_connection = None; db_cursor = None; db_records = None
def create_table(data):
# C... |
#refrences:
#https://www.youtube.com/watch?v=rfscVS0vtbw
#https://www.youtube.com/watch?v=OTON2x71DE0
print("Hello")
print("Welcome to the program")
def menu():
#main
choice = input("""
A: Enter a word
B: Check letter or vowel times
C: Palindrome
D: Anagram
Q: Exit
Please enter your choice: """)
# part... |
import re
# advent of code day4 2020
f = open('input')
data = f.read().split("\n\n")
valid = 0
dicts = []
for p in data:
d = {}
for x in p.split():
# print(x)
k, v = x.split(':')
d[k] = v
dicts.append(d)
# print("---------------------")
# solve part 1
for d in dicts:
if ... |
from abc import ABCMeta, abstractmethod
#Playerインターフェース
class Player(metaclass=ABCMeta):
@abstractmethod
def play(self):
pass
@abstractmethod
def stop(self):
pass
@abstractmethod
def seek(self,position):
pass
#動画再生クラス
class VideoPlayer(Player):
def __init__(self... |
"""
Python machine learning chapter 6 code
Model evaluation and parameters tuning
"""
from IPython.display import Image
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
... |
import numpy as np
#import matplotlib as mpl
#import matplotlib.pyplot as plt
def twod(input1, input2):
x = len(input1)
y = len(input2)
in1 = np.char.array(list(input1))
mtx1 = np.tile((in1, y), 1)
print (mtx1)
in2 = np.char.array(list(input2)
mtx2 = np.tile((in2, x), 1)
#mtx2 = np.ro... |
def top10(text, coding):
all_news = []
with open(text, encoding=coding) as f:
all_news.append(f.read().strip('\n'))
words = all_news[0].split()
words.sort()
words_repeat = {}
repeat = 0
for i in range(0, len(words) - 1):
if words[i] == words[i + 1] and... |
def counting_lexemes(code, lexeme):
codeList = code.split()
res = 0
for i in codeList:
if(i.find(lexeme) != -1):
res += 1
print (res)
code = input()
lexeme = input()
counting_lexemes(code, lexeme)
"""
Durante o processo de análise léxica, o código-fonte do programa é lido e separado em palavra... |
#conversão de medidas: metros para centímetros e milímetros
metros = float(input('Quantos metros? '))
cm_convert = metros * 100
mm_convert = metros * 1000
print('{:.1f} metros equivalem a {:.1f}cm e {:.1f}mm'.format(metros, cm_convert, mm_convert)) |
#calcula quantas pessoas tem mais de 21 anos e qtas têm menos
from datetime import date
atual = date.today().year
maiores = 0
menores = 0
for c in range(1,8):
ano = int(input('em que ano a pessoa nasceu? '))
idade = atual - ano
if idade > 21:
maiores = maiores + 1
else:
menores = menore... |
#maior e menor valor dentro de uma tupla
from random import randint
sorteio = (randint(0,10), randint(0,10), randint(0,10), randint(0,10), randint(0,10))
print(f'Os valores sorteados foram: {sorteio}')
print(f'O maior valor sorteado foi: {max(sorteio)}')
print(f'O menor valor sorteado foi: {min(sorteio)}') |
#sortear um nome com random
import random
nome1 = input('digite o nome do primeiro aluno: ')
nome2 = input('digite o nome do segundo aluno: ')
nome3 = input('digite o nome do terceiro aluno: ')
nome4 = input('digite o nome do quarto aluno: ')
lista = [nome1, nome2, nome3, nome4]
escolhido = random.choice(lista)
print('... |
#cálculo valor a pagar pelos dias alugados de um carro e os km rodados
dias_alugados = int(input('Quantos dias alugados? '))
km_rodados = float(input('Quantos Km você percorreu com o carro? '))
valor_aluguel = dias_alugados * 60
valor_km = km_rodados * 0.15
valor_total = valor_aluguel + valor_km
print('{} dia(s) de alu... |
#sortear um número
from random import randint
from time import sleep #vai fazer o computador esperar para dar o resultado
computador = randint(0, 10) #faz o computador sortear um número int de 0 a 5
tentativas = 0
acertou = False
print('Sou seu computador...\n Vou pensar em um número entre 0 e 10. Tente adivinhar qual ... |
#verifica se a frase é um palíndromo
frase = str(input('digite uma frase: ')).strip().upper()
palavras = frase.split() #retirar os espaços entre as palavras
junto = ''.join(palavras) #juntar as palavras sem os espaços entre elas
inverso = ''
for letra in range(len(junto) - 1, -1, -1):
inverso = inverso + junto[letr... |
#cálculo de seno, cosseno e tangente com módulo math
from math import radians, sin, cos, tan
angulo = int(input('digite o valor de um ângulo: '))
seno = sin(radians(angulo))
cosseno = cos(radians(angulo))
tangente = tan(radians(angulo))
print('o ângulo de {} graus tem o seno {:.2f}, cosseno {:.2f} e a tangente {:.2f}.'... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 23:33:21 2020
@author: Supriyo
"""
list1=[1,2,3,4,5,6,7,8]
print("list before cleaning ",list1)
list1.clear()
print("list after cleaning ",list1)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 00:17:10 2020
@author: Supriyo
"""
list1=[89,4,69,23,79,3,65,96,123,78]
list1.sort()
print(list1)
print("shortest number in the list is ",list1[:1])
print("Largest number in the list is ",list1[-1])
print("Second Largest number in the list ",list1[-2]) |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 12:49:36 2020
@author: Supriyo
"""
list1 = [15, 6, 7, 10, 12, 20, 10, 28, 10]
print(list1)
n=int(input("enter the number to be to find occurrences "))
def occourrances(list):
count=0
for i in list1:
if n==i:
count+=1
retur... |
import sys
import csv
"""sys allows me to pass information from the terminal to the script"""
"""sys.argv[x] allows me to access command line arguments"""
def stringparse(file_name, string_to_search):
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(fil... |
"""
Given an array of positive numbers and a positive number ‘k,’
find the maximum sum of any contiguous subarray of size ‘k’.
"""
"""
Bruteforce 0(N*K) Time and 0(N) space
1. find the sum of all possible k sized subarray in the given array
2. find the subarray with the highest sum and return it
"""
k, input... |
"""
Given an array, find the average of all contiguous
subarrays of size ‘K’ in it.
"""
"""
Approach: sliding window 0(N) time and space complexity
Algorithm:
1. instantiate two variables and assigned to zero
2. Add element till the window get to the required window size k
3. calculate the average from the sum... |
lst = [1, 2, 3, 7, 6, 5]
# linear approach
def findPeak(lst):
if len(lst) == 1:
return 0
n = len(lst)
peak = 0
if lst[0] > lst[1]:
return lst[0]
if lst[n-1] > lst[n-2]:
return lst[n-1]
for i in range(1, n-1):
if lst[i] > lst[i-1] and lst[i] > lst... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 08:45:20 2019
@author: bhuwan.madhikarmi
"""
"""
Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body.
A recursive function has to terminate to be used in a program. A recursive function termina... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 3 15:59:10 2019
@author: bhuwan.madhikarmi
"""
class Queue(object):
def __init__(self, head=None):
self.storage = [head]
def enqueue(self, new_element):
self.storage.append(new_element)
def dequeue(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 17:01:52 2019
@author: bhuwan.madhikarmi
"""
class Node(object):
def __init__(self, value):
self.value = value
self.edges = []
class Edge(object):
def __init__(self, value, node_from, node_to):
self. value = value
... |
class Node:
def __init__(self):
self.data = 0
self.next = None
def sortedMerge(a, b):
result = None
if a == None:
return b
if b == None:
return a
if a.data <= b.data:
result = a
result.next = sortedMerge(a.next... |
def pow(x, n):
if n == 1:
return x
elif n == 0:
return 1
elif n%2 ==0:
return pow(x*x, n/2)
else:
return x*pow(x,n-1)
x = 71045970
n = 41535484
d = 64735492
print pow(x,n)
# num = x
# for i in range(1,n):
# num*=x
# print num%d |
A = [ 4, 0, 2, 1, 3 ]
# for i,elem in enumerate(B):
# try:
# A[i] = B[B[i]]
# except:
# print "Invalid Input"
# print A
# A=[A[j] for j in A]
# print (A)
# Works in O(n) space ---> add one element at a time in b, so that b is not passed by
# reference
b=[]
for i in A:
b.append(i)
i=0
while i<len(A... |
def fractionToDecimal(A, B):
if A == 0:
return 0
if B == 0:
if A > 0:
return float("inf")
if A < 0:
return float("-inf")
x = float(A)/float(B)
xtr = str(x)
xtr = str(int("".join(xtr.split("."))))
if len(xtr) == 12:
k = str(x).split(".")
rep = k[1]
for char in rep:
print char
else:... |
# Using dictionary
def isUnique(s): return len({_:1 for _ in s}) == len(s)
print(isUnique("abc"))
print(isUnique("abca"))
|
from random import *
class QubitRegister:
def __init__(self, num_qubits=None):
"""
Constructor
:param numQubits: the size of the register/the number of qubits to initialize. Default = 1
"""
if num_qubits is None:
self.__num_qubits = 1
else:
... |
summans=input()
ones=summans.count("1")
twos=summans.count("2")
threes=summans.count("3")
if len(summans)>1:
if ones>0:
for i in range(1,ones+1):
print("1+" if i<ones else "1",end="")
if twos>0:
print("+" if ones>0 else "",end="")
for i in range(1,twos+1):
print("2+" if i<twos else "2",end="")
if threes>... |
n=int(input())
strInput=input()
nA=strInput.count("A")
nD=strInput.count("D")
if nD==nA:
print("Friendship")
elif nD<nA:
print("Anton")
else:
print("Danik")
|
class Pet:
def __init__(self,legs,lenth):
self.legs = legs
self.lenth = lenth
def size(self):
return self.lenth**2*2
cat = Pet(4,25)
print(cat.size())
class Cat(Pet):
def __init__(self,legs,lenth,color):
super().__init__(legs, lenth)
self.color = color
... |
import os
from banner import banner
banner("HTML TAG COUNTER" , "Brad")
print("Welcome to the HTML tag counter")
def load(filename):
data = []
print(f"..... loading from {filename}")
if os.path.exists(filename):
with open(filename) as fin:
for entry in fin.readlines():
... |
################################################
# File Name: PyGameAnimations
# Creator Name: Mr. Acosta
# Date Created: 1-10-2020
# Date Modified: 1-14-2020
################################################
# This program will demonstrate moving shapes in
# PyGame
####################################... |
def collatz(number):
if number % 2 == 0:
a = number // 2
print(a)
return a
elif number % 2 == 1:
b = 3 * number + 1
print(b)
return b
print('Enter number: ')
num = int(input())
result = collatz(num)
while result != 1:
result = collatz(result)
|
from abc import ABC, abstractmethod
class VkMusic(ABC):
@abstractmethod
def play(self):
pass
@abstractmethod
def download(self):
pass
class MusicList(VkMusic):
def __repr__(self):
return self.__class__.__name__
def play(self):
return 'Playing your choosing t... |
from abc import ABC, abstractmethod
# invoker class
class Pilot():
def __init__(self, button):
self.button = button
def press(self):
return f'Pilot {self.button.press()}\'s turbine'
# receiver class
class Turbine:
def __init__(self):
self.status = 'off'
def set_off(self):
... |
class Employee:
raise_amount = 1.04
def __init__(self,first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+"."+last+"@gmail.com"
def fullname(self):
return "{} {} {}".format(self.first, self.last, self.pay)
def ... |
#!/usr/bin/python
'''
a simple code to rotate a nxn matrix 90* anti-clockwise
'''
N = input() #dimension of matrix
matrix = [ [] for y in range(N)]
def print_matrix(matrix):
print ''
for i,c in enumerate(matrix):
for j, d in enumerate(c):
print d,
print ''
print ''
def rotate... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 12:46:37 2020
@author: ivan
https://medium.com/analytics-vidhya/tf-gradienttape-explained-for-keras-users-cc3f06276f22
Why to use GradientTape?
https://stackoverflow.com/questions/53953099/what-is-the-purpose-of-the-tensorflow-gradient-tape?nore... |
from tempfile import TemporaryFile
# Create a temporary file and write some data to it
fp = TemporaryFile('w+t') #fp is the file pointer of the temporary file
fp.write('Hello universe!')
# Go back to the beginning and read data from file
fp.seek(0)
data = fp.read()
print(data)
# Close the file, after which it ... |
import os
src=input("Enter the path of the file to change the name:")
dst=input("Enter the path with new file name:")
os.rename(src,dst)
print("The file is successfully renamed")
|
from gpiozero import LED, Button
from time import sleep
from random import uniform
left_name = input("Left player name is ")
right_name = input ("Right player name is ")
right_button = Button(15)
left_button = Button(14)
led = LED(4)
left_score = 0
right_score = 0
def pressed(button):
global right_score, left_scor... |
def showInstructions():
print('''
RPG Game
========
Get to the Garden with a key and a potion
Avoid the monsters!
You are getting tired, each time you move you loose 1 health point.
Commands:
go [direction]
get [item]
''')
def showStatus():
print('---------------------------')
print(name + ' is in the ' ... |
# Space:- 26^m
# time :- O(n)
k
class Trie:
class TrieNode:
def __init__(self):
self.isend = False
self.children = [None for _ in range(26)]
def __init__(self):
self.root = self.TrieNode()
"""
Initialize your data structure here.
"""
def inse... |
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10]) # input the correct answers
W = tf.Variab... |
# Import pandas package
import pandas as pd
# Import Data
data = pd.read_csv("country_vaccinations.csv")
# Activate column names
pd.set_option('display.max_columns', None)
# Three first line
Three_first_line = data.head(3)
# Dataframe column
print(data.columns)
# Columns to drop
to_drop = ['source_name', 'source_w... |
"""
Copyright 2020 PeTrA. All rights reserved.
"""
import time
from threading import Thread
def function(_thread_name):
print(_thread_name + " function start.")
count_number = 0
while True:
if THREAD_KEY == -1:
break
print("count number : ", count_number)
count_number... |
# importing the different modules needed for my code
import random
from math import exp
from csv import reader
# Function to get data from excel file and put into a python array
def getData(filename):
data = []
with open(filename, "r") as file:
csv_reader = reader(file)
for row in csv_reader:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 07 22:38:33 2016
@author: Егор
"""
#script 2
date = list(input("Vvedite dd mm yyyy: "))
for x in range(3):
if date[x]<1:
raise NameError('Error')
date[x]=str(date[x])
if len(date[x])==1 and date[x]!=date[2]:
date[x]='0'+date[x]
date = '/'... |
from graph import Graph
from depth_first_search import DepthFirstSearch
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print('Need input file!')
sys.exit(1)
with open(sys.argv[1], 'r') as f:
g = Graph(f)
s = int(sys.argv[2])
search = DepthFirstSearch(g, s)
... |
import sys
from merge_sort import MergeSort
class BottomUP(MergeSort):
@staticmethod
def sort(a):
print("Use BottomUP MergeSort")
n = len(a)
BottomUP.aux = [0]*n
sz = 1
while sz < n:
lo = 0
while lo < n-sz:
BottomUP.merge(a, l... |
#!/usr/bin/python
import sys, itertools
words_file = "./words.txt"
# get a lookup-table of words
with open (words_file, "r") as fh:
words = [ word.strip() for word in fh.readlines() ]
# find all permutations of entered characters,
# and for each permutation, match against words list;
# finally, return the list of... |
words = []
max_match = 0
match_words = []
def match(word1, word2):
global max_match
global match_words
match = 0
for i in range(len(word1)):
if word1[i] == word2[i]:
match += 1
if match > max_match:
max_match = match
match_words = [word1, word2]
return match... |
import networkx as nx
steps = set()
graph = nx.MultiDiGraph()
with open('input.txt') as file:
for line in file:
line = line.split()
if len(line) == 0:
continue
before = line[1]
then = line[7]
steps.add(before)
steps.add(then)
graph.add_edge(befor... |
from tkinter import *
import Login
from PIL import ImageTk, Image
import PIL
class welcomelog:
def __init__(self, window):
self.window = window
self.window.configure(bg="white", bd=10)
self.window.title("Welcome page!")
self.window.geometry("600x600+0+0")
# ==... |
"""
Network : Interconnection of computers is called network
Client : The computers that receive services
Server : The computers that provide services
3 requirements to establish network :
Hardware : Includes Computers,cables,modems,routers,hubs
Software : Includes programs to communicate between server and cl... |
""" ------Immutable,Replace,Change case and checking Start & Ending of String------ """
print('---------Immutable of String----------')
str1 = 'abcd'
print(str1, str1[0], str1[3])
'''
str1[0]='x'
ERROR:
str[0]='x'
TypeError: 'str' object does not support item assignment '''
a = 'Ram'
b = 'madhu'
print('Object refer... |
"""
Variables : STATE
Functions : BEHAVIOR
Entity
Employee : eid name salary address company designation # STATE
get_emp_details() R # BEHAVIOR
update_emp_hike() U
save_emp_deatils() C
del_emp_details() D
Web applications : DATA
expressoin equation
2x2+3x+4 2x2... |
import time
from calendar import month
# EPOCH Time
epoch = time.time()
print("Epoch Time :", epoch)
# Current Time
current_time = time.ctime()
print("Current time :", current_time)
# Current Date Time
from datetime import *
now = datetime.now()
print("Current Date time :", now)
print("Date now : {}-... |
# Python3 code to demonstrate working of
# Unique dictionary filter in list
# Using map() + set() + items() + sorted() + tuple()
# Initialize list
test_list = [
{'gfg': 1, 'is': 2, 'best': 3},
{'gfg': 1, 'is': 2, 'best': 3},
{'gfg': 9, 'is': 8, 'best': 6}
]
# prin... |
"""
1) A = 10, 20, 30
In the above assignment operation, what is the data type of ‘A’ that Python appreciates as?
Unlike other languages, Python appreciates ‘A’ as a tuple. When you print ‘A’, the output is (10,20,30).
This type of assignment is called “Tuple Packing”.
2) A = 1,2,3,4
a,b,c,d = A
In the above... |
import re
string0 = "The rain in Spain"
x = re.search("in", string0)
print(x)
string1 = "The rain in Spain"
x = re.split("\s", string1)
print(x)
|
def conv_list_tuple(l):
if not l:
print('Given argument is Not a List!')
t = tuple()
t = tuple(l)
return t
def conv_tuple_list(t):
if not t:
print('Given argument is Not a Tuple!')
l = []
for i in t:
l.append(i)
return l
def conv_list_set(l):
if not l:
... |
# Factors of given number using for loop and while loop
n = int(input('Enter a integer:'))
for i in range(1, n // 2 + 1):
if n % i == 0:
print(i, end=' ')
print(n)
'''
i=1
while i <= n//2:
if n%i == 0:
print(i,end=' ')
i +=1
print(n)
'''
|
class AgeError(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def __str__(self):
return self.message
try:
age = int(input('Enter an age of yours: '))
if age >= 18:
print('Your are Eligible for Vote!')
else:... |
# REQ : user will give 2 input numbers.Give addition of consecutive
# elements as response
def add(num1, num2):
num1 += 1
num2 += 1
result = num1 + num2
return result
'''
# Approach 1
res = add(10,20)
print("Addition is :",res)
# Approach 2 : using postman
# Approach 3 : unittesting
'''
|
def check_pangram(str):
l = ['abcdefghijklmnopqrstuvwxyz']
for i in str:
for k in l:
if k == i:
print('It is a pangram!')
else:
print('It is not a pangram!')
string = input('Enter a string: ')
check_pangram(string)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.