blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
b02629b418cb8c551b12360906b2be96c853026b | saranshbansal/learn-python | /ex-3-2-permmissingelem.py | 1,071 | 3.640625 | 4 | import unittest
import random
INT_RANGE = (0, 100000)
def solution(A):
"""
Find the missing element in a given permutation
:param A: list of integers
:return: the integer that is missing in O(n) time and O(1) space complexity
"""
# An empty list so the missing element must be "1"
if len(A... |
0137e324dcb0bc5260bcf65102fe6f03ae2aaf78 | saranshbansal/learn-python | /ex-3-1-frogjmp.py | 1,008 | 3.59375 | 4 | import unittest
import random
INT_RANGE = (1, 1000000000)
def solution(X, Y, D):
"""
Calculate the miminum number of jumps from X to Y
:param X: start integer
:param Y: minimum end integer
:param D: size of the jump
:return: minium number of jumps in O(1) time and space complexity
"""
... |
3ed10d405034b3b3c3c8d39f6421809b6152d366 | MrGoatMan/plaNEET | /Planet.py | 464 | 3.828125 | 4 | class Planet(object):
bodies = ['ringed', 'flat', 'gassy', 'terra']
colors = ['orange', 'red', 'blue', 'blue-green', 'brown']
def __init__(self, body, color):
self.bodyIndex = body
self.colorIndex = color
def __str__(self):
planet = Planet.bodies[self.bodyIndex]
planet ... |
4914e373050abc2fc202a357d4e8a82ee7bd87c7 | laurakressin/PythonProjects | /TheHardWay/ex20.py | 920 | 4.1875 | 4 | from sys import argv
script, input_file = argv
# reads off the lines in a file
def print_all(f):
print f.read()
# sets reference point to the beginning of the file
def rewind(f):
f.seek(0)
# prints the line number before reading out each line in the file
def print_a_line(line_count, f):
print line_count... |
9c996eeb30f22607825e3f42b856bd5888c8c56f | cwcrystal8/wackMIT | /main.py | 1,656 | 3.65625 | 4 | from Person import Person
import constants
import UI
import time
from Watch import Watch
def setUp():
# Ask for name
name = input("Enter your name: ")
# Ask for workoutLocations
workoutLocations = input("Enter your workout locations in a comma separated list: ").split(",")
workoutLocations = [word... |
c9f68086ab8f97bad4b3b1c1961a0216f655f14c | cscoder99/CS.Martin | /codenow9.py | 275 | 4.125 | 4 | import random
lang = ['Konichiwa', 'Hola', 'Bonjour']
user1 = raw_input("Say hello in English so the computer can say it back in a foreign langauge: ")
if (user1 == 'Hello') or (user1 == 'hello'):
print random.choice(lang)
else:
print "That is not hello in English" |
918ac12c1cfde62fa2ab339a8ab57dd7443b2062 | cscoder99/CS.Martin | /codenow3.py | 205 | 3.734375 | 4 | x = raw_input("Enter a decimal: ")
print x
n = 0
for i in x:
if i == '.':
print "Found a decimal"
break
# n = 1 as of right now
n = n + 1
hundreths = int(x[n+2])
|
a3da6cd81cafde1d2b97d8c8b42868007e4bc7c1 | cscoder99/CS.Martin | /hangman.py | 606 | 4 | 4 | inp = raw_input("What is your name: ")
print "Hello "+inp+". Welcome to hangman! Keep in mind spaces count as letters."
word = inp
guesses = ''
#number of turns
turns = 10
#turns
while turns > 0:
missed = 0
for letter in word:
if letter in guesses:
print letter,
else:
print '_',
missed... |
d44d5bc27bab6353e8680039ddca0d79051d56de | Jaydendai23/covid | /hello.py | 454 | 4.03125 | 4 | #print ("hello world")
#name = input ("best country in the world: ")
#print (name)
'''
if (name.lower() == "Canada"):
print (name + " is the best!")
elif (name == "Japan"):
print(name.lower() + " is the second best!")
else:
print ("wrong")
'''
fruits = ['apple,grannyssmith','orange,mandarin,bloodo... |
12866f83a9691dc75123e3b8e962de843529ce30 | Rafli1709/Struktur-Data | /Tugas 3/Score Board.py | 2,274 | 3.546875 | 4 | class GameEntry:
total_player = 0
def __init__(self, name, score, time):
self.name = name
self.score = score
self.time = time
GameEntry.total_player += 1
def setName(self, name):
self.name = name
def getName(self):
return self... |
346ff3a84beeb36520120b174b48dc370b2bfdc1 | anjosanap/faculdade | /1_semestre/logica_programacao/exercicios_aula/timer.py | 187 | 3.78125 | 4 | # Altere o programa anterior de modo que os
# segundos sejam exibidos no formato de um
# relógio digital, ou sejam hh:mm:ss.
s = 0
while s < 60:
print('00:00:%02d' % s)
s += 1
|
6bac138771347788474a115b37b56b241d8cc8f7 | anjosanap/faculdade | /1_semestre/logica_programacao/exercicios_apostila/estruturas_sequenciais_operadores_expressoes/ex6.py | 298 | 4.15625 | 4 | """
Faça um programa que peça a temperatura em grausFahrenheit,
transforme e mostre a temperatura em graus Celsius.
"""
fahrenheit = float(input('Insira sua temperatura em graus Fahrenheit: '))
celsius = (fahrenheit - 32) * 5 / 9
print('Sua temperatura em Celsius é:', '%.1f' % celsius, 'ºC')
|
05358477aa11e923d3ca5d133221718c5bb0bceb | anjosanap/faculdade | /1_semestre/logica_programacao/exercicios_aula/funcao.py | 194 | 3.828125 | 4 |
def quociente(x, y):
q = 0
while x >= y:
x -= y
q += 1
return q
a = int(input('a: '))
b = int(input('b: '))
q = quociente(a, b)
print('%d // %d = %d' % (a, b, q))
|
427f34023e2965902ecfd85b86fd555d37e7e54b | anjosanap/faculdade | /1_semestre/linguagem_programacao/ac5/ex2.py | 265 | 3.71875 | 4 | def sorteio():
num = input()
number = num.split()
alunos = []
n = number[0]
k = number[1]
for i in range(1, int(n) + 1):
nomes = input()
alunos.append(nomes)
alunos.sort()
print(alunos[int(k) - 1])
sorteio()
|
8ca86bc7752ea6b3e092093a824daf988a74fb3b | anjosanap/faculdade | /1_semestre/linguagem_programacao/ac5/ex3.py | 598 | 3.84375 | 4 | def count_list():
entrada = input()
lista = entrada.split()
inteiros = []
for n in lista:
inteiros.append(int(n))
while True:
comandos = input()
if 'inserir' in comandos:
valor = int(comandos.split()[1])
inteiros.append((valor))
elif 'remo... |
0c8bb785b97184847991a9b0bae582bd6fdbe96c | anjosanap/faculdade | /1_semestre/linguagem_programacao/ac2/ex5.py | 602 | 3.765625 | 4 | salario = float(input())
def inss():
if salario <= 1751.81:
desconto = round(salario * 0.08, 2)
print("Desconto do INSS: R$", "%.2f" % desconto)
else:
if 1751.82 <= salario <= 2919.72:
desconto = round(salario * 0.09, 2)
print("Desconto do INSS: R$", "%.2f" % de... |
2052521302b0654c70fc5e7065f4a2cd6ff71fb1 | martinfoakes/word-counter-python | /wordcount/count__words.py | 1,035 | 4.21875 | 4 | #!/usr/bin/python
file = open('word_test.txt', 'r')
data = file.read()
file.close()
words = data.split(" ")
# Split the file contents by spaces, to get every word in it, then print
print('The words in this file are: ' + str(words))
num_words = len(words)
# Use the len() function to return the length of a list (words... |
fbc2c2b14924d71905b9ad9097f2e9d7c9e541fc | davidobrien1/Programming-and-Scripting-Exercises | /collatz.py | 1,533 | 4.78125 | 5 | # David O'Brien, 2018-02-09
# Collatz: https://en.wikipedia.org/wiki/Collatz_conjecture
# Exercise Description: In the video lectures we discussed the Collatz conjecture.
# Complete the exercise discussed in the Collatz conjecture video by writing a
# single Python script that starts with an integer and repeatedly a... |
047cdec97ff851abf704b75c1f0ec5f20a66994c | davidobrien1/Programming-and-Scripting-Exercises | /tests.py | 1,163 | 3.9375 | 4 | # David O'Brien, 2018-02-23
# Week 5 Exercise 4 - Project Euler Problem 5
# Reference: https://code.mikeyaworski.com/python/project_euler/problem_5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# Write a Python program using for and range to calculate the s... |
aa71378aff7348a005466c9c753ea29f9045b5dd | davidobrien1/Programming-and-Scripting-Exercises | /tutorial.py | 118 | 3.671875 | 4 | # Fibonacci series:
# the sum of two elements defines the next
a, b = 10,30
while b < 100:
print(b)
a, b = b, a+b
|
45646923c0e4813a259e489f4fce767db05b5ed3 | whysofar72/SOME-Projects | /Python/Tutorials/ConditionalStatements_basicform.py | 303 | 3.609375 | 4 | if True:
print("Defcon1")
print("Defcon2")
print("-----------")
print("Defcon5")
if False:
print("Defcon1")
print("Defcon2")
print("-----------")
print("Defcon5")
input_1 = 1
default = 2
if input_1 == default:
print("= WELCOME ! =")
if input_1 != default:
print("= WRONG ! =")
|
d31bfb61f8e01688b186e6ccf860c12f8b1184de | j-kincaid/LC101-practice-files | /LC101Practice/Ch13_Practice/Ch13_fractions.py | 543 | 4.21875 | 4 | class Fraction:
""" An example of a class for creating fractions """
def __init__(self, top, bottom): # defining numerator and denominator
self.num = top
self.den = bottom
def __repr__(self):
return str(self.num) + "/" + str(self.den)
def get_numerator(self):
return... |
878934e0c30544f1b8c659ed41f789f20d9ac809 | j-kincaid/LC101-practice-files | /LC101Practice/Ch10_Practice/Ch10Assign.py | 1,008 | 4.15625 | 4 | def get_country_codes(prices):
# your code here
""" Return a string of country codes from a string of prices """
#_________________# 1. Break the string into a list.
prices = prices.split('$') # breaks the list into a list of elements.
#_________________# 2. Manipulate the individual element... |
01c29535868a34895b949fa842ba41393251e622 | j-kincaid/LC101-practice-files | /LC101Practice/Ch9_Practice/Ch_9_Str_Methods.py | 880 | 4.28125 | 4 | #___________________STRING METHODS
# Strings are objects and they have their own methods.
# Some methods are ord and chr.
# Two more:
ss = "Hello, Kitty"
print(ss + " Original string")
ss = ss.upper()
print(ss + " .upper")
tt = ss.lower()
print(tt + " .lower")
cap = ss.capitalize() # Capitalizes the first chara... |
6a33880c02406c0b57a910fd204736ee07cb38b2 | j-kincaid/LC101-practice-files | /LC101Practice/Unit2_videos/main.py | 3,238 | 3.703125 | 4 | from flask import Flask, request
app = Flask(__name__)
app.config['DEBUG'] = True
form = """
<!doctype html>
<html>
<body>
<form action="/hello" method="post">
<label for="first-name">First Name:</label>
<input id="first-name" type="text" name="first_name" />
<input typ... |
182a1b4b156d851e37140c4da8b15396d09532ae | j-kincaid/LC101-practice-files | /sketchbook/colorSwap.py | 800 | 3.828125 | 4 | import image # imports the image module
img = image.Image("colorSwap.jpg") # makes an image object
new_img = image.EmptyImage(img.getWidth(), img.getHeight()) # creates new image
win = image.ImageWin(img.getWidth(), img.getHeight()) # creates window
# To start with, each pixel already has RGB values, and positions ... |
516a1eca47213d5e9a8deec7d65c2d8b2da63186 | j-kincaid/LC101-practice-files | /initials/initials1.py | 564 | 3.78125 | 4 | def get_initials(fullname):
# some code heremy_name = "Edgar Allan Poe"
user_name = input(‘Type your name and press ENTER: ’)
name_list = user_name.split()
init = ""
for name in name_list:
init = init + name[0]
print(init)
if __name__ == ‘__main__‘:
main()
def main():
get... |
fbbd8aec184e28090d2f422ce3e7761b93b1e0e6 | Iggy-o/Animal-Quiz | /main.py | 3,752 | 4.03125 | 4 | #Ighoise Odigie
#May, 5 2020
#Youtube: https://www.youtube.com/channel/UCud4cJjtCjEwKpynPz-nNaQ?
#Github: https://github.com/Iggy-o
#Preview: https://repl.it/@IghoiseO/Animal-Quiz#main.py
#<!--First Part: The Setup-->
#This is the title which is just for aesthetic purposes
intro = "---Welcome to Guess That Animal---\n... |
c6ec555eeaef1073a39e398c7521b1647e5887e3 | Alex-Nelson/fluffy-meme | /Code/gameCode.py | 2,691 | 3.78125 | 4 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import time
import random
myTime = 20
myScore
# game function
def game():
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
d48fa465ac91eaaff4ebe1763c5602a6ee7f4ea9 | omrilahav/MinHash | /src/shingles_extractors/base_shingles_extractor.py | 1,086 | 3.640625 | 4 | class ShinglesExtractor(object):
"""
This class handles Shingles extraction from an input object, to be used for the generation
of a min-Hash signature for that object.
This is one of the "trickiest" parts since every different type of object (text, photo, etc.)
requires specific domain implementat... |
2317892ebfe4c78a51c72e644ff2b08c6e31ad35 | CalebRound30/bookish-octo-succotash | /Borwell Software Challenge.py | 58,742 | 4.125 | 4 | #Borwell Software Challenge
def mode1():# sub section 1 called in main
print('')
print('Area of the floor calculator')
print('')
roomType = input('Does the room have a recess\n Yes/No....')
print('')
if roomType == 'yes' or roomType == 'y':
numOfRecess=int(input('How many receses do you... |
8623429eef056fbe8086ea157a6960dfb3b0020a | sandeeppanem/PythonCode | /Search_SortedRotatedArray.py | 1,042 | 3.734375 | 4 | def BinSearch(input_list,low,high,key):
if high<low:
return -1
mid=(low+high)/2
if input_list[mid]==key:
return mid
if key>input_list[mid]:
return BinSearch(input_list,mid+1,high,key)
else:
return BinSearch(input_list,low,mid-1,key)
def findPivot(input_list,low,high):
if high<low:
return -1
if high==... |
307715546240a9f1b6ace9636e05ded963ad5cb2 | bstcpext/tdd | /compute_stats_refactor.py | 556 | 3.71875 | 4 |
file = 'random_nums.txt
def read_ints():
data = []
with open(file, 'r') as f:
for line in f:
num = int(line)
data.append(num)
return data
def count():
data = read_ints()
i = 0
while i < len(data):
i =+ 1
return i
def summation():
sum = 0
... |
d24e276ac5dc479fc22ad2e0caa2517bc04ac8c2 | badgeteam/ESP32-platform-firmware | /firmware/python_modules/pixel/valuestore.py | 2,584 | 3.5625 | 4 | ## These functions allow you to easily load and save Python objects as json files in /config/.
def load(namespace='system', keyname=''):
"""
Loads any type of Python primitive object from a json file.
:param namespace:
:param keyname:
:return:
"""
import ujson
if namespace == '' or keyn... |
3646f720e237994dcc4dac0649b8e444ab4591c8 | butflame/DesignPattern | /Structural/Decorator.py | 673 | 4.0625 | 4 | """
Decorator Pattern.
To make addition actions to func or methods without modify origin code.
"""
from functools import wraps
def memoize(fn):
known = dict()
@warps(fn):
def memoizer(*args):
if args not in known:
known[args] = fn(*args)
return known[args]
# Only apply decorator in some conditions
cond =... |
2c4f3ba1691eacb17f503cce81def743950d16c0 | hgpestana/hacker-rank | /scripts/min-max.py | 320 | 3.578125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def min_max(array):
results = []
for i in range(len(array)):
results.append(sum(array) - array[i])
print("{} {}".format(min(results), max(results)))
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5]
min_max(arr)
|
a05fb71cacdcfafa844a44b06c517fe5d88bb9ec | nehapokharel/pythonPractice | /functions/question14.py | 325 | 3.890625 | 4 | def sort_dictionary(result):
sorted_keys = sorted(result, key = lambda i: i['price'])
return sorted_keys
fruits = [
{"name" : "apple", "price" : 150},
{"name" : "mango", "price" : 160},
{"name" : "litchi", "price" : 120},
{"name" : "banana", "price" : 200}
]
y = sort_dictionary(fruits)
print(y... |
7b3ddc35dd89fc07576a077b4107aa1a8be15052 | nehapokharel/pythonPractice | /question38.py | 193 | 3.796875 | 4 | sample_dictionary = {'a':1,'b':2,'c':3,'d':4}
key = input("Enter key: ")
if key in sample_dictionary:
del sample_dictionary[key]
else:
print('key not found')
print(sample_dictionary) |
273d151a3a0eff1b9900649c6dbb81629eb50655 | nehapokharel/pythonPractice | /question18.py | 120 | 3.828125 | 4 | numberlist = [1, 34, 5, 7]
max = numberlist[0]
for num in numberlist:
if num > max:
max = num
print(max)
|
7a68d3bfdd84827f9ae01de16146f2ae415a4f9b | nehapokharel/pythonPractice | /functions/question11.py | 203 | 3.71875 | 4 | def sum_number():
return lambda x : x + 15
y = sum_number()
print("sum: " + str(y(5)))
def multiple_number():
return lambda x, y: x * y
z = multiple_number()
print("multiple: " + str(z(2, 5))) |
969eb84abc5650282e0c271fa3887763e2d9057f | Pices-26/Python_Basic_learning | /when_will_you_turn_100.py | 299 | 3.84375 | 4 | #this will tell you when you will turn 100
name = input('input your name: ')
age = int(input('input your age: '))
year = int(input('what is the year? \n '))
add_age = 0
will_turn = 0
add_age = 100 - age
will_turn = year + add_age
print(name + ' you will turn 100 in:' + str(will_turn))
|
107086f6c6b924820be8e5a542141049b2291920 | CoderTag/Python | /DataStructure/LinkedList.py | 1,828 | 3.859375 | 4 | from random import randrange
class Node(object):
data = None
link = None
class LinkedList(object):
def __init__(self):
self.head = None
self.size = 0
def insertAtEnd(self, data):
node = Node()
node.data = data
node.link = None
if self.head == None:
... |
bce135535ef6977883aeb90a274f5d4c7c4c9b1e | CoderTag/Python | /Pract/counting_with_dictionary.py | 599 | 3.5 | 4 | from collections import defaultdict
colors = ['red', 'green', 'blue', 'green', 'blue', 'green', 'blue', 'red', 'green']
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
print(d)
print('<->' * 20)
d = {}
for color in colors:
d[color] = d.get(color, 0 + 1)
print(d)
print('<-... |
3075271587efa23d3a2eba83eece902024321387 | CoderTag/Python | /tutorial-2:number.py | 350 | 3.984375 | 4 | int_num = 3
float_num = 4.5
print(f'{type(int_num)} {type(float_num)}')
print(3/2) # Division
print(3//2) # FLoor Division
print(3**2)
print(abs(-67)) # absolute value
print(round(3.75)) # round it to nearest int value
print(round(3.5))
print(round(3.4))
print(round(3.75,1)) # 2nd digit says how many ... |
c2570e4c6ef6f4d83565952d783fa681eed14981 | lunaxtasy/school_work | /primes/prime.py | 670 | 4.34375 | 4 | """
Assignment 3 - Prime Factors
prime.py -- Write the application code here
"""
def generate_prime_factors(unprime):
"""
This function will generate the prime factors of a provided integer
Hopefully
"""
if isinstance(unprime, int) is False:
raise ValueError
factors = []
#for c... |
0cc45bbbaa8f7a70f6eeb9b72dda5e9042559cc7 | Punit-Choudhary/Popular_movies | /main.py | 8,524 | 3.8125 | 4 | # Projec-+b741b
# b Name : Popular Movies of IMDB.com
# Importing required modules
import pandas as pd
import numpy as np
import time
import sqlalchemy
import matplotlib.pyplot as plt
# Imported Data frame
df = pd.DataFrame()
csv_file = "D:\Python\March\Popular_movies\imbd_updated.CSV"
def read_csv_file():
df =... |
f40a3e83c7a8a29bf29d7de2e7c67028d6441708 | infnetdanpro/lesson1 | /answers.py | 319 | 3.609375 | 4 | def get_answer(question):
answers = {'привет':'И тебе привет!', 'как дела':'Лучше всех', 'пока':'Увидимся'}
return answers.get(question, 'Задайте вопрос еще раз').lower()
question = input('Введите текст: ')
print(get_answer(question)) |
c7e3c16658603c5b47969d310fc0b41125500feb | TangMartin/CS50x-Introduction-to-Computer-Science | /PythonPractice/stringlists.py | 558 | 4.03125 | 4 | def main():
word = input("Word: ")
letters = len(word)
counter = 0
for x in range(round(letters / 2)):
if(word[x] == word[letters - 1 - x]):
counter += 1
else:
continue
if(round(letters / 2) == counter):
print("The word is a palindrome")
else... |
b241bbd11590407332240b8254c911742e4382cc | TangMartin/CS50x-Introduction-to-Computer-Science | /PythonPractice/oddoreven.py | 264 | 4.28125 | 4 | number = -1
while(number <= 0):
number = int(input("Number: "))
if(number % 2 == 0 and number % 4 != 0):
print("Number is Even")
elif(number % 2 == 0 and number % 4 == 0):
print("Number is a multiple of four")
else:
print("Number is Odd")
|
d7ea7a3aa5fd686de83f2a7b7c5928eb06bb75a7 | TangMartin/CS50x-Introduction-to-Computer-Science | /PythonPractice/characterinput.py | 153 | 3.84375 | 4 | name = input("What is your name? ")
age = int(input("What is your age? "))
years = str(2020 + (100 - age))
print(name + " will be 100 years in " + years) |
3a8d7389f833f615e0e79a24733bb3d07ab1f91a | jdavini23/zookeeper | /Problems/Tail/task.py | 154 | 3.984375 | 4 | # print the last symbol of the predefined variable `sentence`
print("Enter a number: ") # user enters 10
user_num = input()
print(user_num + user_num) |
9ddd5548919db4e21d415812ded03b0cfdae030a | jdavini23/zookeeper | /Problems/Movie theater/task.py | 174 | 3.609375 | 4 | num_of_halls = int(input())
capacity = int(input())
number_of_viewers = int(input())
if num_of_halls * capacity >= number_of_viewers:
print(True)
else:
print(False)
|
aedbfeef11bc3906360a67ae3a58f01ebda26b60 | fendouai/gkseg | /gkseg/segment/handler.py | 1,762 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Handler:
def __init__(self):
self.segmented = []
self.marked = []
self.labeled = []
self.word = ''
self.nmcnt = 0
self.mkcnt = 0
def add(self, ch):
self.word = self.word + ch
... |
b68f2ea57865491cfd10b0a6a4af755f57025a12 | httghttg/Beyond-Infinity | /Model/GameSpriteModel.py | 1,632 | 3.5 | 4 | import pygame
class GameSprite(pygame.sprite.Sprite):
# class for a Sprite. To create a sprite you must provide: (x coordinate, y coordinate, size of the image, array of
# all the images, and the starting frame)
def __init__(self, xcor, ycor, width, height, images, starting_frame):
super(GameSprit... |
50a08493366db7134899674c17c22803d832e7e4 | Kartavya-verma/Competitive-Pratice | /PyLearn/demo2.py | 417 | 4.03125 | 4 | '''lis=[]
n=int(input("Enter the length of list: "))
for i in range(n):
a=int(input("Enter the value to be inserted in list:"))
lis.append(a)
for i in lis:
print(i,end=" ")'''
from array import *
array=array('i',[])
num=int(input("Enter the length of array: "))
for i in range(num):
x=int(input("Enter ... |
70fcc8d990a5bb45f294af0c6b6c4607df6c2b5a | Kartavya-verma/Competitive-Pratice | /LeetCode/valid_parantheses.py | 630 | 3.578125 | 4 | # n = input()
# l = 0
# for i in n:
# # print(i)
# if i == "(":
# l += 1
# print(l)
# elif i == ")":
# l -= 1
# print(l)
# # print(l)
s = "{[]}"
if len(s) % 2 != 0:
print("false")
else:
stack = []
for c in s:
if c == "(" or c == "[" or c == "{" :
... |
c1e0db17ea4fba4b05457058965f697d2eb41a54 | Kartavya-verma/Competitive-Pratice | /Python/looping_in_dict.py | 655 | 3.671875 | 4 | user_info={
"name":"harshit",
"age":24,
"fav_movies":["coco","kimi no na wa"],
"fav_tune":["awakening","fairy tail"],
}
'''if "name" in user_info:
print("present")
else:
print("not present")
if "harshit" in user_info.values():
print("present")
else:
print("not present")'''
for i in ... |
32d0aa6e3c5c083e6db1e174c3726a3ae99835ab | Kartavya-verma/Competitive-Pratice | /PyLearn/demo1.py | 362 | 4.125 | 4 | '''for i in range(0,5,1):
for j in range(0,5,1):
if j<=i:
print("*",end="")
print()'''
'''for i in range(6):
for j in range(6-i):
print("*",end="")
print()'''
q=int(input("Enter a num: "))
for i in range(2,q):
if q%i==0:
print("Not a prime num")
... |
5427e7c9d4f295ffef3a41ce8354a51bd3fa6aa9 | Kartavya-verma/Competitive-Pratice | /Python/nptel3.py | 658 | 3.5 | 4 | top=-1
def Push(stk,x):
stk.append(x)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "under flow"
else:
x=stk.pop()
if len(stk)==0:
top=-1
else:
top=len(stk)-1
return x
def isEmpty(a):
if a==[]:
return True
else:
... |
4f0eeae9e8b694f185647af56c474c8bb9e2b7f3 | Kartavya-verma/Competitive-Pratice | /Helix Contest/helix_fact.py | 174 | 4.0625 | 4 | from math import factorial
for i in range(int(input())):
n = int(input())
if factorial(n)%10 == 0:
print("Divisible")
else:
print("Not Divisible") |
d8b911f33e95fc1708b27c69a14f4115a71fcd95 | Kartavya-verma/Competitive-Pratice | /CodeChef/sep_lunch_ada_matrix.py | 629 | 3.703125 | 4 | # N = 4
#
# def transpose(A, B):
# for i in range(N):
# for j in range(N):
# B[i][j] = A[j][i]
#
# # driver code
#
#
# A = [[1, 2, 9, 13],
# [5, 6, 10, 14],
# [3, 7, 11, 15],
# [4, 8, 12, 16]]
#
# B = A[:][:]
#
# transpose(A, B)
#
# print("Result matrix is")
# for i in ran... |
b9185f75bd5c207a1a5042e39acbcfd01d519491 | Kartavya-verma/Competitive-Pratice | /Assignment/Flow control assignment/4.py | 174 | 3.859375 | 4 | test_number = 9669669
print("The original number is : " + str(test_number))
res = str(test_number) == str(test_number)[::-1]
print("Is the number palindrome ? : " + str(res)) |
c4392782c11dd95c0949742b733933b9410eb14d | Kartavya-verma/Competitive-Pratice | /LeetCode/climbing_stairs.py | 790 | 3.59375 | 4 | # Method 1
class Solution:
def climbStairs(self, n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
else:
a = 1
b = 2
res = 0
while n > 2:
res = a + b
... |
6b3560205341dd1b07af4c3c6bd8b6a87a83afb3 | Kartavya-verma/Competitive-Pratice | /Python/tuples.py | 409 | 3.8125 | 4 | '''example=("one","two","three")
days=("monday","tuesday")
print(example[::-1])'''
'''mixed=(1,2,3,4.0)
for i in mixed:
print(i,end=",")'''
'''nums=(1,)
words=("word1",)
guitars='yamaha','baton rouge','taylor'
guitarists=("maneli","eddie","adrew")
g1,g2,g3=(guitarists)
print(g1)'''
'''favourites=("south",["tok... |
3d0f7459c13797a77e083002c839e992821fdcc1 | Kartavya-verma/Competitive-Pratice | /LeetCode/power_of_two.py | 118 | 3.65625 | 4 | n = int(input())
c = 0
while n > 0:
c += 1
n = n & (n-1)
if c == 1:
print("true")
else:
print("false") |
36020e1b3eaa7ce3cfd732813f6f86b0948245e3 | Kartavya-verma/Competitive-Pratice | /Linked List/insert_new_node_between_2_nodes.py | 1,888 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def inserthead(self, newnode):
tempnode = self.head
self.head = newnode
self.head.next = tempnode
del tempnode
def li... |
8318f65105de5d40127e27fc0b99dbe9bac1b2cc | Kartavya-verma/Competitive-Pratice | /Python/function.py | 225 | 3.71875 | 4 | #name="harshit"
#print(len(name))
def add_two(a,b):
return a+b
#total=add_two(5,4)
#print(total)
#print(add_two(5,4))
a=int(input("Enter 1st number:"))
b=int(input("Enter 2nd number:"))
total=add_two(a,b)
print(total) |
3e738b9ca0a1be7f071f8f7aee5179499f2a75bf | Kartavya-verma/Competitive-Pratice | /Python/for_&_string.py | 294 | 3.734375 | 4 | '''name="harshit"
for i in range(len(name)):
print(name[i])'''
'''name="harshit"
for i in name:
print(i)'''
'''num=input("Enter a number:")
sum=0
for i in num:
sum+=int(i)
print(sum)'''
num=input("Enter a number: ")
sum=0
for i in range(len(num)):
sum+=int(num[i])
print(sum) |
ea3cca6587734cce5c7cff69f398afe5f340e323 | Kartavya-verma/Competitive-Pratice | /Python/reverse.py | 56 | 3.578125 | 4 | number=["1","2","3","4"]
number.reverse()
print(number)
|
3d4e91026d5ecc2b014b1593e27181a46d3f3010 | Kartavya-verma/Competitive-Pratice | /Python/2_no_greater.py | 186 | 4.0625 | 4 | a=int(input("Enter 1st number :"))
b=int(input("Enter 2nd number :"))
if a>b:
print("1st is greater")
elif b>a:
print("2nd is greater")
else:
print("Number is 0 or negative") |
d067a858f74ce1c34297dd8a3a8795c8aceb558a | bzjsky/cy_spider | /util/RegExUtil.py | 334 | 3.625 | 4 | # -*- coding: utf-8 -*-
import re
def find_first(pattern, string):
if string is None or len(string) == 0:
return
items = re.findall(pattern, string)
if len(items) > 0:
return items[0]
def remove(pattern, string):
return re.sub(
pattern=pattern,
repl="",
string... |
5d0121feb7e806e3ef4146331fce29947966bfb5 | bauassr/Session18_assignment3 | /session18.2.py | 1,812 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 10:23:56 2018
@author: avatash.rathore
"""
import numpy as np
import pandas as pd
import scipy.stats as stats
import scipy as s
import matplotlib.pyplot as plt
import math
print("""In one state, 52% of the voters are Republicans, and 48% are Democrats. In... |
44cce6854386b70e91096ff69d7a7a9e5d8a0053 | novpeter/Algorithms | /huffman_encoder.py | 1,436 | 3.671875 | 4 | import heapq
from collections import Counter # словарь в котором для каждого объекта поддерживается счетчик
from collections import namedtuple
parent = namedtuple("Node", ["left", "right"])
leaf = namedtuple("Leaf", ["char"])
class Node(parent):
def walk(self, code, acc):
self.left.walk(code, ac... |
34e7f7e3d1b5c3688c8091c12c360da3f4563c45 | PoojaKushwah1402/Python_Basics | /Sets/join.py | 1,642 | 4.8125 | 5 | # join Two Sets
# There are several ways to join two or more sets in Python.
# You can use the union() method that returns a new set containing all items from both sets,
# or the update() method that inserts all the items from one set into another:
# The union() method returns a new set with all items from both sets:
... |
52355dd175d820141ce23ace508c0c73501a74b0 | PoojaKushwah1402/Python_Basics | /variable.py | 809 | 4.34375 | 4 | price =10;#this value in the memory is going to convert into binary and then save it
price = 30
print(price,'price');
name = input('whats your name ?')
print('thats your name '+ name)
x, y, z = "Orange", "Banana", "Cherry" # Make sure the number of variables matches the number of values, or else you will get an error.... |
692f1ef93f6b188a9a3244d45c73239e18ded92c | PoojaKushwah1402/Python_Basics | /Sets/sets.py | 999 | 4.15625 | 4 | # Set is one of 4 built-in data types in Python used to store collections of data.
# A set is a collection which is both unordered and unindexed.
# Sets are written with curly brackets.
# Set items are unordered, unchangeable, and do not allow duplicate values.
# Set items can appear in a different order every time you... |
9df5a51bffcc602bc34b04de97ef2b65e1a7759f | PoojaKushwah1402/Python_Basics | /List/list.py | 1,906 | 4.4375 | 4 | #Unpack a Collection
# If you have a collection of values in a list, tuple etc. Python allows you extract the
#values into variables. This is called unpacking.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x,'x')
print(y,'y')
print(z,'z')
# Lists are one of 4 built-in data types in Python used to sto... |
54171a5b3ac44a76a925540decb9b93280649162 | lnfnet/myStady | /python_code/inherit.py | 600 | 4.03125 | 4 | #!/usr/bin/python
#incoding = utf-8
class SchoolMember:
'''represents any school member.'''
def __init__(self,name,age) -> None:
self.name=name
self.age=age
print("init school member! %s",self.name)
def tell(self):
'''Tell me details.'''
print('Name:%s Age: %s',self.... |
0520b470cc82feca95dbb066f8be9d0047270a55 | Solome6/StockHistoryGrapher | /visualize_functions.py | 763 | 3.65625 | 4 | import matplotlib.pyplot as plt
import matplotlib.dates as mdates
"""
Input: queried data, start_date, end_date.
Output: None.
Does: Plots the dates on the x-axis and closing prices on the y-axis.
"""
def visualize(data, start, end, symbol):
dates = data.get('date')
close_prices = data.get('close')... |
f2bf7b8d58c3cd1c62ef60dcd106de516a7dce3f | Franco414/DASO_C14 | /Guia_de_Ejercicios_Python/Ejercicio8.py | 699 | 3.8125 | 4 | """
8. Escribir una función que reciba un diccionario y escriba en un archivo cuyo nombre se recibe
también como argumento, los datos en formato clave=valor.
"""
def dic2txt(diccionario,nombre):
lista_claves = list(diccionario.keys())
lista_valores = list(diccionario.values())
print(lista_claves)
print... |
f87ea76282626fba9e5f4e590bfdf282304346d4 | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad7/Ejercicio_7_4.py | 1,649 | 4.46875 | 4 | """
a) Escribir una función que reciba dos vectores y devuelva su producto escalar.
b) Escribir una función que reciba dos vectores y devuelva si son o no ortogonales.
c) Escribir una función que reciba dos vectores y devuelva si son paralelos o no.
d) Escribir una función que reciba un vector y devuelva su norma.
"""
... |
cf3d9ca8fcdc8614da2125e706b882c8e17b76db | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad3/Ejercicio_3_3.py | 4,399 | 3.953125 | 4 | """
Ejercicio 3.3. Área de un triángulo en base a sus puntos
a) Escribir una función que dado un vector al origen (definido por sus puntos x,y), devuelva la
�
norma del vector, dada por || (x, � y)|| = x 2 + y 2
b) Escribir una función que dados dos puntos en el plano (x1,y1 y x2,y2), devuelva la resta de
ambos (debe d... |
dcfa6ed57445ecd90fdec3e3f5c431f0628bf3db | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad5/Ejercicio_5_9.py | 816 | 4.375 | 4 | """
Ejercicio 5.9. Escribir una función que reciba dos números como parámetros, y devuelva cuántos múl-
tiplos del primero hay, que sean menores que el segundo.
a) Implementarla utilizando un ciclo for, desde el primer número hasta el segundo.
b) Implementarla utilizando un ciclo while, que multiplique el primer número... |
ec15aa066d78cf97b500f439dd5afbc76b75699f | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad4/Ejercicio_4_7.py | 1,053 | 3.75 | 4 | """
Ejercicio 4.7. Escribir un programa que reciba como entrada un año escrito en números arábigos y
muestre por pantalla el mismo año escrito en números romanos.
Unidad=["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
Decena=["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
Centena=["", "C", "CC... |
b7938c1ce021f5a226b7d872f53b1aba98f9536d | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad2/ejercicio_2_5.py | 853 | 4.0625 | 4 | """
Ejercicio 2.5. Escribir un programa que reciba un número n por parámetro e imprima los primeros n
números triangulares, junto con su índice. Los números triangulares se obtienen mediante la suma de los
números naturales desde 1 hasta n. Es decir, si se piden los primeros 5 números triangulares, el programa
debe imp... |
3c2a6460f9ecf8aa897ba35c3bf02c082e1f8c7a | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad4/Ejercicio_4_6.py | 601 | 3.6875 | 4 | """
Ejercicio 4.6. Suponiendo que el primer día del año fue lunes, escribir una función que reciba un número
con el día del año (de 1 a 366) y devuelva el día de la semana que le toca. Por ejemplo: si recibe ’3’ debe
devolver ’miércoles’, si recibe ’9’ debe devolver ’martes’
"""
def obtener_dia(numero):
dias=["Domi... |
110cb8c22701030bdc7ce2eef73162ecc995a360 | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad5/Ejercicio_5_10.py | 569 | 3.828125 | 4 | """
Ejercicio 5.10. Escribir una función que reciba un número natural e imprima todos los números primos
que hay hasta ese número.
"""
def es_primo(numero):
resultado=True
if numero>=-1 and numero<=1:
return resultado
for i in range(2,numero):
if numero%i==0:
resultado=False
... |
0158dbde9a2e6a599b1755dad831b5680701aca0 | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad7/Ejercicio_7_10.py | 1,370 | 3.546875 | 4 | """
Escribir una función que reciba un texto y una longitud y devuelva
una lista de cadenas de como máximo esa longitud. Las líneas deben ser cortadas correctamente en los
espacios (sin cortar las palabras).
"""
def separar_texto(nombre,longitud):
lista=[]
my_txt=open(nombre,"r")
content=my_txt.read()
... |
1749fc700b55dc9860bfe2f98b8336ee151c29ce | Franco414/DASO_C14 | /Ejercicios_Extras/Unidad4/Ejercicio_4_4.py | 1,727 | 4.28125 | 4 | """
Ejercicio 4.4. Escribir funciones que permitan encontrar:
a) El máximo o mínimo de un polinomio de segundo grado (dados los coeficientes a, b y c),
indicando si es un máximo o un mínimo.
b) Las raíces (reales o complejas) de un polinomio de segundo grado.
Nota: validar que las operaciones puedan efectuarse antes de... |
9694b823a72621adf5771ae2882c5ded9491dcb5 | leskoarpi/Projekt1 | /arpi2.py | 707 | 3.78125 | 4 | import turtle
def star(turtle, n,r):
for k in range(0,n):
turtle.pendown()
turtle.forward(r)
turtle.penup()
turtle.backward(r)
turtle.left(360/n)
fred = turtle.Turtle()
def recursive_star(turtle, n, r, depth, f):
if depth == 0:
star(turtle, n, f*4)
else:
for k in range(0,n):
turt... |
ed5b69798e6c9acd058440d77f20dde3fbab5a2b | kingslayer2357/SummaryPlay | /pythonScripts/Python_SpeechRecoginition.py | 1,438 | 3.515625 | 4 | import speech_recognition as sr
from os import path
from pydub import AudioSegment
src = "output.mp3"
dst = "output.wav"
sound = AudioSegment.from_mp3(src)
sound.export(dst, format="wav")
import speech_recognition as sr
import os
from pydub im... |
74027ce2ead3993f161141d0388035c1340b80f0 | AndrianusTinas95/learning-oop-python | /class-object.py | 476 | 3.75 | 4 | class Hero:
# class variable
count = 0
def __init__(self,name,health,power,armor):
# is instance variablr
self.name = name
self.health = health
self.power = power
self.armor = armor
Hero.count +=1
print("Membuat hero dengan nama " + name)
he... |
b16799d63448e4e7cebab19d99a1263a87d64bb6 | fahadhamid/CSV-Parsing | /Parser.py | 4,999 | 3.59375 | 4 | """parses the file and displays each individual record"""
__author__ = 'root'
import csv
def remove_title_info(list_reader):
for title_row in list_reader:
if str(title_row).__contains__('Patient Name'):
end_title = list_reader.index(title_row)
return end_title
def remove_extra_ti... |
359d4f4ea9ac43ce34ec14d0c060f89f7e59ce0e | oconnorjoseph/CourseworkPython | /HW2/problem1.py | 842 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 8 01:57:08 2017
@author: Joseph O'Connor
UNI: jgo2115
"""
VOWELS = "aeiou"
running = True
user_word = ""
def piggy(word):
accumulated_consonants = ""
for char in word:
if char in VOWELS:
if len(accumulated_consona... |
901fd7be482bf667c0d4b64ec369fca27462c932 | oconnorjoseph/CourseworkPython | /HW3/problem1.py | 3,625 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Joseph O'Connor
UNI: jgo2115
"""
from collections import defaultdict
import string
def compare(item1, item2):
item1[0] - item2[0]
def count_ngrams(file_name, n=2):
"""
This function reads an input file and returns a dictionary of n-gram co... |
5d7f9c250fb8269cf8697c41fa932ce6181aba6b | khouka/RoboticArmPush | /src/ram_push/scripts/Interia.py | 710 | 4 | 4 | print"This is a basic interia calculator for the cylinder and box links"
print"For box shaped links"
m = input('mass: ')
x = input('input the length(x): ')
y = input('input the width(y): ')
z = input('input the height(z): ')
ixx = 0.0833333 * m * (y**2 + z**2)
iyy = 0.0833333 * m * (x**2 + z**2)
izz = 0.0833333 * m *... |
ee49c1101672e180884db5918808e8c0c0d33f55 | arun-nemani/project-euler | /p006.py | 720 | 3.59375 | 4 | # The sum of the squares of the first ten natural numbers is 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers,
# and the square of the sum is 3025 − 385 = 2640.
# ... |
3bfe7b111d532b9be3d0e7c4ba824509b1b6dd4d | Pi-Robot/code | /robot/class4.py | 895 | 3.84375 | 4 | # threading class
import threading
import time
class myThread (threading.Thread):
def __init__(self, name, counter, delay):
threading.Thread.__init__(self)
self.name = name
self.counter = counter
self.delay = delay
def run(self):
print ("Start " + self.name)
print... |
60a21b10292239686a40be128f39236d7e66de5c | Sean-Burnett/Python | /lottobig.py | 4,935 | 3.578125 | 4 | import sys, os
a = []
b=98
c=98
d=98
e=98
f=98
g=98
def pickThree():
while True:
try:
b = input("Input the first number of the last mega million number:")
if b not in [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41... |
ec9891b66eeea30422c4090620faf35a990d1155 | LearningPythonBU/UriOnlineJudge | /1021-r1.py | 706 | 3.625 | 4 | val = float(input())
stack = [100,50,20,10,5,2]
print("NOTAS:")
for x in stack:
num = 0
while(val >= x):
num = num+1
val = val - x
print(str(num) + " nota(s) de R$ %0.2f" % x )
print("MOEDAS:")
# this is necessary because fractional subtraction
# was providing rounding errors, especially with
# the smaller f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.