blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c5cde9f453531733d7d0f3d6b80172577a662ed1 | JayTwitty/pig_latin | /reverse_pig_latin.py | 133 | 3.796875 | 4 |
sentence = input("What is the pig latin sentence that you want translated to English?")
sentence = sentence.split()
print(sentence) |
1fe9d7bdf16f7880a6998f6d1ae7205ecdaecaf6 | YeTong-Cloud/MLStudy | /matplotlibTest/drawLine.py | 2,546 | 4.0625 | 4 | """
=======================================
A simple plot with a custom dashed line
=======================================
A Line object's ``set_dashes`` method allows you to specify dashes with
a series of on/off lengths (in points).
"""
import numpy as np
import matplotlib.pyplot as plt
class drawLineClass:
# ... |
fe819de9021c08c0176c8cdab49ee0765c1ba2b1 | HarryMWinters/coding-katas | /code-wars/snail/solution.py | 978 | 3.734375 | 4 | def snail(snail_map):
"""
Create a 1-D array of ints constructed from a snail traversal of the input array.
Args:
snail_map: An array of equal length integer arrays.
Returns:
A 1-D array of integers.
"""
outputArr = []
while snail_map:
outputArr.extend(snail_map[0])
... |
95c2f14fd3b94211761d8b2770b41ad6c4c320ef | HarryMWinters/coding-katas | /hacker-rank/cavity-map/cavityMap.py | 1,935 | 3.859375 | 4 | def cavityMap(grid):
"""
Generate a list of of string with 'cavities' replaced by the the uppercase letter X.
See README for fuller description of cavity.
Args:
grid: A list of strings.
Returns:
A list of strings of with the same dimensions as grid.
Raises:
TypeError:
... |
a7b0d12de35acf4a6a55f6064913db2c3d0d5f61 | HarryMWinters/coding-katas | /hacker-rank/flipping-bits/solution.py | 434 | 4.0625 | 4 | def flippingBits(base10Number):
"""
The result of converting to base 2, flipping all the bits,
and converting back into base 10.
Args:
base10Number: An integer.
Returns:
An integer.
"""
binary = "{0:b}".format(base10Number)
binZero = "0" * 32
binary = binZero[:-len(b... |
1951e7c53edc5ee6d710ef96d5fb9c147bd6003a | HarryMWinters/coding-katas | /hacker-rank/crush/solution.py | 831 | 4.03125 | 4 | def arrayManipulation(n, queries):
"""
The maximum value of an element in an array of length arrLength
after the operations in queries have been performed on it.
Complexity:
O(arrLength * len(queries)
Args:
arrLength: Non negative integer denoting length of array.
queries: A... |
5c080df2641747eb5a1c8d313ed62d5194d2f3ae | bobbyocean/draggable_convex_hull | /polynomials.py | 4,020 | 3.609375 | 4 | """
Robert D. Bates, PhD
Polynomial Class
After writing x=Poly([0,1]), x can now be used to make polynomails. Like,
f = (x-1)+x**6
Has many attached functions like, f.roots(), f.derivative(),
f.convex_hull(), etc.
"""
import numpy as np
from itertools import zip_longest
def prod(iterable,start=1):
for i in i... |
09a05fdb4236cebffaa44ae9b71b734e6b0d82b2 | SMinTexas/multiply_a_list | /mult_list.py | 349 | 4.1875 | 4 | # Given a list of numbers, and a single factor (also a number), create a
# new list consisting of each of the numbers in the first list multiplied by
# the factor. Print this list.
mult_factor = 2
numbers = [2,4,6,8,10]
new_numbers = []
for number in numbers:
product = number * mult_factor
new_numbers.append... |
c92a186d6388c6f06f5f88d97ee4e1c4cb05f395 | hingu-parth/Data_Structures-Python | /Binary Search Tree/1038. Binary Search Tree to Greater Sum Tree.py | 513 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
def new(root,sumv):
if not root:
... |
8536d794b6f66bbbb364f4f58a7fe438784e0a63 | rampage-1/networking-tools | /echoserver.py | 1,104 | 3.5625 | 4 | #!/usr/bin/env python3
# ^ use user environment python3, more reliable than? /bin/python3
# for https://realpython.com/python-sockets/
# not an original work
# creates a socket object, binds it to interface:PORT, listens, accepts connection, echos back data recvd
import socket
HOST = '127.0.0.1' # loopback address f... |
4c7ff99357954ba73987f833eff1cb4daf07feb8 | mrayapro/python_samples | /example_7_math_comparisons.py | 224 | 3.953125 | 4 | x = 5
print(x == 5)
print({x == 5} is {x == 5})
print(x == -5 is {x == -5})
print(x > 4 is {x > 4})
print(x > 5 is {x > 5})
print(x >= 5 is {x >= 5})
print(x < 6 is {x < 6})
print(x < 5 is {x < 5})
print(x <= 5 is {x < 5})
|
20f796f850f1147150061ca20e0c250569a31fd0 | mrayapro/python_samples | /Mani_example20.py | 128 | 3.734375 | 4 | my_list = ['3', '8', '1', '6', '0', '8', '4']
mystring='abc'
new_list=[s + mystring for s in my_list]
print(new_list)
|
1fe280eafbf7f4ca37046d98d4cf1d1ae08472ed | PrzemyslawMisiura/Deck_of_cards | /Deck_of_cards.py | 2,953 | 3.90625 | 4 | # Specifications
# Card:
# Each instance of Card should have a suit ("Hearts", "Diamonds", "Clubs", or "Spades").
# Each instance of Card should have a value ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K").
# Card's __repr__ method should return the card's value and suit (e.g. "A
# of Clubs", "J of ... |
d1779c189502386d65bee77b44494954dd6fa554 | Emranul-Haque-Rakib/Natural-Language-Processing | /BagOfWordsModel.py | 2,451 | 3.53125 | 4 | import nltk
import re
import heapq
paragraph="""A sub-committee of the AL is now working in full swing to complete a draft of the manifesto following directives of party chief and Prime Minister Sheikh Hasina, according to two of its senior leaders.
The BNP also has assigned a group of experts to draft its manifesto t... |
998d78d1840298c6f662f688949dd118c6e26d83 | dylan157/TresureHunt | /Tresurehunt.py | 28,458 | 3.6875 | 4 | #!/usr/bin/env python
#Welcome to my version of AQA Tresure Hunt. By Dylan Spriddle. Started 26/09/2016
#You start the game on the menu where you have a choice between playing ('1') or options('2')
#The options allows you to change icons, map size, icon x_y_width (player icon size). Ps. have a look at GameBot :D
... |
fc77fd275354dad7a87ead984532b4d68e5ce5b3 | ayesha-omarali/PracticeProblems | /lengthoflastword.py | 560 | 3.796875 | 4 | def lengthoflastword(A):
if A == '':
return 0
A = A[::-1]
word = ''
flag = True
if A[0] == ' ':
count = 0
for i in A:
if i != ' ':
word += i
flag = False
elif i == ' ' and not flag:
break
A = word... |
44332b97b6ab0d930b440bbd891bb1035382a734 | qiaolunzhang/py_scrapy | /writing_solid_python_code/advice35.py | 947 | 3.78125 | 4 | class A(object):
def instance_method(self, x):
print("calling instance method instance_method(%s, %s)"%(self, x))
@classmethod
def class_method(cls, x):
print("calling class_method(%s, %s)" % (cls, x))
@staticmethod
def static_method(x):
print("calling static_method(%s)" % ... |
95f534ef40d46a4bc35e4e201f245ee98c54556f | Softypo/StockMarket_ADV | /stock_adv_Functions.py | 12,531 | 3.5 | 4 |
# importing modules
import numpy as np
import pandas as pd
###ETL reddit data
#----------------------------------------------------------------------------------------------------------------------------------------
def pq (names, subredits='allstocks', sort='relevance', date='all', comments=False):
#importing r... |
92d120cd666c5ba7d4e49369715b17150973e05b | RyanLongRoad/classes | /farm/Field/field_class.py | 7,446 | 3.5625 | 4 | from potato_class import *
from wheat_class import *
from sheep_class import *
from cow_class import *
import random
class Field():
"""Simulate a field that can contain animals and crops"""
#constructor
def __init__(self,max_animals,max_crops):
self._crops = []
self._animals = ... |
7ab0803b372232161f2a5f3b1f165ce9890b5bbd | Ashik-Phantom/OpenCV-Python-Basics | /9.1-Face_detection.py | 563 | 3.546875 | 4 | # Face detection - Only detects the face not the person
import cv2
facecascade = cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml") # Pre trained face model
Img = cv2.imread('Resources/my_pic1.jpeg')
img = cv2.resize(Img,(600,600))
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces
fac... |
40d01cedf0c714e191ae59d898e87d237ab8849f | droftware/Knight-Rescue | /KnightRescue/player.py | 4,035 | 3.578125 | 4 | import pygame
import constants
import person
import landforms
import ladder
import fireball
import sys
import donkey
import cage
class Player(person.Person):
""" Defines the player object.It inherits from Person class."""
def __init__(self):
"""Constructor for Player class."""
super(Player,self).__init__(0,... |
8a1bab3272fd58fe4999fe571fa7eb58f1cac9e4 | Souravvk18/Python-Project | /dice_roll.py | 1,204 | 5 | 5 | '''
The Dice Roll Simulation can be done by
choosing a random integer between 1 and 6 for which we can use the random module in the Python programming language.
The smallest value of a dice roll is 1 and the largest is 6, this logic can be used to simulate a dice roll.
This gives us the start and end values to use i... |
b836b5f8ee930033348291d83be460e57ef5fd0d | Souravvk18/Python-Project | /text_based.py | 861 | 4.34375 | 4 | '''
you will learn how to create a very basic text-based game with Python.
Here I will show you the basic idea of how you can create this game and then you can modify or
increase the size of this game with more situations and user inputs to suit you.
'''
name = str(input("Enter Your Name: "))
print(f"{name} you are... |
8817f472e24034a7157bd400da6f7ee26eb5cc69 | HoNedAy/lemon_erp | /qcd/lession.py | 5,813 | 4.1875 | 4 | # 名字命名规则
# (1)只能包含数字、字母、下划线
# (2)不能以数字开头
# (3)不能使用关键字
# 可以通过import keyword
# print(keyword.kwlist)打印关键字
# ctrl+/也可以多行注释
# import keyword
# print("打印到控制台")
# print(type(12))
# print(type(3.14))
# print(isinstance(12,int))
# print("刚刚'你好呀'下雨啦")
# print("刚刚\"人名\"下雨啦")
# print("""
# 今天下雨了没
# 今天没下雨
# ... |
df58a62863d9eede2e9dba8466d4530364b60ffc | 0x000552/python | /coursera/diving_in_python/study_process.py | 3,100 | 3.59375 | 4 | """
os.fork
"""
"""
import os
pid = os.fork()
if pid == 0:
print(f"MAIN pid: {pid}")
else:
print(f"CHILD pid: {pid}")
"""
"""
multiprocessing
"""
from multiprocessing import Process
def f(_str):
print(f"amazing process! _str = {_str}")
prcs1 = Process(target=f, kwargs={"_str": "WOW"})
prcs1.start() #... |
d8a388914e511f6697eeb9cbb91f6099d086a025 | mrgold92/Python_Complete | /01-Conceptos-Básicos/01.04-Trabajando-con-Fechas.py | 1,445 | 3.96875 | 4 | #####################################################################
# Trabajando con fechas #
#####################################################################
# #
# Sintaxis: datetime.now() ... |
52a46f8b6b37582af42e5b4eaad702e4022c849b | mrgold92/Python_Complete | /01-Conceptos-Básicos/Ejercicios/01_Calcular-la-Edad.py | 355 | 3.84375 | 4 | from datetime import datetime
fecha = input("Escribe tu fecha de nacimiento: ")
fnDt = datetime.strptime(fecha, "%d-%m-%Y").date()
hoyDt = datetime.now().date()
edad = hoyDt.year - fnDt.year
if(edad >= 18):
print(f"Tienes {edad} años, eres mayor de edad.")
else:
años = 18 - edad
print(f"Te faltan {años} ... |
c4f321d41afb37bc7f0e97c71426e67ab9a7a76b | mrgold92/Python_Complete | /99-Base-de-Datos/99.05-SQLite.py | 1,773 | 3.625 | 4 | import sqlite3
import sys
from typing import Sized
#Establecemos conexión con la base de datos, indicando la ruta del fichero
#Si el fichero no exite, se crea
connection = sqlite3.connect('.\\Ficheros\\demo.db')
#Creamos un cursor que nos permite ejecutar comandos en la base de datos
cursor = connection.cursor()
#En... |
21c438ce49cd3cb187e43b05a74daae410d7db9d | lutingying/lutingying | /HW4.py | 5,613 | 3.921875 | 4 | #HW #4
#Due Date: 07/27/2018, 11:59PM EST
#Name:
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__ = __str__
class Stack:
# ------- Copy ... |
6d9e4b5517e4777ccbca6cb1df0f83b7aae20377 | lian88jian/py_everything_exercise | /src/pack_2016_10_17_hundred_example/10/14.py | 328 | 3.828125 | 4 |
#分解质因数
num = 90;
primeArr = [];
i = 2;
while i <= num:
if num % i == 0:
primeArr.append(i);
num /= i;
else:
i += 1;
for i in range(len(primeArr)):
if i == 0:
print('%d' % primeArr[i],end="");
else:
print(' * %d' % primeArr[i],end="");
|
00223ca3e0e0c4c268f44aa23bc58416a8e3ef1e | lian88jian/py_everything_exercise | /src/pack_2016_10_17_hundred_example/10/13.py | 185 | 3.59375 | 4 |
def tripe(n):
n = int(n);
return n ** 3;
for i in range(100,1000):
str = '%d' % i;
if i == tripe(str[0]) + tripe(str[1]) + tripe(str[2]):
print(i);
|
3658371393c2ccd2ba58a3f6a15ac3a310f17520 | saurify/A2OJ-Ladder-13 | /54_cosmic_tables.py | 1,289 | 3.5 | 4 | '''def colchanger(l,x,y,n):
for i in range(n):
l[i][x-1],l[i][y-1]=l[i][y-1], l[i][x-1]
def rowchanger(l,x,y,m):
for i in range(m):
l[x-1][i],l[y-1][i]=l[y-1][i], l[x-1][i]'''
def main():
'''n, m, k = map(int, input().split())
R = {str(i): i - 1 for i in range(n+1)}
C = {str(i): i - 1 for i in range(m+1)}
a... |
8fba0b74dc2c82cc0adcd0d6f81cc0031131f65c | saurify/A2OJ-Ladder-13 | /37_bank.py | 198 | 3.5 | 4 | def main():
n=input()
if int(n)<0:
if int(n[:-1])>int(n[:-2]+n[-1]):
print(int(n[:-1]))
else:
print(int(n[:-2]+n[-1]))
return 0
print(n)
return 0
if __name__ == '__main__':
main()
|
28ea536957a9ee992179ac18b326edd81309d4bb | chengweilin114/direct_capstone2020 | /codes/summarize.py | 5,467 | 3.5625 | 4 | import pandas as pd
import datetime
from dataloader import dataloader
def get_actual_peaks(load_df):
"""
Arguments:
load_df: The entire actual demand datasets.
Return:
peaks_df: Keep the highest demand for each day.
This function keeps the highest demand (the peak hour)
for each... |
a2c2794cf054e57d43a3f3c4da884f39921d07c1 | idkrepp12/python-projects | /jeff.py | 221 | 3.921875 | 4 | import random
print("Hi")
while True:
print("ask me your question...")
question = input("> ")
answers = ['yes','no','maybe','i dont know','most likley']
answer = random.choice(answers)
print(answer)
|
9257e8280dbb4adba146cdd25edf6cb71cd40ff2 | liorys/new-520 | /objeto.py | 1,818 | 3.734375 | 4 | #!/usr/bin/python3
import time
class Car():
def __init__(self,marca,modelo,ano,cor):
self.marca = marca
self.modelo = modelo
self.ano = ano
self.cor = cor
self.velocidade = 0
self.combustivel = 'gasolina'
def acelerar(self):
self.velocidade += 10
... |
abbf9c92a6558f4cce385ce98b1de1d8a54e31da | liorys/new-520 | /frutas-list-def.py | 1,347 | 4.03125 | 4 | #!/usr/bin/python3
from pprint import pprint
frutas = [
{'nome':'pera','preco':1.0,'qtd':10},
{'nome':'uva','preco':2.0,'qtd':20},
{'nome':'abacaxi','preco':3.0,'qtd':30},
{'nome': 'morango', 'preco':4.0, 'qtd': 40},
{'nome': 'kiwi', 'preco': 5.0, 'qtd':50},
]
def buscaf... |
3b9c5b1aa16c865e84fc039d280fa85b0cf2a55a | csrm/python_basics | /temporary_list_sort.py | 349 | 4.03125 | 4 | #List of no.s
numbers = [156, 23, 1, 97, 100, 45, 7, 90 ]
#Print the list
print('Original List:',numbers)
#Print the list
print('Temporarily sorted the list in Ascending Order:',sorted(numbers))
#Print the list
print('Temporarily Sorted List in Descending Order:',sorted(numbers, reverse = True))
#Print the list
print(f... |
b6b0f2782322be0e0945ea3febb734f3b03d7eaa | csrm/python_basics | /pop_from_list.py | 297 | 3.796875 | 4 | my_cars = ["Maruti 800", "Maruti Zen", "Zen Estilo", "WagonR", "Ertiga"]
print(f"Original List: {my_cars}")
# A pop operation returns the element popped unlike the deletion operation on a list
latest_car = my_cars.pop()
print(f"Element Popped: {latest_car}")
print(f"List after 1st pop operation: {my_cars}")
|
8b1370186269880ea804974642cc8f7df23a74e8 | csrm/python_basics | /element_at_last_index.py | 214 | 4.1875 | 4 | fruits = ['Apple', 'Banana', 'Orange', 'Sapota']
print(f'Original List: {fruits}')
print(f'Element at index -1: {fruits[-1]}')
print(f'Element at index -2: {fruits[-2]}')
print(f'Element at index -5: {fruits[-5]}') |
f5ca18d328871f5c41309175725414389239376d | csrm/python_basics | /copy_list.py | 664 | 4.15625 | 4 | #Define a list of food items
regular_food = ['Annam', 'Pappu', 'Kura', 'Pacchadi', 'Charu', 'Curd']
#Assign the list regular_food to my_fav_food
my_fav_food = regular_food
#Copy list regular food to mom_fav_food
mom_fav_food = regular_food[:]
print(f'Regular Food : {regular_food}\nMy Favourite Food: {my_fav_food}\nMom... |
fa4ae23af436a4a6ef8a1b06cbcde8e79d9f608d | csrm/python_basics | /keyword_args.py | 390 | 3.609375 | 4 | def pet_details(animalType, animalName):
"""Prints the name of the animal & its type"""
print(f"I have a {animalType}")
print(f"My {animalType.lower()}'s name is {animalName}")
animalType = 'Dog'
animalName = 'Jimmy'
pet_details(animalType = animalType, animalName = animalName)
animalType = 'Tiger'
animalName = '... |
7593d1d720dcdc84cfa8c07c6b97f341b96cb87e | HollyMccoy/InCollege | /Profile.py | 1,401 | 3.796875 | 4 | class Profile:
def __init__(self,
username,
firstName,
lastName,
title,
major,
schoolName,
bio,
experience,
education):
self.experience = []
self.username = username
self.firstName = firstName
s... |
4eb506aafc70283bb2e38cd8fc96dda63600e330 | HollyMccoy/InCollege | /menus/Languages.py | 1,025 | 3.921875 | 4 | # Menu commands for the "Languages" submenu
# Path: Main menu / important links / privacy policy / guest controls / languages
import globals
def ShowMenu():
"""Present the user with a menu of guest control settings."""
while True:
selection = input(
"\n" + "-- Languages --: " + ... |
d0a4ff6900081e99e3ddfa9a9d36c90722460409 | Barbara-Diaz/Calculator | /proyecto.py | 2,769 | 3.78125 | 4 | import tkinter as tk
from tkinter import messagebox
import sys
#################################################
def convertir(dato):
try:
dato=int (dato)
return dato
except ValueError:
try:
dato=float(dato)
return dato
except ValueError:
dat... |
79af9fa8c11bac176eb28de0674851027336dbad | Iernst95/myProjects | /Python-Projects/PetstoreFinalProject/python4401FinalProject.py | 4,471 | 3.84375 | 4 | from Petstore import Cat,Dog,Turtle,Frog,Parrot
from Customer import Person
import pickle
import random
def main():
todays_animals = []
create_inventory(todays_animals)
print("Welcome to our Pet Store!")
print("Every day we have new and exciting animals to buy!\n")
name = input("what is your name?:... |
a4626ca589be214fc375c7c0fe005807cf4f9291 | rosekay/data_structures | /lists.py | 1,232 | 4.34375 | 4 | #list methods applied
list_a = [15, 13.56, 200.0, -34,-1]
list_b = ['a', 'b', 'g',"henry", 7]
def list_max_min(price):
#list comprehension
return [num for num in price if num == min(price) or num == max(price)]
def list_reverse(price):
#reverse the list
price.reverse()
return price
def list_count(price, num)... |
6983b9b8ad8737a418c59ed38256630d3ed7b598 | SbSharK/PYTHON | /PYTHON/whileelse.py | 246 | 4.1875 | 4 | num = int(input("Enter a no.: "))
if num<0:
print("Enter a positive number!")
else:
while num>0:
if num==6:
break
print(num)
num-=1
else:
print("Loop is not terminated with break") |
58692a5a7da1097be3d19ba1edc3faf13458e1e7 | SbSharK/PYTHON | /PYTHON/lec2.py | 589 | 4.09375 | 4 | #!
a=int(input("Enter number 1 "))
b=int(input("Enter number 2 "))
c=int(input("Enter number 3 "))
if a>b and a>c:
print("a is largest, value is ",a)
elif b>c and b>a:
print("b is largest, value is ",b)
elif c>a and c>b:
print("c is largest, value is ",c)
else:
if a==b and a==c:
prin... |
b05f477cbc8438335692cc426d545cf624035b49 | SbSharK/PYTHON | /PYTHON/fileOpen.py | 412 | 3.8125 | 4 | def fileOpen(filename):
fd = open(filename)
data=fd.readline()
count = 0
while data!='':
if(count%2!=0):
print(data)
data=fd.readline()
count+=1
else:
continue
print("\n Number of Lines",count)
fd.close()
if __name__ ... |
d6e485bfd4f23e04505e36d53397e39f81832a53 | Morgan-Sell/connect-four-oop | /play.py | 2,375 | 3.5 | 4 | import numpy as np
from connectfour import Board, Player
import pygame
import sys
game_over = False
no_token = 0
p1_token = 1
p2_token = 2
blue = (0, 0, 255)
column_count = 7
row_count = 6
square_size = 100
#board_width = column_count * square_size
#board_height = row_count * square_size
p1_name = input('Player 1 N... |
0ecddbc90aaf35f0fb28351b096deb152ebd0e44 | tuhiniris/Python-ShortCodes-Applications | /patterns1/hollow inverted right triangle star pattern.py | 374 | 4.1875 | 4 | '''
Pattern
Hollow inverted right triangle star pattern
Enter number of rows: 5
*****
* *
* *
**
*
'''
print('Hollow inverted right triangle star pattern: ')
rows=int(input('Enter number of rows: '))
for i in range(1,rows+1):
for j in range(i,rows+1):
if i==1 or i==j or j==rows:
print('*',end=' '... |
122de28469b09f5f0050d9e6c5001fedeb90b94e | tuhiniris/Python-ShortCodes-Applications | /patterns2/number pattern_triangle_15.py | 348 | 3.953125 | 4 | '''
Pattern
Enter number of rows: 5
1
2 3
4 5 6 7
8 9 1 2 3 4 5 6
7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4
'''
print('Number pattern: ')
counter=1
k=1
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,counter+1):
if k==10:
k=1
print(k,end=' ')
k... |
0215399d8173998139d327bfd73917982e9a4e7a | tuhiniris/Python-ShortCodes-Applications | /array/right rotate an array.py | 797 | 4.3125 | 4 | from array import *
arr=array("i",[])
n=int(input("Enter the length of the array: "))
for i in range(n):
x=int(input(f"Enter the elements into array at position {i}: "))
arr.append(x)
print("Origianl elements of the array: ",end=" ")
for i in range(n):
print(arr[i],end=" ")
print()
#Rotate the given array ... |
a38424508206bc52de7afef6400f0a031773a349 | tuhiniris/Python-ShortCodes-Applications | /class and objects/Use of self parameter and to maintain state of an object.py | 1,198 | 3.90625 | 4 | '''
Description:
------------
When objects are instantiated, the object itself
is passed into the self parameter. The Object is
passed into the self parameter so that the object
can keep hold of its own data.
'''
print(__doc__)
print('-'*25)
class State(object):
def __init__(self):
global x... |
88c8659d9a348812fa58d4e47ef7c7d801f744c7 | tuhiniris/Python-ShortCodes-Applications | /basic program/print all possible combinations from the digits.py | 570 | 3.78125 | 4 | ##Problem Description
##The program takes three distinct numbers and prints all possible combinations from the digits.
while True:
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
c=int(input("Enter the third number: "))
d=[]
d.append(a)
d.append(b)
... |
6a157dd21d9cdff8fbd373649f1a5dead92151ac | tuhiniris/Python-ShortCodes-Applications | /basic program/print the sum of negative numbers, positive even numbers and positive odd numbers in a given list.py | 779 | 4.125 | 4 | n= int(input("Enter the number of elements to be in the list: "))
even=[]
odd=[]
negative=[]
b=[]
for i in range(0,n):
a=int(input("Enter the element: "))
b.append(a)
print("Element in the list are: {}".format(b))
sum_negative = 0
sum_positive_even = 0
sum_positive_odd = 0
for j in b:
if j > 0:
if j%... |
987fdb176bd3aba61e03f288233d20db427e47df | tuhiniris/Python-ShortCodes-Applications | /array/print the number of elements of an array.py | 611 | 4.40625 | 4 | """
In this program, we need to count and print the number of elements present in the array.
Some elements present in the array can be found by calculating the length of the array.
"""
from array import *
arr=array("i",[])
n=int(input("Enter the length of the array: "))
for i in range(n):
x=int(input(f"Enter t... |
d282b4996d72d792df13ba6d25f541a0411a286f | tuhiniris/Python-ShortCodes-Applications | /file handling/Count the Number of Blank Spaces in a Text File.py | 433 | 4.03125 | 4 | '''
Problem Description:
--------------------
The program reads a file and counts
the number of blank spaces in a text file.
'''
print(__doc__)
print('-'*25)
fileName=input('Enter file name: ')
k=0
with open(fileName,'r')as f:
for line in f:
words=line.split()
for i in words:
for letter in i:
... |
4ff69ac15644ff508436eac964f4e3f8be11ea2e | tuhiniris/Python-ShortCodes-Applications | /tuples/convert tuple to string.py | 160 | 3.59375 | 4 | '''
You can use join() method to
convert tuple into string.
'''
test = ("America", "Canada", "Japan", "Italy")
strtest = ' '.join(test)
print(strtest) |
7139cde7a49d54db3883ae161d1acecf942489ed | tuhiniris/Python-ShortCodes-Applications | /list/Reversing a List.py | 1,808 | 5.03125 | 5 | print("-------------METHOD 1------------------")
"""
Using the reversed() built-in function.
In this method, we neither reverse a list in-place
(modify the original list), nor we create any copy of the list.
Instead, we get a reverse iterator which we use to cycle through the list.
"""
def reverse(list):
retur... |
584171438444fc7001b68698651b725933f58b26 | tuhiniris/Python-ShortCodes-Applications | /patterns2/program to print 0 or 1 square number pattern.py | 390 | 4.1875 | 4 | '''
Pattern
Square number pattern:
Enter number of rows: 5
Enter number of column: 5
11111
11111
11111
11111
11111
'''
print('Square number pattern: ')
number_rows=int(input('Enter number of rows: '))
number_columns=int(input('Enter number of columns:'))
for row in range(1,number_rows+1):
for column in ... |
e06defb7a919a2a12e11189c112c5bb885455813 | tuhiniris/Python-ShortCodes-Applications | /class and objects/Iteration overloading Methods.py | 802 | 4.09375 | 4 | '''
Discription:
-----------
The __iter__ returns the iterator object and is implicitly called
at the start of loops. The __next__ method returns the next value
and is implicitly called at each loop increment. __next__ raises
a StopIteration exception when there are no more value to return,
which is implicit... |
7166cac047616cf383f96c4584f7cf8a756ede9e | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_29.py | 327 | 4.25 | 4 | """
Example:
Enter number: 5
A B C D E
A B C D
A B C
A B
A
"""
print('Alphabet Pattern: ')
number_rows = int(input("Enter number of rows: "))
for row in range(1,number_rows+1):
print(" "*(row-1),end="")
for column in range(1,number_rows+2-row):
print(chr(64+column),end=" ")
... |
fec7edf8eb0203ce4f31868dbea9811946200e53 | tuhiniris/Python-ShortCodes-Applications | /patterns2/rhombus or parallelogram star pattern.py | 824 | 4.0625 | 4 | '''
Pattern 4
Enter rows: 5
Rhombus star pattern
*****
*****
*****
*****
*****
'''
print('rhombus star pattern:')
rows=int(input('Enter number of rows: '))
for i in range(1,rows+1):
for j in range(0,rows-i):
print(' ',end=" ")
for j in range(1,rows+1):
print('*',end=" ")
print('\n... |
f8327e9e9ed9601eb9570777acb835a08f5a9fed | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_18.py | 450 | 4.0625 | 4 | '''
Pattern:
Enter number of rows: 5
E E E E E E E E E
D D D D D D D
C C C C C
B B B
A
'''
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
print(' '*(row-1),end=' ')
for column in range(1,number_rows+2-row):
prin... |
3f868bcc92790acb85e72e8033d29bde05db17a1 | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_12.py | 302 | 4.15625 | 4 | '''
Alphabet Pattern:
Enter number of rows: 5
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
'''
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,number_rows+1):
print(chr(64+row),end=' ')
print() |
05245453d39856168dbc249ebf5de56d659b338c | tuhiniris/Python-ShortCodes-Applications | /number programs/determine whether a given number is a happy number.py | 1,573 | 4.25 | 4 | """
Happy number:
The happy number can be defined as
a number which will yield 1 when it is replaced by the sum of the square of its digits repeatedly.
If this process results in an endless cycle of numbers containing 4,then the number is called an unhappy number.
For example, 32 is a happy number as the process ... |
091a210b5cc80d42ce28a35b80b7186e808ae101 | tuhiniris/Python-ShortCodes-Applications | /strings/find the frequency of characters.py | 1,095 | 4.3125 | 4 | """
To accomplish this task, we will maintain an array called freq with same size of the length of the string. Freq will be used to maintain the count of each character present in the string. Now, iterate through the string to compare each character with rest of the string. Increment the count of corresponding element... |
70ff4d1d2f196c4baf2231e6dfc54430db72249b | tuhiniris/Python-ShortCodes-Applications | /patterns1/number pattern_1.py | 512 | 3.953125 | 4 | '''
Pattern
Enter number of rows: 5
Enter number of column: 5
12345
21234
32123
43212
54321
'''
print('Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(row,1,-1):
if column < 10:
print(' ',end='')
print(column,end=' ')
else:... |
a92e1513deea941b6d84b8c6bfdac8a5accb8715 | tuhiniris/Python-ShortCodes-Applications | /tuples/Access Tuple Item.py | 367 | 4.21875 | 4 | '''
To access tuple item need to refer it by it's the index number,
inside square brackets:
'''
a=[]
n=int(input('Enter size of tuple: '))
for i in range(n):
data=input('Enter elements of tuple: ')
a.append(data)
tuple_a=tuple(a)
print(f'Tuple elements: {tuple_a}')
for i in range(n):
print(f'\nElement... |
f3ff7b22352de6864f57eb3c9b52e4643215de8c | tuhiniris/Python-ShortCodes-Applications | /file handling/Read a File and Capitalize the First Letter of Every Word in the File.py | 346 | 4.28125 | 4 | '''
Problem Description:
-------------------
The program reads a file and capitalizes
the first letter of every word in the file.
'''
print(__doc__,end="")
print('-'*25)
fileName=input('Enter file name: ')
print('-'*35)
print(f'Contents of the file are : ')
with open(fileName,'r') as f:
for line in f:
... |
edf144c53cc3cb95eb5a10cbdb08c8a7fc249868 | tuhiniris/Python-ShortCodes-Applications | /patterns1/mirrored rhombus or parallelogram star.py | 895 | 4.21875 | 4 | '''
Pattern 6
Mirrored rhombus star
Enter number of rows: 5
*****
*****
*****
*****
*****
'''
print('Mirrored rhombus star pattern:')
rows=int(input('Enter number of rows: '))
for i in range(1,rows+1):
for j in range(1, i):
print(' ',end=' ')
for j in range(1,rows+1):
print('*',end=' ')
... |
767c3c3577e16a4bf9ee546663c701a7be1954fb | tuhiniris/Python-ShortCodes-Applications | /patterns2/print chessboard number pattern with 1 and 0.py | 567 | 3.953125 | 4 | '''
Pattern
print chessboard number pattern with 1 and 0
Enter number of rows: 5
Enter number of columns: 5
10101
01010
10101
01010
10101
'''
print('print chessboard number pattern with 1 and 0 (Just use odd numbers for input):')
number_rows=int(input('Enter number of rows: '))
number_columns=int(input('En... |
3fc0f4902507d2fab0a8d3b597ab87dd24981a13 | tuhiniris/Python-ShortCodes-Applications | /list/Find the Union of two Lists.py | 1,136 | 4.4375 | 4 | """
Problem Description
The program takes two lists and finds the unions of the two lists.
Problem Solution
1. Define a function which accepts two lists and returns the union of them.
2. Declare two empty lists and initialise to an empty list.
3. Consider a for loop to accept values for two lists.
4. Take the nu... |
5bffa97dee1d35e4f0901c7fa8ca8bb4b7d59d9e | tuhiniris/Python-ShortCodes-Applications | /basic program/test Collatz Conjecture for a Given Number.py | 897 | 4.5625 | 5 | # a Python program to test Collatz conjecture for a given number
"""The Collatz conjecture is a conjecture that a particular sequence always reaches 1.
The sequence is defined as
start with a number n.
The next number in the sequence is n/2 if n is even and 3n + 1 if n is odd.
Problem Solution
1. Create a f... |
d2c1e86b6bd345c54188b982464fdb98a7166a8a | tuhiniris/Python-ShortCodes-Applications | /file handling/Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File.py | 439 | 4.09375 | 4 | '''
Problem Description
The program takes a letter from the user
and counts the number of occurrences of
that letter in a file.
'''
fileName=input('Enter the file Name: ')
character=input('Enter letter to be searched: ')
k=0
with open(fileName,'r') as f:
for line in f:
words=line.split()
for i in wo... |
47d85156bab21b683fd7b8314b2e5e5a4a9872cc | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_3.py | 281 | 4.25 | 4 | """
Example:
Enter the number of rows: 5
A A A A A
B B B B
C C C
D D
E
"""
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,number_rows+2-row):
print(chr(64+row),end=' ')
print() |
b9deb359bb546695348a01125af7428dfef2c537 | tuhiniris/Python-ShortCodes-Applications | /array/demonstrate Searching elements of an array using array module.py | 415 | 4.09375 | 4 | from array import *
n=int(input("Enter the length of the array: "))
arr=array("i",[])
for i in range(n):
x=int(input("Enter the elements: "))
arr.append(x)
print("elements in the array: ",end=" ")
for i in range(n):
print(arr[i],end=" ")
print()
n=int(input("Enter the element which is to be searched for: "... |
c7e2728ee88872cf73915da32fa57b1050df9e2d | tuhiniris/Python-ShortCodes-Applications | /class and objects/Singleton class using Metaclass.py | 1,036 | 4.0625 | 4 | '''
A metaclass is a class used to create a class. Metaclasses are usually sub classes of the type class, which redefines class creation protocol methods in order to customize the class creation call issued at the end of a class statement.'''
print(__doc__)
print('\n'+'-'*35+'Singleton class using MetaClass'+'-'*35)... |
4961def023e1e2fb805239116cd8785ea4b09b74 | tuhiniris/Python-ShortCodes-Applications | /list/Put Even and Odd elements in a List into Two Different Lists.py | 826 | 4.46875 | 4 | """
Problem Description
The program takes a list and puts the even and odd elements in it into two separate lists.
Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if... |
377813d90508ffa5402d90d7a288c078d9fa3786 | tuhiniris/Python-ShortCodes-Applications | /strings/replace the spaces of a string with a specific character.py | 208 | 4.15625 | 4 | string=input('Enter string here: ')
character='_'
#replace space with specific character
string=string.replace(' ',character)
print(f'String after replacing spaces with given character: \" {string} \" ') |
454c5b13b7079f428bd1b04b3a243a9c4c05bdcd | tuhiniris/Python-ShortCodes-Applications | /list/Ways to find length of list.py | 1,584 | 4.46875 | 4 | #naive method
print("----------METHOD 1--------------------------")
list=[]
n=int(input("Enter the size of the list: "))
for i in range(n):
data=int(input("Enter elements of the array: "))
list.append(data)
print(f"elements in the list: {list}",end=" ")
# for i in range(n):
# print(list[i],end=" ")
print()... |
7c9bef892156d20b357d5855820d8b7e79c316af | tuhiniris/Python-ShortCodes-Applications | /dictionary/Check if a Given Key Exists in a Dictionary or Not.py | 731 | 4.21875 | 4 | '''
Problem Description
The program takes a dictionary and checks if a
given key exists in a dictionary or not.
Problem Solution
1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator,
check if... |
b4f2b3c62901c46920d30b2a868c9aab798fcb20 | tuhiniris/Python-ShortCodes-Applications | /patterns1/mirrored right triangle star pattern.py | 297 | 4.09375 | 4 | '''
Pattern 9
Mirrored right triangle star
Enter number of rows: 5
*
**
***
****
*****
'''
print('Mirrored right triangle star pattern:')
rows=int(input('Enter number of rows:'))
for i in range(0,rows):
for j in range(0,rows-i):
print('*',end=' ')
print('\n', end="") |
293e894a12b3f1064a46443f84cbfe4d0b70db6e | tuhiniris/Python-ShortCodes-Applications | /basic program/count set bits in a number.py | 724 | 4.21875 | 4 | """
The program finds the number of ones in the binary representation of a number.
Problem Solution
1. Create a function count_set_bits that takes a number n as argument.
2. The function works by performing bitwise AND of n with n – 1 and storing the result in n until n becomes 0.
3. Performing bitwise AND with n ... |
6d7a32d214efdcef903bd37f2030ea91df771a05 | tuhiniris/Python-ShortCodes-Applications | /number programs/check if a number is an Armstrong number.py | 414 | 4.375 | 4 | #Python Program to check if a number is an Armstrong number..
n = int(input("Enter the number: "))
a = list(map(int,str(n)))
print(f"the value of a in the program {a}")
b = list(map(lambda x:x**3,a))
print(f"the value of b in the program {b} and sum of elements in b is: {sum(b)}")
if sum(b)==n:
print(f"The numb... |
f255734a30161a2f194f998797b100bef4f44396 | tuhiniris/Python-ShortCodes-Applications | /class and objects/Acess private members in Child Class.py | 4,888 | 4.375 | 4 | print('Accessing private members in Class:')
print('-'*35)
class Human():
# Private var
__privateVar = "this is __private variable"
# Constructor method
def __init__(self):
self.className = "Human class constructor"
self.__privateVar = "this is redefined __private variable"... |
5f4083e687b65899f292802a57f3eb9b1b64ca5a | tuhiniris/Python-ShortCodes-Applications | /basic program/program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5.py | 295 | 4.125 | 4 | #program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5
lower = int(input("Enter the lower range: "))
upper = int(input("Enter the upper range: "))
for i in range(lower,upper+1):
if i%7 == 0 and i%5==0:
print(i)
|
7599d879058a9fca9866b3f68d93bcf2bda0001c | tuhiniris/Python-ShortCodes-Applications | /number programs/Swapping of two numbers without temperay variable.py | 1,492 | 4.15625 | 4 | ##Problem Description
##The program takes both the values from the user and swaps them
print("-------------------------------Method 1-----------------------")
a=int(input("Enter the First Number: "))
b=int(input("Enter the Second Number: "))
print("Before swapping First Number is {0} and Second Number is {1}" .f... |
ad835b40d50ac5db87b17903ac17f79c3fc820ef | tuhiniris/Python-ShortCodes-Applications | /matrix/find the transpose of a given matrix.py | 1,212 | 4.6875 | 5 | print('''
Note!
Transpose of a matrix can be found by interchanging rows with the column that is,
rows of the original matrix will become columns of the new matrix.
Similarly, columns in the original matrix will become rows in the new matrix.
If the dimension of the original matrix is 2 × 3 then,
the dimensio... |
ae96cee9c409b9af3ee4f2cca771093eb5fd32cd | tuhiniris/Python-ShortCodes-Applications | /list/Generate Random Numbers from 1 to 20 and Append Them to the List.py | 564 | 4.53125 | 5 | """
Problem Description
The program takes in the number of elements and generates random numbers from 1 to 20 and appends them to the list.
Problem Solution
1. Import the random module into the program.
2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random ... |
36fb60f1f2f02582d5074381a9b2368caed28534 | tuhiniris/Python-ShortCodes-Applications | /patterns1/box number pattern of 1 and 0 with cross center.py | 529 | 3.84375 | 4 | '''
Pattern
box number pattern of 1 and 0 with cross center
Enter number of rows: 5
Enter number of columns: 5
10001
01010
00100
01010
10001
'''
print('box number pattern of 1 and 0 with cross center: ')
number_rows=int(input('Enter number of rows: '))
number_columns=int(input('ENter number of columns: ')... |
dfc74333121a6d5c10de86c9cb3278082c4ed883 | tuhiniris/Python-ShortCodes-Applications | /patterns2/number pattern_triangle_4.py | 349 | 3.953125 | 4 | '''
Pattern
Enter number of rows: 5
1
11
101
1001
11111
'''
print('Number triangle pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,row+1):
if row==1 or row==number_rows or column==1 or column==row:
print('1',end=' ')
else:
... |
63be41d69ba4e4439bc76854fe9ba108209d8c51 | tuhiniris/Python-ShortCodes-Applications | /patterns1/hollow mirrored inverted right triangle star pattern.py | 444 | 4.09375 | 4 | '''
Pattern
Hollow mirrored inverted right triangle star pattern
Enter number of rows: 5
*****
* *
* *
**
*
'''
print('Hollow mirrored inverted right triangle star pattern: ')
rows=int(input('Enter number of rows: '))
for i in range(1,rows+1):
for j in range(1,i):
print(' ',end='')
for j ... |
4730566ea55fb752722cfb9257308de6de3ccc9c | tuhiniris/Python-ShortCodes-Applications | /recursion/Find if a Number is Prime or Not Prime Using Recursion.py | 539 | 4.25 | 4 | '''
Problem Description
-------------------
The program takes a number
and finds if the number is
prime or not using recursion.
'''
print(__doc__,end="")
print('-'*25)
def check(n, div = None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print(f"Numbe... |
c75674ae6650df10f2b3f0a9eda6da53bcedbe39 | tuhiniris/Python-ShortCodes-Applications | /list/Ways to find the sum of element exists in list.py | 1,506 | 4.09375 | 4 | print("---------METHOD 1-------------")
total = 0
list=[]
n=int(input("Enter size of list: "))
for i in range(n):
data=int(input("Enter elements of the list: "))
list.append(data)
print(f"elements of the list: {list}")
#Iterate each element in the list
#add them in variable total
for element in range(n):
... |
e05bdb231fd02fea1c2799737704a407b576e260 | eunhye43/8percent-assignment | /src/utils/id_generator.py | 376 | 3.5 | 4 | import abc
import uuid
class IdGenerator(abc.ABC):
@abc.abstractmethod
def generate(self) -> str:
raise NotImplementedError
class UserIdGenerator(IdGenerator):
def generate(self) -> str:
return "user-" + str(uuid.uuid4())
class AccountNumberGenerator(IdGenerator):
def generate(self... |
a6031788a2a62c5d421337d87556bfd491658805 | Evgenij/Course_on_Python | /Lab_1/task4.py | 1,144 | 3.703125 | 4 | def print_format_text(resText):
print("\n---- Длиннее 7 ----")
for i in resText:
if len(i) >= 7:
print(i)
print("\n---- Длиннее 5, но короче 7 ----")
for i in resText:
if len(i) >= 5 and len(i) < 7:
print(i)
print("\n---- Короче 5 ----")
for i in resText:
if len(i) < 5:
print(i)
text = "Инвест... |
699aea73c33d68fdaee66406e8db7cefe2196a44 | Evgenij/Course_on_Python | /Lab_3/Task5/string_formatter.py | 1,597 | 3.84375 | 4 |
class StringFormatter:
def set_string(self, str):
self.string = str
# удаление всех слов из строки, длина которых меньше n букв
def delete_words(self, n):
words = self.string.split(' ')
self.string = ' '.join(list(filter(lambda word: len(word) >= n, words)))
return self.string
# замена всех цифр в строке... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.