text stringlengths 5 121k |
|---|
cola = []
import sys
def Crear():
cola = [0,0,0,0,0]
return cola
def push(valor,indice):
cola[indice] = valor
return indice+1 ... |
cola = []
import sys
def Crear():
cola = [0,0,0,0,0]
return cola
def push(valor,indice):
cola[indice] = valor
return indice+1 ... |
import sys
class Nodo():
def __init__(self,datos):
self.datos = datos
self.siguiente = None
def Enlazar():
global raiz
global p
global q
p=Nodo(str(input("Ingrese el elemento a enlazar: "))) ... |
key = {}
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
commonletters = ['e','t','a','o','i','n','s','h','r','d','l','c','u','m','w','f','g','y','p','b','v','k','j','x','q','z']
letters = {}
cipher = input("Cipher:\n")
print("\nAnalysing...\n"... |
def createKey(keyword):
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
cyphertext_alphabet = []
for letter in keyword:
if letter.upper() not in cyphertext_alphabet:
cyphertext_alphabet.append(letter.upper())
... |
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
counts = {}
key = {}
curmax = 0
plain = ''
cipher = input("Cipher:\n").upper()
printnums = int(input("How many results do you want to output?\n--> "))
for i in alphabet:
counts[i] = cipher.count(i)... |
cipher = input("Cipher:\n")
boxnum = int(input("How wide are the boxes?\n--> "))
boxes = []
currentstr = ""
move = []
rearranged = []
condensed1 = []
condensed2 = ""
if len(cipher) % boxnum != 0:
procede = input('Hmm. You are going to have characters left over. Do you want to procede? (y/n) ')
if ... |
"""
/*******************************************************
* Project : DP_MASTER
* Summary : Master Dynamic Programming Concepts
* Author(s) : VGT GAYAN
* Date : 2021/07/24
* Copyright (C) 2020-2021 {VGT GAYAN} <{gayanvgt@gmail.com}>
*
* This code cannot be copied and/or distributed without the expre... |
arr = []
dict={}
duplicate = []
n = int(input("enter the number of elements"))
for i in range(0,n):
element = int(input("enter elementwise"))
arr.insert(i, element)
for i in arr:
if i in dict.keys():
duplicate.append(i)
else:
dict[i] = i
if arr[i] not in dict.keys():
dict[ar... |
import random
data = list(range(237))
def next_batch(batch_size, data, shuffle=True, infinite=True):
batch = (len(data) - 1) // batch_size + 1
print(batch)
while True:
if shuffle:
random.shuffle(data)
for i in range(batch):
yield data[i::batch]
if... |
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("pink")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("blue")
brad.speed(2)
for x in range (0,4):
brad.forward(100)
brad.right(90)
x = x+1
angie = turtle.Turtle()
angie... |
'''
Bryan Baraoidan
mudroom.py
This file contains the definition for a room in the game world
'''
class MudRoom:
def __init__(self, name, description, contents, exits):
"""
str: name, description
str list: contents
str dict: exits
"""
self.name = name
self.de... |
def binarysearch(item_list,item):
first = 0
last = len(item_list) - 1
found = False
while(first<=last and not found):
mid = (first+last)//2
if item_list[mid] == item:
found = True
else:
if item< item_list[mid]:
last = mid-1
else... |
L=[]
while len(L) <3:
new_name = input("Add name: ").strip()
L.append(new_name)
if len(L)==3:
print(L)
|
import matplotlib.pyplot as plt
snacks = ['jumbo','palito de queso','galletas oreo','perro','helado']
precio = [2000,4000,3500,5000,4000]
plt.bar(snacks,precio)
plt.title('Snacks favoritos')
plt.xlabel('snacks')
plt.ylabel ('precio')
plt.savefig ('graficos snacksfavoritos.png')
plt.show()
cuidad1 = input("Ingresa ... |
ab={
'Swaroop':'swaroop@swaroopch.com',
'Larry':'larry@wall.com',
'Mali':'mali@qq.com',
'Spa':'spa@hotmail.com'
}
print('Swaroop \'s address is ',ab['Swaroop'])
del ab['Spa']
print('\nThere are{}contents in the address-book\n'.format(len(ab)))
for name,address in ab.items():
print('Contact {} at {... |
class person(object):
def __init__(self,name,age,nama_lawan):
self.name = name
self.age = age
self.nama_lawan = nama_lawan
def sapa(self):
print("halo namaku: "+self.name)
print("namamu siapa?")
def salamkenal(self):
print("halo namaku: "+se... |
def isArNum(n, s):
c = 0
t = n
while t > 0:
r = t % 10
c += r ** s
t //= 10
return (c == n)
n = int(input())
s = len(str(n))
print(isArNum(n, s))
|
import math
def gcdpf(a, b):
if a == 0:
return b
if b == 0:
return a
if a == b:
return a
if a > b:
return gcdpf(a - b, b)
else:
return gcdpf(a, b - a)
def gcdea(a, b):
if b == 0:
return a
return gcdea(a, a % b)
a = int(input())
b = int(inp... |
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('coinbaseUSD.csv')
df['Date'] = pd.to_datetime(df['Timestamp'],unit='s').dt.date
group = df.groupby('Date')
Price = group['Close'].mean()
days_to_predict = 90
df_train= Price[:len(Price)-days_to_predict]
df_test= Price[len... |
from sys import stdout
from intcode import Intcode
def read_data():
with open('input.txt') as program:
return [int(code) for code in program.read().strip().split(',')]
class Scaffolding:
def __init__(self):
self.ic = Intcode(read_data())
self.area = dict()
self.x_size = self.... |
from path import manhattan, read_data, parse
wires = read_data()
pathes = parse(wires)
distances = [manhattan(p, (0, 0)) for p in pathes[0] if p in pathes[1]]
print(min(distances))
|
def swap(lIdx, rIdx):
"""
:param lIdx: Left Index
:param rIdx: Right Index
:return: nothing
"""
temp = array[lIdx]
array[lIdx] = array[rIdx]
array[rIdx] = temp
def partition(array, firstIdx, lastIdx):
"""
:param array: array being partitioned
:param firstIdx: head of the... |
def main():
s=int(input(""))
temp=s
rev=0
while(s>0):
dig=s%10
rev=rev*10+dig
s=s//10
if(temp==rev):
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
|
posneg=[0,0]
while True:
number = int(input("Please input number : "))
if number > 0:
posneg[0]+=1
elif number<0:
posneg[1]+=1
else:
break
print("Positive :",posneg[0])
print("Negative :",posneg[1])
|
status={90:'Senior Status',60:'Junior Status',30:'Sophomore Status',0:'Freshman Status'}
while True:
credit = int(input("Enters the number of college credits earned : "))
for credit_rule,std_status in status.items():
if credit>credit_rule or credit_rule==0:
print(std_status)
... |
name = input("What is your name? ")
lastname = input("What is your lastname? ")
print("Hello",name,lastname)
print("Welcome to Python!")
|
n = int(input('n: '))
number_range = [True for _ in range(10**n)]
count=0
for number in range(10**n):
if number_range[number]==False or number < 2:
number_range[number]=False
continue
if number>=(1+10**(n-1)):
count+=1
for not_prime in range(number*2,10**n,number):
n... |
unit=['K','C','F','R']
def temp2kelvin(temp,inunit):
if inunit == 0:
return temp
elif inunit == 1:
return temp+273.15
elif inunit == 2:
return ((temp+459.67)*5/9)
elif inunit == 3:
return ((temp-7.5)*40/21+273.15)
return -999
def kelvin2temp(kelvin,outunit):
if ... |
class LinkedList:
head = None
def add(self, element):
if self.head is None:
self.head = Node(element)
return
new_start = Node(element)
new_start.pointer = self.head
self.head = new_start
def pop(self):
if self.head is None:
... |
class ThreeInOne:
def __init__(self, stackSize):
self.__stackCapaity = stackSize
self.__array = [None]*3*stackSize
self.__sizes = [0]*3
def push(self, stackNum, value):
if(int(stackNum) > 2):
print("Stack number should be less than 3")
return
if(s... |
from linkedList import LinkedList
def returnKthToLast(linkedList, k):
ptr1 = linkedList.head
ptr2 = linkedList.head
for i in range(0, k-1):
try:
ptr2 = ptr2.next
except Exception as exception:
return exception
while(ptr1.next and ptr2.next):
ptr1 = ptr1.... |
from linkedList import LinkedList
import math
def sumLists(linkedList1, linkedList2):
number1 = ""
number2 = ""
current1 = linkedList1.head
while(current1):
print(current1)
number1 = number1+str(current1.value)
current1 = current1.next
current2 = linkedList2.head
while(... |
class CaseInsensitive:
def __init__(self, **kwargs):
for key, value in kwargs.items():
self[key.lower()] = value
def __contains__(self, key):
return super(CaseInsensitive, self).__contains__(key.lower())
def __getitem__(self, key):
return super(CaseInsensitive, self).__getitem__(key.lower())
def __setit... |
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication
class Simple_window(QMainWindow):
"""
This is a simple examplo about how generate a GUI whith PyQt5
"""
def __init__(self):
super(Simple_window, self).__init__()
self.setGeometry(300, 300, 320, 300)
self... |
from tkinter import *
from tkinter import messagebox
def clear():
name_entry.delete(0,
END
)
surname_entry.delete(0,
END
)
def display():
messagebox.showinfo("GUI Python",
name_entry.get... |
from tkinter import *
root = Tk()
root.title("Fill Method")
root.geometry("500x500")
btn1 = Button(text="CLICK ME",
background="#555",
foreground="#ccc",
padx="15",
pady="6",
font="15"
)
btn1.pack(side=RIGHT,
fill=Y
... |
import random
print("random() - (0.0 до 1.0)): ")
number = random.random()
print(number)
print("\nrandom() - (0.0 до 100.0)): ")
number = random.random() * 100
print(number)
print("\nrandint(min, max): ")
number = random.randint(1, 13)
print(number)
print("\nrandrange(start, stop, step): ")
number = random.randrang... |
import numpy as np
import matplotlib.pyplot as plt
"""
from default.KMeans import KMeans
"""
from sklearn.cluster import KMeans
data = np.loadtxt("gauss_clusters.txt", delimiter=",", skiprows=1)
x = [x for x, y in data]
y = [y for x, y in data]
colors = np.random.rand(len(data))
plt.scatter(x, y, c=... |
"""
There is a popular conjecture in Maths which states that numbers that can be expressed as a sum of three cubes of integers,
allowing both positive and negative cubes in the sum. Refer https://en.wikipedia.org/wiki/Sums_of_three_cubes
Andrew Booker wrote an algorithm in March 2019 in order to find the result for ... |
def my_function():
print("Hello From My Function!")
def my_function_with_args(username, greeting):
print("Hello, %s, From My Function! I wish you %s" % (username, greeting))
def sum_two_number(a, b):
return a + b
my_function()
my_function_with_args("Jo... |
import json
json_string = json.dumps([1, 2, 3, "a", "b", "c"])
print(json.loads(json_string))
def add_employee(salaries_json, name, salary):
salaries = json.loads(salaries_json)
salaries[name] = salary
return json.dumps(salaries)
salaries = '{"Alfred" : 300, "J... |
def check(string):
p=set(string)
s={'0','1'}
if s==p or p=={'0'} or p=={'1'}:
print("It is a valid string")
else:
print("please enter again a valid binary string")
if __name__ == "_main_" :
string=input("please enter a valid binary string\n")
check(string)
substr... |
import sys
def check_digit(x, dig):
while x > 0:
if x % 10 == dig:
return True
x = x // 10
return False
def find_nums(upper, lower, cur_num, nums, dec):
if dec == 0:
nums.append(cur_num)
return
for i in range(1,10):
if check_digit(cur_num,i) == Fals... |
import sys
name = str( sys.stdin.readline() ).strip()
new_name = ''
cur_char = ''
for ch in name:
if cur_char == ch:
continue
else:
new_name = new_name + ch
cur_char = ch
print(new_name) |
import sys
def create_binary(x):
bin = []
cur_dig = 2**29
while cur_dig > 0:
if x >= cur_dig:
bin.append(1)
x = x - cur_dig
else:
if len(bin) > 0:
bin.append(0)
cur_dig = cur_dig // 2
return bin
def binary_to_nu... |
import sys
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)
limit = int(sys.stdin.readline())
nums = []
for i in sys.stdin:
nums.append(int(i))
if len(nums) == limit:
break
for n in nums:
print( factorial(n) % 10)
|
import is_odd
def is_even(number):
return not (is_odd.is_odd(number)) |
'''
Leetcode- 135. Candy - https://leetcode.com/problems/candy/
time complexity - O(N)
space complexity - O(N)
Approach - first we assign each child one candy each
2) Then we compare left neighbour, if it is greater then then we add 1 candy else it remains the same
3) Sameway we do compare the right... |
import sys
pre_order_traversal_list = []
post_order_traversal_list = []
in_order_traversal_list = []
bfs_traversal_list = []
class Node:
def __init__(self, n):
self.value = n
self.left = None
self.right = None
def insert(self, n):
if n < self.value:
if self.left:... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
if not self.head:
self.head = Node(data)
return
cur = self.head
while cur.next:
cur = cur.next
cur.next = Node(data)
def remove(self, data):... |
n = int(input())
e = int(input())
graph = {}
vis = {}
for i in range(e):
u, v = [int(x) for x in input().split()]
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
graph[v].append(u)
s = int(input())
q = [s]
vis[s] = True
print(graph)
print(q)
pr... |
import socket
import sys
def main():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
except socket.error as e:
print("The connection has failed!")
print("Error: {}" .format(e))
sys.exit()
print("Socket successfully created")
target_host = input("Type the ... |
phrase = "The right format"
i = len(phrase)
while i < 42:
print ("-", end='')
i += 1
print (phrase)
|
class GotCharacter:
"""A class representing the GOT character with their name and if they are alive or not
"""
def __init__(self, first_name, is_alive=True):
try:
if not first_name:
self.first_name = None
elif isinstance(first_name, str):
self.... |
num=input("Enter an odd length number:")
length=len(num)
for i in range(length):
for j in range(length):
if i==j or i+j==length-1:
print(num[i],end=" ")
else:
print(" ",end=" ")
print() |
n=int(input("Enter the number of rows:"))
for row in range(n):
val=row+1
dec=n-1
for col in range(row+1):
print(val,end=" ")
val=val+dec
dec=dec-1
print() |
print("This program computes the volume and the area of the side surface of the Rectangular parallelepiped")
a, b, c = input("Enter the length of 3 sides").split()
a = int(a)
b = int(b)
c = int(c)
print("The volume is ", a * b * c)
print("The area of the side surface is ", 2 * c * (a + b))
|
import gym
import numpy as np
from abc import ABC
from gym import spaces
from typing import Tuple
from copy import deepcopy
from collections import namedtuple
Ship = namedtuple('Ship', ['min_x', 'max_x', 'min_y', 'max_y'])
Action = namedtuple('Action', ['x', 'y'])
class BattleshipEnv(gym.Env, ABC):
def __init... |
print('What is your name?')
name = input()
print('Hello, ' + name + '.')
|
age = 20
if age >= 18 and age <21:
print('At least you can vote')
print('Poker will have to wait')
if age >= 18:
print('You can vote.')
if age >= 21:
print('You can play poker.')
|
shopping = ["bread","milk","eggs"]
print(shopping)
for item in shopping:
print(item)
mixed = [365,"days",True]
print(mixed)
|
import math
class DocDistance(object):
def __init__(self):
self.file_1 = "../txtFile/javawikipage.txt"
self.file_2="../txtFile/pythonwikipage.txt"
def read_file(self,filename):
try:
file=open(filename)
return file.readlines()
except Exception as e:
print(e)
def word_split_file(self,records):
wor... |
import sys
class HeapSort(object):
"""核心思想:
堆定义:
可以看做完全二叉树,除最后一层外,其它层都是满的,而且左子树一定比右子树先填满
构建堆
维持堆的特性,以最大堆来讲,左右子节点都要比父节点要小,所以先找到当前节点的子节点最大的下标,如果当前节点不是最大的,则交换
,对交换过的节点再次循环以防堆结构被破坏【被替换节点数】
"""
def __init__(self, toSortFile):
super(HeapSort, self).__init__()
self.tsf = toSortFile
def loadData(self,fileName)... |
from graphics import *
import pygame
import random
import time
import os
def drawAll(shapes):
for shape in shapes:
shape.draw(win)
def undrawAll(shapes):
for shape in shapes:
shape.undraw()
def colorAll(shapes, color):
for shape in shapes:
shape.setFill(color)
def out... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from stock_predictor import StockPredictor
TRAIN_SET_PERCENT = 0.8
X_LABEL = 'Time in days'
Y_LABEL = 'Close price of stock'
def load_file(file_name, columns):
file_data = pd.read_csv(file_name,
... |
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
""... |
class Node:
def __init__(self, id):
self.parent = id
self.rank = 0
class UnionFind:
def __init__(self, size):
self.nodes = list()
for i in range(0, size):
self.nodes.append(Node(i))
def find(self, x):
if self.nodes[x].parent != x: ... |
import math
if __name__ == "__main__":
from matplotlib import pyplot, rc
rc('font', size=12)
def wind_speeds(p, y_min, y_max, rho, f, N=10):
"""Calculates the geostrophic wind speeds between altitudes $y_min and $y_max.
Calculation of the pressure gradient uses finite differences, 4th order.
:pa... |
import sys
class Operation_on_file:
def __init__(self):
pass
def LoadFile(self,plik):
row = []
try:
with open(plik, "r") as f:
row = f.readlines()
except FileNotFoundError:
print(f"Brak pliku {plik}")
return row
def Main(... |
for i in range(10):
print(12 * i) |
import time
from math import sqrt, ceil, floor
def floor_number(f, r):
if f == 1:
return r * (r + 1) // 2
k = f - 2
if f % 2 == 0:
k += 1
n = r // 2
if r % 2 == 1:
n += 1
init = f * f // 2
return (2 * n + 2 * k + 1) * (n - 1) + init
else:... |
month = int(input("Enter a month (MM): "))
if (month > 12) or (month < 0):
print ("Months can only be from 01 to 12.")
day = int(input("Enter a day (DD): "))
if (month % 2 == 0) and (day > 30) or (day < 0):
print("Incorrect amount of days for that month.")
if (month % 2 != 0) and (day > 31) or (day < 0):
... |
class Person:
def __init__(self, name):
self.name = name
self.__life_value = 100
def got_shot(self):
print('中槍 -50HP')
self.__life_value -= 50
def show_status(self):
print('HP : %s' % self.__life_value)
def __shot(self):
print('%s 開槍' % self.name)
... |
import unittest
def calculate_temp(**kwargs):
pass
class TestMethods(unittest.TestCase):
def test_add_1(self):
result = calculate_temp(temp=100, original='C', to='F')
self.assertEquals(result,212)
def test_add_2(self):
result = calculate_temp(temp=212, original='F', to='C')
... |
class Array:
def __init__(self, size):
self.stack = [ None for _ in range(size)]
class Stack:
def __init__(self, size):
self.stack = Array(size).stack
self.top = -1
def is_empty(self):
return self.top == -1
def push(self, element):
self.stack[self... |
list = []
a = 8
b = 9
print(a*b)
print("8*9") |
def AddZeros(x, n, left=True):
"""
x is a string
n is number of zeros to be added
left true meaning leading zeros, false meaning lagging zeroes
"""
if left:
return str(0) * n + x
else:
return x + str(0) * n
def KaratsubaMultiplier(x, y):
x = str(x)
y = str(y)
... |
from random import shuffle
spade = "\u2660"
heart = "\u2665"
diamond = "\u2666"
club = "\u2663"
class Dealer(object):
def __init__(self, arg):
self.arg = arg
class Player(object):
def __init__(self, arg):
self.arg = arg
def hit():
pass
def stand():
pass
class Card... |
import requests
url = input("Enter the URL: ")
wordlist = input("Enter the path to the wordlist: ")
with open(wordlist) as f:
for line in f:
directory = line.strip()
full_url = url + "/" + directory
r = requests.get(full_url)
if r.status_code == 200:
print("[+] Director... |
import random
char ="qwertyuiopasdfghjklmnbvcxz1234567890"
no_pass =input("enter no of passwords you need")
digit =input("enter no of digits :")
no_pass =int(no_pass)
digit = int(digit)
for p in range(no_pass):
password = ''
for c in range(digit):
password += random.choice(char)
print(pass... |
import numpy as np
import matplotlib.pyplot as plt
from math import factorial
M = 10
ave = 0.3
def comb(n, r):
return factorial(n) / factorial(r) / factorial(n - r)
def binomial(x):
return comb(M, x)*(pow(ave, x))*(pow(1-ave, M-x))
x = range(0,10,1)
x = np.array(x)
plt.plot(x, binomial(x))
plt.show()
|
import re
import itertools
def selectSentence():
engSentence = raw_input('Enter the name of English sentence file : ')
hindiSentence = raw_input('Enter the name of Hindi sentence file : ')
word = raw_input('Enter the word whose sentences you want : ')
f_e = open(engSentence , 'r'... |
import numpy as np
print("Hello world")
def circumference(radius):
'''calculating the circumference of a circle
'''
return 2*np.pi*radius
def surface(radius):
'''This fucntion calculates the surface of the circle
: param float radius : radius of the given circle
'''
return np.pi*radius**2
def... |
def editDictionary(dictionary, currentKey, nextKey, keyToAdd):
if (dictionary[nextKey] != None):
dictionary[keyToAdd] = dictionary[currentKey] + dictionary[nextKey][0]
else:
dictionary[keyToAdd] = dictionary[currentKey] + dictionary[nextKey][0]
return dictionary |
""" Assignment 2, Exercise 1, INF1340, Fall, 2015. Pig Latin
This module converts English words to Pig Latin words
"""
__author__ = 'Sinisa Savic', 'Marcos Armstrong', 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
def pig_latinify(word):
"""
Thi... |
"""Numeric operators practice."""
__author__ = "730336784"
number_one: int = int(input("Pick a number "))
number_two: int = int(input("Pick another number "))
number_one_to_the_power_of_number_two: int = number_one ** number_two
number_one_divided_by_number_two: float = number_one / number_two
number_one_int_divide... |
"""Demonstrations of dictonary capabilities."""
schools: dict[str, int]
schools = dict()
schools["UNC"] = 19400
schools["Duke"] = 6717
schools["NCSU"] = 26150
print(schools)
print(f"UNC has {schools['UNC']} students.")
schools.pop("Duke")
is_duke_present: bool = "Duke" in schools
print(f"Duke is present... |
"""List utility functions."""
__author__ = "730336784"
def all(x: list[int], y: int) -> bool:
if len(x) == 0:
return False
i: int = 0
while i < len(x):
if x[i] != y:
return False
i = i + 1
return True
def is_equal(a: list, b: list) -> bool:
i:... |
"""mylist.append(1)
mylist.append(2)
mylist.append(3)
for x in mylist:
print x """
mylist=[1,2,3]
print(mylist[10])
|
import os
path = os.getcwd()
filenames = os.listdir(path)
count = 0
for filename in filenames:
filename_array = filename.split('-')
if len(filename_array) > 1:
new_filename = filename_array[0]
os.rename(filename, new_filename)
count = count + 1
print("%s files have been renamed" % ... |
import sys
import tkinter
import tkinter.messagebox
a = input("Enter username : \n")
b = input("Enter Password : \n")
if a!="pranesh67" or b!="Pass@123":
tkinter.messagebox.showwarning("Login Page","The username or Password is incorrect");
sys.exit(0)
else:
print("### write the whole program here w... |
def convert(value):
cent = round(value * 100)
coin = 0
while True:
if cent == 0:
break
elif cent >= 25:
cent -= 25
coin += 1
elif cent >= 10:
cent -= 10
coin += 1
elif cent >= 5:
cent -= 5
coi... |
"""Harsha vardhan reddy
121910313001"""
def dynamic_input():
print("enter the elements:")
for i in range(n):
a=int(input())
ar.append(a)
return ar
def binary_search(s):
if(ar[mid]==s):
print("ele is found in",mid)
for i in range(low,mid-1):
if(ar[i]==... |
n=int(input())
ar=[]
print("enter the elements:")
for i in range(n):
a=int(input())
ar.append(a)
s=int(input("enter an ele to search:"))
l=len(ar)
for i in range(l):
if(ar[i]==s):
print("ele found in",i)
|
n=int(input("enter the number:"))
count=0
dup=n
while dup>0:
r=dup%10
count+=r**3
dup//=10
if(n==count):
print("amstrong num")
else:
print("not an amstrong num")
|
"""Harsha vardhan reddy
121910313001"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def append(self,data):
if self.tail is None:
self.head=Nod... |
"""Harsha vardhan reddy
121910313001"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
def listprint(self):
printv = self.head
while printv:
print (printv.... |
import numpy as np
import math
def manhattan(x, y):
"""Manhattan distance."""
return abs(x[0] - y[0]) + abs(x[1] - y[1])
def _neighbourhood_1d(winner, n_nodes, neighbourhood_size, circular):
"""Get neighbourhood, represented as indexes, of a node. The node itself is included. 1D version."""
idx_min,... |
L1 = ['a', 'b', 'c']
L2 = ['b', 'd']
print("For finding common elements")
for val in L1:
if val in L2:
print(val)
print("\n For non-common elements")
L3 = L1 + L2
for elem in L3:
if (elem not in L1) or (elem not in L2):
print(elem) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.