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 |
|---|---|---|---|---|---|---|
8383a43b540f04be1f3e20a85017c9f42fe4e13c | ugant2/python-snippate | /pract/string.py | 1,664 | 4.3125 | 4 | # Write a Python function to get a string made of the first 2
# and the last 2 chars from a given a string. If the string
# length is less than 2, return instead of the empty string.
def string_end(s):
if len(s)<2:
return ' '
return len(s[0:2]) + len(s[-2:])
print(string_end('laugh out'))
# Write ... |
d58357ae7e41c5f02aa4c14dfd83a77c13fa7d1c | ugant2/python-snippate | /function/lamdafunction2.py | 484 | 3.9375 | 4 |
# combine first name and last name into single "full name"
full_name = lambda fn, ln: fn.split() + ln.split()
print(full_name("yufanr", "the"))
#lambda function to sort alphabetically
authors = ["paulo cohelo", "mark twin", "robbin sharma", "laxmi parsad devkota","madhav parsad gmere"]
authors.sort(key=lambda na... |
6d59933e03b7bec866a76eff22a09196d441b92b | ugant2/python-snippate | /file and Exception/elseClause.py | 661 | 3.765625 | 4 | # The use of the else clause is better than adding
# additional code to the try clause because it avoids accidentally catching an exception
# that wasn’t raised by the code being protected by the try … except statement.
import sys
for arg in sys.argv[1:]:
try:
f = open(arg, "r")
except OSError:
... |
75a068175dd23bd786319ab2df60e61aee8dbfa1 | ugant2/python-snippate | /oop/inheritance Animal.py | 651 | 4.34375 | 4 |
# Inheritance provides a way to share functionality between classes.
# Imagine several classes, Cat, Dog, Rabbit and so on. Although they may
# differ in some ways (only Dog might have the method bark),
# they are likely to be similar in others (all having the attributes color and name).
class Animal:
def __init... |
3eb1b151dc78e3a0166c3836c8e28d7ea725c958 | ugant2/python-snippate | /dictionary/usingDictionary.py | 352 | 3.921875 | 4 | table = {"python":"Guido van Rossum", "perl":"larry wall", "tcl":"john ousterhout" }
print(table)
print("\t")
table = {"python":"Guido van Rossum", "perl":"larry wall", "tcl":"john ousterhout" }
language = "perl" #cannot someone easily access over information through dictionery
creator = table[language]
print(creat... |
c975b964adf0ba049513c825185b1e21722f26f1 | lkutsev/GB_05_01 | /main.py | 1,055 | 3.625 | 4 | #Не читать - еще не готово!!!
#1 2 + 4 × 3 +
#def pipeline(e, *functions):
# for f in functions:
# e = bind(e, f)
# return e
#Теперь вместо
#bind(bind(bind(bind(unit(x), f1), f2), f3), f4)
#мы можем использовать следующее сокращение:
#pipeline(unit(x), f1, f2, f3, f4)
def i():
return str(input('Input:'... |
46ae9300e6f5bace52a23c43da9a51625f9ed19a | Rohit-83/DSA | /lcm and hcf.py | 572 | 3.9375 | 4 | #wap to find lcm and hcf
def lcm(num1,num2):
if num1>num2:
greater = num1
else:
greater = num2
while True:
if (greater%num1 == 0) and (greater%num2 == 0):
lcm = greater
break
greater+=1
return lcm
#print(lcm(54,24))
#the above method takes very ... |
ce859cc4f6b43e5c6cb1b8455318a1799510a40e | deepakrawat68/code-snippets | /sum.py | 189 | 4.21875 | 4 | # Python program to print sum of two numbers
num1=input('Enter first number : ')
num2=input('Enter second number : ')
sum = int(num1) + int(num2)
print('Sum of entered numbers is :', sum)
|
7991749d7f4dd91166d2662adf4c929959b7d767 | ajcvictor/file-mgmt | /read_message.py | 271 | 3.984375 | 4 |
file_name = "my_message.txt"
with open(file_name, "r") as file:
contents = file.read()
lines = contents.split("\n") # converts string to list
print("THERE ARE", len(lines), "LINES IN THIS FILE")
for line in lines:
print("LINE:", line)
|
7afc1fba01851dd2e64ff935580eba6b76f4efb2 | viniromao159/converterBinDec | /main.py | 1,629 | 4.25 | 4 | import os
def converter(operation, valor): #<----- Função de conversão
if operation == 1:
result = int(valor, base=2)
return result
else:
valor = int(valor)
return bin(valor)[2:]
os.system('cls') or None # limpeza do terminal
cont = 0
while cont < 1:
# Menu do sistema
... |
fc8a5b78b256c1d2517a41d51e6451ded057183e | mackenziekira/hb_code_challenges | /completed/height_bst.py | 236 | 3.734375 | 4 | def height_bt(node):
"""returns the heigt of a binary tree"""
if not node:
return 0
left_height = 1 + height_bt(node.left)
right_height = 1 + height_bt(node.right)
return max(left_height, right_height) |
310dd10aa41472ee8b2998ba7fd48894eba8b6fa | partrita/biopython | /Section2/045.py | 200 | 3.53125 | 4 | #045.py
from random import randint
arr_lotto = []
for i in range(6):
n = randint(1, 45)
if n not in arr_lotto:
arr_lotto.append(n)
for i in sorted(arr_lotto):
print(i)
|
011838b948339295f91c8b00dcc91d0dd1d203f4 | partrita/biopython | /Section2/008.py | 89 | 3.640625 | 4 | #008.py
num = 5
result = 1
while num > 0:
result *= num
num -= 1
print(result)
|
a8af418b9cff8cb6ee6da6dea287fbd6b8e9034c | mikhael-oo/honey-production-codecademy-project | /honey_production.py | 1,525 | 4.1875 | 4 | # analyze the honey production rate of the country
# import all necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
# import file into a dataframe
df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/l... |
7cabb3d44067c67d5ed50700fa3120ad2277053c | vgates/python_programs | /p010_fibonacci_series.py | 940 | 4.46875 | 4 | # Python program to print first n Fibonacci Numbers.
# The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
# The sequence is characterized by the fact that every number after the
# first two is the sum of the two preceding ones.
# get the user input and store it in the variable n
# int function... |
4b2b1f3eb6ebadc10e0737b8affbfc0351d0e87d | vgates/python_programs | /p015_factorial.py | 1,015 | 4.34375 | 4 | # Python program to find factorial of a number
# Factorial of a number n is the multiplication of all
# integers smaller than or equal to n.
# Example: Factorial of 5 is 5x4x3x2x1 which is 120.
# Here we define a function for calculating the factorial.
# Note: Functions are the re-usable pieces of code which ... |
fbcbaf08bbef3de4a4d96c1fed02e9d6b75e8621 | owenjklan/cahelper | /countries/parse.py | 214 | 3.59375 | 4 | #!/usr/bin/env python3
import csv
with open('all.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print('("{tag}", "{item}", False),'.format(tag=row[1], item=row[0]))
|
a8b41d779258171e0c22cea91701ab267a7d19a3 | accountofI/p4e | /8.4.py | 292 | 3.828125 | 4 | myList = []
fhand = open('romeo.txt')
for line in fhand:
words = line.split() #Splits line into array of words
for word in words:
if word in myList : continue #Discards duplicates
myList.append(word) #Updates the list
print(sorted(myList)) #Alphabetical orderprint(lst) |
b7029e43f6da0c643223c1e6874669665c8e7d87 | YusifGadimaliyev/word_hunter | /automation.py | 1,050 | 3.578125 | 4 | # import sqlite3
# from words import sozler
#
# con = sqlite3.connect("oyun.db")
# kursor = con.cursor()
# con_gamer = sqlite3.connect("gamer.db")
# kursor_gamer = con2.cursor()
# OLMAYAN TABLE'NI ELAVE ETMEK UCUN:
# def create_table_finds():
# kursor.execute("CREATE TABLE IF NOT EXISTS finds(soz TEXT)")
# co... |
8e76de1d36b1329159ba96b3ae0ac83754d6fbfd | SkittlesPlayz/Codecraft-python | /variable addingHOPE.py | 170 | 3.953125 | 4 | print("What is the value of x?")
x = float(raw_input())
x = int(x)
print("What is the value for Y?")
y = float(raw_input())
y = int(y)
xy = x + y
print (xy * xy)
|
4fe985365a3e1d0f0f7096d1bb0cfecc226de99e | mulualem04/ISD-practical-6 | /ISD practical6Q5.py | 562 | 4.0625 | 4 | sentence_1 = input("Enter a sentence: ")
sentence_2 = input("Enter a sentence: ")
# ask for sentence to enter
name = sentence_1 + " " + sentence_2
# concatenating sentences
print(name)
print(name.split())
myList = name.split()
# returns a list of all the words in the sentence
myList.sort()
# Sort items in a list in alp... |
54dfe83ac6ccb3ce1f389d2c3338bc6263583c9a | JazzyServices/jazzy | /uripath.py | 5,241 | 3.5625 | 4 | """
A URI has the following form:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
This module handles the "path" part of a URI
Paths also appear in filesystem (obvs) so this module can handle those as well
UPaths are created by passing a pathname to the constructor:
E.g
pwd = UPath(os.getcwd())
... |
fd73120ca7a5ac32608d0aec17003c45fb9198a0 | JazzyServices/jazzy | /built_ins/slices.py | 1,850 | 4.25 | 4 | # encoding=ascii
"""Demonstrate the use of a slice object in __getitem__.
If the `start` or `stop` members of a slice are strings, then look for
those strings within the phrase and make a substring using the offsets.
If `stop` is a string, include it in the returned substring.
This code is for demonstration purposes ... |
9bfb1c88aa5c76788dd0cd99ce36d9e81585f432 | AymericS96/Python-EDA | /data-visualization/house_pricing.py | 1,015 | 3.765625 | 4 | import pandas as pd
import seaborn as sb
import matplotlib as mpl
import numpy as np
# 2) Donnez la liste des variables présentes dans ce dataset ainsi que leur nature (sont elles qualitatives, quantitatives, discrète etc…) et leur type (float, int, str etc…)
data = pd.read_csv("./data_csv/house_pricing.csv")
data.he... |
ddb1527ca959187aa259651277211dc7b1798229 | chagaleti332/HackerRank | /Practice/Python/Numpy/floor_ceil_and_rint.py | 1,758 | 4.03125 | 4 | """
Question:
floor:
The tool floor returns the floor of the input element-wise.
The floor of x is the largest integer i where i <= x.
import numpy
my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
print numpy.floor(my_array) #[ 1. 2. 3. 4. 5. 6. 7. 8. 9.]
cei... |
12a5c1259f669055442de8ddfb7dfd6245e2bcbf | chagaleti332/HackerRank | /Practice/Python/Collections/namedtuple.py | 2,990 | 4.59375 | 5 | """
Question:
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of
a tuple.
Example:
Code 01
>>> from collections import namedtuple
>>> Point = na... |
24a0e80c3f81577f00b5b2096e4b32992914db5e | chagaleti332/HackerRank | /Practice/Python/Math/integers_come_in_all_sizes.py | 960 | 4.4375 | 4 | """
Question:
Integers in Python can be as big as the bytes in your machine's memory. There is
no limit in size as there is: 2^31 - 1(c++ int) or 2^63 - 1(C++ long long int).
As we know, the result of a^b grows really fast with increasing b.
Let's do some calculations on very large integers.
Task:
Read four num... |
56049a2b6eaef72e1d4381a7f76a1d4cb9800912 | chagaleti332/HackerRank | /Practice/Python/Introduction/python_print.py | 441 | 4.4375 | 4 | """
Question:
Read an integer N.
Without using any string methods, try to print the following:
123....N
Note that "" represents the values in between.
Input Format:
The first line contains an integer N.
Output Format:
Output the answer as explained in the task.
Sample Input:
3
Sample Output:
123
... |
08605343a771a0837e3383972c370a03516db4aa | chagaleti332/HackerRank | /Practice/Python/Sets/set_add.py | 1,440 | 4.5625 | 5 | """
Question:
If we want to add a single element to an existing set, we can use the .add()
operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
Non... |
59e25fa8a6649f0d23deaa9fe33e4df78f674c03 | chagaleti332/HackerRank | /Practice/Python/Introduction/python_loops.py | 458 | 4.1875 | 4 | """
Question:
Task
Read an integer N. For all non-negative integers i < N, print i^2. See the
sample for details.
Input Format:
The first and only line contains the integer, N.
Constraints:
* 1 <= N <= 20
Output Format:
Print N lines, one corresponding to each .
Sample Input:
5
Sample Output:
... |
2d0beaf86a1f65715dbdacdcf07aec623856b6cb | chagaleti332/HackerRank | /Practice/Python/Sets/the_captains_room.py | 1,570 | 4.15625 | 4 | """
Question:
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an
infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was gi... |
4735407294bd47ed69477087a1f628d3426d0cfb | chagaleti332/HackerRank | /Practice/Python/RegexAndParsing/group_groups_groupdict.py | 2,019 | 4.4375 | 4 | """
Question:
* group()
A group() expression returns one or more subgroups of the match.
Code
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.group(0) # The entire match
'username@hackerrank.com'
>>> m.group(1) # The first parenthesized sub... |
6ab8e6e334434326b8d52145366e35ac535e8dd9 | chagaleti332/HackerRank | /Practice/Python/BasicDataTypes/lists.py | 1,968 | 4.34375 | 4 | """
Question:
Consider a list (list = []). You can perform the following commands:
* insert i e: Insert integer e at position i.
* print: Print the list.
* remove e: Delete the first occurrence of integer e.
* append e: Insert integer e at the end of the list.
* sort: Sort the list.
* pop: Pop ... |
6690b31000e29c6594ef232016582ba250556526 | muratdemiray/python-education-v2 | /homework/MuratDemiray_homework_day_2.py | 490 | 3.921875 | 4 | # Murat Demiray
list = [1,2,3,4,5,'Malcom in the Middle','a','b','c','d','e']
l = len(list) #length of list
if l % 2 == 0 : # equal half - if you remove middle this will work
first = list[0:int(l/2)]
second = list[int(l/2):l]
list = second + first
else: # not equal half - this works when ther... |
fae9557bf5e212348bd899524ebf39a08a6d49e0 | HarisHad2/Pairprogramming1 | /Index_of_capletter.py | 159 | 3.953125 | 4 | def index_of_caps(word):
yy = []
for i in word:
if i.isupper():
word.index.append(i)
return yy
print(index_of_caps("eDaBiT"))
|
2485b5649e9e3f5359fe6d1a171ecf46066856b4 | kilicsedat/LeetCode-Solutions | /0079. Word Search.py | 900 | 4.03125 | 4 |
# coding: utf-8
# # Word Search
# Medium
#
# Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
#
... |
7df46ad2a941be596a42e01b88b5da4bcefcc756 | 13226617889/Neaten | /Desktop_finishing.py | 5,771 | 3.65625 | 4 | """
1.获取路径目录信息
2.写判定条件,条件符合,创建目录,移动符合条件的文件进目录,并以后缀名分类 # 完成
3.写UI界面
4.实现,word,excel,ppt,图片等,视频,txt,画图软件,python文件,psd模板(PS)
"""
##os.rmdir(splitext[1:])#删除空目录
import sys
import os
import shutil
#b = os.self.Path.absself.Path(os.curdir) #获取现在的绝对路径
class Neaten:
def __init__(self,list,Path,storePath,N... |
6e3c5e0755b356ae1087811b9ef37ee539d4d523 | sanaAyrml/AICourse98 | /HW7_22.py | 4,430 | 3.703125 | 4 | import gym
import numpy as np
import matplotlib.pyplot as plt
import math
import random
class QLearner:
def ns(self, num, p):
return int(round(self.env.observation_space.high[num] - self.env.observation_space.low[num] * p + 1))
def __init__(self, learning, discount):
# Import and initialize M... |
ee963b1b5adfaa7d4f222820c9a2829130667f2b | DragosSHD/Python_Atelierul_Digital | /course6_main.py | 992 | 3.59375 | 4 | # Tkinter Side
import tkinter
from course6_fields import Field
def save_grade(firstname, lastname, email, subject_name, grade):
print(firstname, lastname, email, subject_name, grade)
window = tkinter.Tk()
window.mainloop()
window.geometry('800x600')
window.title('Custom title')
inner_frame = tkinter.Frame(win... |
6893900977a3dfefe78b7f09c150561336d2d26f | Mrudula09/unscramble | /code.py | 1,790 | 3.796875 | 4 | import time
import itertools
import inspect
import os
def meaning_full_words(word,size_of_words):
starting_time=time.time()
#Opening dict_words.txt file.
dictionary = open_input_file("dictionary.txt", 'r')
#Getting the words as set.
words = set(map("".join, itertools.permutations(word,size_of_word... |
f42c8e60bef26e34041aed2a854b5838a2217665 | ulloaluis/2048 | /util.py | 7,953 | 3.53125 | 4 | """
Classes, helper functions, and constants for 2048.
"""
import random
import copy
# Valid keyboard actions: note that these were the values
# I observed from using Python's input() function and the
# arrow keys on a Macbook. There are likely more elegant
# solutions to reading keyboard input.
RIGHT = '\x1b[C'
LEF... |
38ed58fa8dd259613fc8bce2480a531cf913cff3 | ArthurPassos16/A-Star | /main.py | 6,959 | 3.890625 | 4 | # Implementando um Algoritmo A* para Resolução de Labirintos
# Arthur Passos, Eduarda Chagas e Gabriel Sousa
# Link do youtube: https://youtu.be/tYSYfbRMIRs
#
# Imports necessários
import math
import queue
# Limites do ambiente
bound_x = 15
bound_y = 15
###############################################################... |
b86d09f772688e692c6e459d015a922d67f663d3 | vivek1376/leetcode | /nonadjacentsum_max.py | 436 | 3.953125 | 4 | #!/usr/bin/env python3
def calcMax(list):
max1 = max2 = temp = 0
for num in reversed(list):
#print("=========")
#print("num:" + str(num))
temp = max1
if (num + max2 > max1):
max1 = num + max2
else:
max1 = 0 + max1
max2 = temp
... |
513a182b53ec2575a3c050d374e78b4ec0687333 | robot-99/Pong | /main.py | 1,015 | 3.515625 | 4 | from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)
player1 = Paddle((350, 0))
player2 = Paddle((-350, 0))
ball = Ball()
score... |
e06fba0be1d8bab1efbc6e671f19ac867b9f3fa7 | khidmike/learning | /Python/gregorian.py | 302 | 3.640625 | 4 | # When supplied with a four-digit year, outputs that year's Gregorian epact
def main():
year = int(input("Type in a year in format YYYY to calculate Gregorian epact: "))
C = year // 100
epact = (8 + (C//4) - C + ((8*C + 13) // 25) + 11*(year%19))%30
print(epact)
print()
main()
|
162cd5c5c636f39d116bb3b928b70ce60f1bf25c | khidmike/learning | /Python/caesar.py | 849 | 4.21875 | 4 | # Simple program using a Caesar Cipher to encode / decode text strings
import sys
def main():
print("Welcome to the Caesar Cipher Encoder / Decoder")
print()
coding = str(input("What would you like to do? Type 'e' to encode / 'd' to decode: "))
if (coding != "e") and (coding != "d"):
print("... |
69fb03d6f9a26a2b1633c09ec2b9f72133c40627 | kmenon89/python-practice | /dictionary.py | 1,030 | 4.125 | 4 | #all about dictiionaries
#create
dicti={1:'a',2:'b',3:'c'}
print(dicti)
print(dicti[1])
#append
dicti[4]='d'
print(dicti)
#deletion
del dicti[4]
print(dicti)
#get a value
print(dicti.get(2))
#clear whole dicti
dicti.clear()
print(dicti)
#sort dicti
dicti={2:'a',3:'b',1:'c'}
print(dicti)
order=d... |
39abe353ce29504e04c5d00232e5a41ad49d45b4 | kmenon89/python-practice | /tuple.py | 395 | 3.515625 | 4 | #read tuple ,print details
imelda="more mayhem","Imelda May",2011,((1,"Pulling"),
(2,"psycho"),(3,"Mayhem"),(4,"Kentish"))
print(imelda)
album,artist,year,tracks=imelda
print(album)
print(artist)
print(year)
print(tracks)
print("*"*5)
print(album,artist,year,tracks)
print("*"*5)
for i in tracks:
... |
bf45447e0c258970584c89c445b40d7d84193812 | kmenon89/python-practice | /whileloopchallenge.py | 613 | 4.53125 | 5 | #get the line length ,angle,pen color from user and keep drawing until they give length as 0
#import turtle to draw
import turtle
# declare variables
len=1
angle=0
pcolour="black"
#use while loop
while len != 0 :
#get input from user about length angle and pen colour
len=int(input("welcome to sketch... |
dea48149e44c33fb105b105a52cae1324d503b4c | kmenon89/python-practice | /String1.py | 396 | 3.609375 | 4 | #the string challenge
print("There once was a movie star icon \n who preffered to sleep with the light on"
"\n They learned how to code \n a device that sure glowed \n and lit up the night using Python !")
print("There once was a movie star icon \n who preffered to sleep with the light on \n They learned how t... |
679a164e1ffe6086681b2ec1c990633cadb673ba | kmenon89/python-practice | /fibonacci.py | 929 | 4.1875 | 4 | #fibinacci series
a=0
b=1
#n=int(input("please give the number of fibonacci sequence to be generated:"))
n=int(input("please give the maximum number for fibonacci sequence to be generated:"))
series=[]
series.append(a)
series.append(b)
length=len(series)-1
print(length,series[length])
while len(series)<... |
270154c6daa81202ec74bd427d3c93590131d22c | seth4man/PythonDataPractice | /MemoryChallenge.py | 1,099 | 3.75 | 4 | # Find a way to read in 'ctabus.csv' that makes Python
# much more memory efficient than seen in 'CTABus.py'
#Place each column into a list
#Memory used: 128.8688209 MB (Better than storing in tuples)
#Memory used when also using library for storing dates: 110.97282179999999 MB
import datetime
def read_data(filename):... |
5cc57de0d52b06ee8ffcbea03baa6ad113e03b9b | richard-kessler/data_science | /Development/Simple_Linear_Regression_Housing_Data.py | 4,220 | 3.734375 | 4 | <<<<<<< HEAD
# -*- coding: utf-8 -*-
"""
#Purpose: Simple Linear Regression to evaluate if housing lot area affects a homes sale price.
#Feature Selection Candidates
0 PID
1 Lot_Area
2 House_Style
3 Overall_Qual
4 Overall_Cond
5 Year_Built
6 Heating_QC
7 Central_Air
8 Gr_Liv_Area
9 Bedroom_AbvGr
10 Fireplaces
11 Gara... |
6c120bcb895c4e43032c8a6a7ac686c8c644e9eb | LuciaFresno/facultad | /Microeconomia/1er parcial/ej1.4.py | 1,541 | 3.5 | 4 | """
1.4. Pedro es un consumidor cuyas preferencias están representadas por la Tasa Marginal de Sustitución 𝑇𝑀𝑆 = 2𝑦/x . Si los precios son 𝑃x = 3 y 𝑃y =1, y tiene un ingreso de $ 180,
¿cuál es la canasta de bienes que maximiza su utilidad?
"""
# -*- coding: utf-8 -*-
import sympy as sp
sp.init_printing()
m... |
da36695e4d06ef55c2ff92db0ab7561ce85c86d9 | jels-code/python-ds-algo | /circular_linked_list/circular_linked_list.py | 3,064 | 3.78125 | 4 | import math
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def __iter__(self):
if not self.head:
return
node = self.head.next
head = self.head
yie... |
2eec57774a9a43c8fe101ddacb016550392a62a5 | 0xedb/python-playing | /main.py | 544 | 3.5 | 4 | def func(first, *next, **rest):
print((first))
print((next))
print((rest))
func('a', 332, 32, a=3932, b=3939)
def swapper(x, y):
return lambda z: y, x
another = swapper(10, 11)
print(another)
name = "Bruno"
id = 3937
print(f"{name} ------ {id}")
class Human:
def __init__(self, name):
... |
e8c815f504f17c7909b98324c18d1a9ef3d06c47 | gustavopierre/Introduction_to_Programming_using_Python | /list_demo.py | 986 | 4.125 | 4 | empty_list = list()
print("empty_list ->", empty_list)
list_str = list("hello")
print("list_str ->", list_str)
list_tup = list((1, 2, (3, 5, 7)))
print("list_tup ->", list_tup)
empty_list = []
print("empty_list ->", empty_list)
list_syn = [3, 4, "a", "b"]
print("list_syn ->", list_syn)
print("'a' in list_syn ->", 'a' i... |
1845cadeadd4ea79940a737be598abe41bd0f683 | gustavopierre/Introduction_to_Programming_using_Python | /read_text.py | 921 | 3.71875 | 4 | print('\n*****Iterating over lines******')
with open('pep20.txt') as text_file:
for line in text_file:
print(line, end=" ")
print("\n*********Using read() method********")
with open('pep20.txt', encoding="us") as text_file:
text = text_file.read()
print(text)
print("\n*********Using readlines() method... |
34c3e924f464af3cca47d3f84133503a616c7669 | gustavopierre/Introduction_to_Programming_using_Python | /basic_programs_part1_3.py | 203 | 4 | 4 | num_1 = int(input("Enter first number: "))
num_2 = int(input("Enter second number: "))
quotient = int(num_1/num_2)
print("\nQuotient:", quotient)
reminder = num_1 % num_2
print("Reminder: ", reminder)
|
aff82f990ecdaa6e7ef1f95b665919af1209c1dd | kevinta893/NetworkIt | /NetworkItPi-Python/networkit_template_pi.py | 2,885 | 3.78125 | 4 | from networkit import *
import RPi.GPIO as GPIO
import time
#See wiring diagram for demo setup. This code emulates what Arduino's start code looks like
ledPin = 11
buttonPin = 13
pressed = False
count = 0
network_client = None
def setup():
#setup network
print "Connecting to network..."
global net... |
daa04ed4d5439f5019b086f5ebb524c0be019b5f | Shusovan/Basic-Python-Programming | /Queue.py | 616 | 3.890625 | 4 | lst=[]
def enqueue():
n=input('Enter the elements of Queue: ')
lst.append(n)
menu()
def dequeue():
lst.pop(0)
menu()
def display():
print(lst)
menu()
def menu():
print('\n*****MENU*****')
print('1.Enqueue\n2.Dequeue\n3.Display\n4.Exit')
choice=int(in... |
5b3e23591c57aa7007254eaf7fcaf55da7032b02 | Shusovan/Basic-Python-Programming | /Binary Search.py | 684 | 3.90625 | 4 | def Binary_Search():
arr=[]
a=int(input('Enter the size: '))
for i in range(a):
n=int(input())
arr.append(n)
x=int(input('Enter the key: '))
low=0
high=len(arr)-1
mid=0
while low<=high:
mid=(low+high)//2
if ... |
a0ba598b5d524e97fee7cfd3c04c3a6785573db5 | Shusovan/Basic-Python-Programming | /Compound Interest.py | 281 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
def Compound_Interest():
P=int(input('Enter the principle'))
r=int(input('Enter the rate of interest'))
t=int(input('Enter the time'))
A=P*((1-r/100)**t)
return A
print('Compuond Interest',Compound_Interest())
|
672a259cb1750731a713d6c3bf44d31bf9a33e50 | kmunge/news-highlights | /tests/test_article.py | 537 | 3.53125 | 4 | import unittest
from app.model import Article
class ArticleTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = Article('Kevin Kittony','Big chan... |
506e36fa9d3c3e44136de81d6bd017bdb594d86d | bartkim0426/deliberate-practice | /exercises4programmers/ch02_input_output/python/01_hello.py | 614 | 3.8125 | 4 | '''
psuedocode
get_name
name = get name from standard input
return name
end
concat_hello
set message
Hello, + name, nice to meet you!
return message
end
print_out
print message
end
main
name = get_name
message = concat_hello(name)
print_out(name)
end
'''
def get_name() -> str:
... |
d2015bc58d2c72e4d91ea716ba2cc6cf05f064ec | bartkim0426/deliberate-practice | /exercises4programmers/ch03_operations/python/07_rectangle.py | 1,462 | 4.375 | 4 | '''
pseudocode
get_length_and_width
length: int = int(input("What is the length of the room in feet? "))
width: int = int(input("What is the width of the room in feet? "))
end
calculate_feet_to_meter
squre_meter: float = round(square_feet * 0.09290304, 3)
end
calculate_squre_feet
squre_feet = length ... |
854080b7b8eafc8122602b4bab7a49202f784717 | bartkim0426/deliberate-practice | /exercises4programmers/ch02_input_output/python/03_qutation.py | 848 | 3.9375 | 4 | '''
pseudocode
get_input
get input from stdin
end
print_quotation
quote = get_input('What is the quote? ')
person = get_input('Who said it? ')
message = person + " says, " + "\"" + quote + "\""
print(message)
end
'''
def get_input(question: str) -> str:
'''Get input from stdin with print out... |
fe723e1609062cfc4207a0068da35d45390e9d07 | ereminmax/ISEME | /ex6.py | 323 | 3.625 | 4 | x = "There are %d types of people."%10
binary = "binary"
do_not = "don't"
y= "Those whwo know %s and those who %s."%(binary, do_not)
print x
print y
print "I said: %r"%x
print "I also said: '%s'."%y
hilarious =False
joke_evaluation="Isn't that joke so funny?%r"
print joke_evaluation % hilarious
print "This"+"is one lin... |
3809e8bff3f319a95563c34a799af473a09ca71b | phutthaphong01/-Code | /Testing/Test6.py | 579 | 3.703125 | 4 | #No.11
'''a = int(input())
b = int(input())
c = a+b
print("Addition: %d"%c);print("Concatenation: %s%s"%(a,b))'''
#No.12
'''midterm = float(input("Midterm score : ")) #0<=midterm<=60
final = float(input("Final score: ")) #0<=final<=60
total = midterm + final
aver = (total)/2
print("Total: %.1f"%total);print("Average:... |
83888d1bdc4e2ed6f4cf14728f756bd0091a7636 | phutthaphong01/-Code | /Testing/Test5.py | 242 | 3.84375 | 4 | #Test5 No.1
'''C = float(input("Enter Temp: "))
F = (9/5)*C + 32
K = C + 273.15
print("F:%.2f"%F,"K:%.2f"%K)'''
#No.2
'''width = float(input("Enter width = "))
high = float(input("Enter high = "))
cal = (1/2)*width*high
print("%f"%cal)'''
|
db4e3b325d7041142680a0ceff285d6f7a8fdb39 | brunacarenzi/thunder-code | /maior e menor num..py | 751 | 4.21875 | 4 | # mostrar qual valor é o maior e qual e o menor
print('Olá, por favor teste este esse programa.')
n1 = int(input('Informe o 1º número: '))
n2 = int(input('Informe o 2º número:'))
n3 = int(input('Informe o 3º número:'))
# Verificando o menor número
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 ... |
91ce1227c7ee2803c148909cf6bf59246429fad2 | brunacarenzi/thunder-code | /meses.py | 1,046 | 4.21875 | 4 | '''Escreva o método chamado getMesPorExtenso() que recebe um inteiro,
referente ao mês do ano, um código referente ao idioma (1 para português e 2
para inglês) e retorne o mês por extenso. A tabela a seguir ilustra alguns exemplos.'''
#meses em Português
mesesp = ('zero', 'Janeiro', 'Fevereiro', 'Março', 'Abril... |
a7ec7a303b22b6f9d417dfb1a44ba2271da4ea58 | ljtnono/PearVideoSpider | /BaseParser.py | 1,650 | 3.734375 | 4 | """
爬虫解析器基类定义
"""
from abc import abstractmethod
class BaseParser(object):
"""
爬虫解析器的基类,定义了解析的基本方法
"""
def __init__(self, next=None, level=None, **kwargs):
"""
初始化的时候设置下一个解析器
:param next: 可能为None,如果为None那么说明只有一个解析器
:param kwargs 其他额外的参数
"""
self.nextPar... |
88eef3ed933fd0dfa717a3fd4f4485f9673a00d4 | MichelleMiGG/CVMundo1 | /exercício17.py | 211 | 3.828125 | 4 | # Cateto oposto e adjacente.
co = float(input('Qual o cateto oposto? '))
ca = float(input('Qual o cateto adjacente? '))
h = (co ** 2 + ca ** 2) ** (1/2)
print('O comprimento da hipotenusa é {:.2f}' .format(h))
|
5dd1db0a4355bcced52d8cab859d633f09130251 | MichelleMiGG/CVMundo1 | /exercício06.py | 196 | 3.9375 | 4 | # Dobro, triplo e raiz.
n1 = float(input('Digite um número: '))
d = n1 * 2
t = n1 * 3
r = n1 ** (1/2)
print('O dobro do número {} é {}, seu triplo é {} e sua raiz é {}' .format(n1, d, t, r))
|
79c7dd30ecee6bde01bc0ec8148fa9bb18d65bd2 | MichelleMiGG/CVMundo1 | /exercício31.py | 230 | 3.546875 | 4 | # Viagem.
dist = int(input('Digite a distância da sua viagem em km: '))
if dist <= 200:
pp = dist * 0.50
print('A passagem custará R${}' .format(pp))
else:
ppa = dist * 0.45
print('A pasagem custará R${}' .format(ppa))
|
fb456a01145c04650f707a5af02664c0d7f9eddc | danielbednarz2/hacks | /singleton.py | 4,516 | 4.03125 | 4 | import threading
__all__ = ['Singleton']
class Singleton(object):
"""Classes inheriting from Singleton will be singletons. Only one instance
will ever exist. When creating a second instance, the __init__ method is
replaced to avoid it being run multiple times. The second and later
times an in... |
253cd269b2c35c6ab96639fdd5c4f7b289980495 | paltaa/Tareas-energia | /memoria_coagra.py | 1,147 | 3.5 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import csv
k={}
#leer el archivo csv por fila
with open('Final20102016CSV.csv', 'rU') as csvfile:
readCSV = csv.reader(csvfile)
i=0
for row in readCSV:
k[i]=str(row)
i=i+1
#separar las filas en 4 columnas distintas
for i in xrange(0,len(... |
f3ac0037df5a2ecca66736e8a54739d6b178e093 | Shweta-yadav12/if-else | /calcualator.py | 394 | 4.34375 | 4 |
num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=input("enter the number")
if num3=="+":
print(num1+num2)
elif num3=="-":
print(num1-num2)
elif num3=="*":
print(num1*num2)
elif num3=="/":
print(num1/num2)
elif num3=="%":
print(num1%num2)
elif num3=="**":
print(num... |
10b54abd641ba0c104a753b994dd970f97c83394 | Shweta-yadav12/if-else | /GrinterandnotGrinter.py | 201 | 4.0625 | 4 |
num1=int(input("enter the number"))
num2=int(input("enter the number"))
if num1>num2:
print("it is grinterthan")
elif num1<num2:
print("it is not grinterthan")
else:
print("both are equal |
c866d92bdc37ddb43be957b0843b4b14260371b1 | Shweta-yadav12/if-else | /Perorgrade.py | 188 | 4.03125 | 4 |
per=int(input("enter the marks"))
if per>90:
print("grade is A")
if per>80 and per<=90:
print("grade is B")
if per>60 and per<=80:
print("grade is C")
if per<60:
print("gr |
6abebde29cb324b6f432e518b67e228a422bdc7c | Shweta-yadav12/if-else | /7devisible.py | 122 | 4.0625 | 4 | num=int(input("enter the num"))
if num%7==0:
print("number is devisible")
else:
print("number is not devisible")
|
5592cbeed700f7c8039127e23a71107dfdeb6af3 | Shweta-yadav12/if-else | /Riversno.py | 177 | 3.53125 | 4 |
n=int(input("enter the number"))
x=n%10
y=(n//10)%10
z=((n//10)//10)%10
b=((n//10)//10)//10
a=x*1000+y*100+z*10+b
if a<100000:
print(a)
else:
print("input is wrong")
|
4d11e3882054825b61c2f15d5a7f2e683758d9bb | Arunsunny28180/python1 | /co1/20_remv_even.py | 324 | 4.03125 | 4 | #20_removing even no.
list1=[]
list2=[]
lim=int(input("enter a lim:"))
print("enter the numbers:")
for i in range(lim):
list1.append(int(input()))
print("The list is:",list1)
list2.extend(list1)
for i in list1:
if i%2==0:
list2.remove(i)
print("after removing even numbers:",list2)
# sum
s = sum (list1)
prin... |
16e3ae9fa947b72bcb31158fc28f4203b56176d0 | bnak/interviews | /Whiteboarding/Recursion/recursion.py | 3,305 | 4.1875 | 4 | """
Recursion
---------------------
The Evil Wizard Malloc has attacked you and taken away your ability
to use loops! The only way you can defeat him is by fighting back
using the power of recursion!
Below are function stubs for a variety of functions that are able
to be solved recursively. For this exercise, you a... |
cc9d688abd57fe60de7bf705f0efeedc6e468a86 | bnak/interviews | /skills2/skills2_completed.py | 3,960 | 4.15625 | 4 | string1 = "I do not like green eggs and ham."
list1 = [2, 5, 12, 6, 1, -5, 8, 5, 6, -2, 2, 27]
list2 = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
words = ["I", "do", "not", "like", "green", "eggs", "and", "ham", "I", "do", "not", "like", "them", "Sam", "I", "am"]
"""
Write a function that takes a string and produces a dictio... |
395820b8a58b4c06f7596627135766f023852bc7 | DilaraPOLAT/Algorithm2-python | /2.lab05.03.2020/odev1_asalbolenbul.py | 362 | 3.765625 | 4 | """
kullanici tarafindan girilen sayinin asal bolenlerini bulan ve
ekrana yazdiran pyhton kodu...
"""
sayi=int(input("bir sayi giriniz:"))
asalmi=1
for i in range(2,sayi+1):
asalmi=1
for j in range(2,i):
if(i%j==0):
asalmi=0
break;
if (asalmi == 1):
if(sayi%i==0):
... |
fe290593c81f87f7e51b979d896b3b64a38d0c6d | DilaraPOLAT/Algorithm2-python | /5.Hafta(list,tuple)/venv/ornek2.py | 1,187 | 4.375 | 4 | """
ornek2:
rasgele uretilen bir listenin elemanlarinin frekans degerlerini bulan ve en yuksek frekans
degerine sahip sayiyi gosteren python kodunu yazınız.
"""
import random
randlist=[random.randint(1,100) for i in range(100)]
print(randlist)
freq=[0]*100
max_freq=0
max_num=0
# for num in range(1,100):
# for item... |
f1686d33b784805bbbaa3aef0f06c6e7cccc4cdd | DilaraPOLAT/Algorithm2-python | /2.lab05.03.2020/1. ornek.py | 456 | 3.859375 | 4 | """
kullanicidan alinan vize final notuna gore gecme notunu ve harfi hesplayan program
"""
vizenotu=int(input("vize notu giriniz:"))
finalnotu=int(input("final notu giriniz:"))
donemsonunotu=vizenotu*0.4+finalnotu*0.6
harfnotu=""
if(donemsonunotu<=30):
harfnotu="FF"
elif(donemsonunotu<=60):
harfnotu="CC"
elif(d... |
e4fa51b06c1e12b3a0b6f850b65bca27aaa1826d | MayorofRapture/curly-waffle | /PlatesRetry3.py | 4,601 | 3.9375 | 4 | import tkinter as tk
from tkinter import Tk
import math
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
#describing the window itself
self.parent.title("Plate Calculator")
... |
e17cfdf3f4c4a13619d54000e4e986cec03b59a5 | Karagul/FinProj | /tools/yearStat.py | 858 | 3.625 | 4 | #!/usr/bin/python
from collections import defaultdict
def read_from_file(input_file):
"""
Returns the file contents in a list.
The EOL character \n is stripped from each line.
"""
msg = 'reading from %s ...' % (input_file)
print msg,
file_data = []
with open(input_file, 'r') as f:
for line in f:
... |
7611bfe13dc8250703af3eb6c2ad7d586fdbf716 | faramarzQ/predicting_topic_based_social_influence | /codes/classes/Scholar.py | 1,307 | 3.609375 | 4 | import os
import json
class Scholar:
"""
Scholar class
"""
def __init__(self, desired_features):
""" init method
Args:
desired_features ([dict]): [deisired feature to extract from data]
"""
self.desired_features = desired_features
self.empty = F... |
109d67ff87920bde71f83e12727a6a3df4a77b99 | filipolszewski/aoc2020 | /day19/solution.py | 508 | 3.609375 | 4 | def pre_process_rules(rules):
swap_done = True
ready_rules = {}
return rules
def is_valid(word, rules, i):
rule_zero = rules[i]
return False
with open("input.txt", 'r') as data:
sections = data.read().split("\n\n")
rules_section = sections[0]
rules = [line.replace("\"",... |
5e2199a08bdf526e29101f6552632de0608e9526 | filipolszewski/aoc2020 | /day24/solution.py | 2,362 | 3.546875 | 4 | from collections import defaultdict
nav_dict = {"0": (0, 1), "1": (1, -1), "2": (-1, 1), "3": (0, -1), "4": (-1, 0), "5": (1, 0)}
def replace(param):
return param.replace("ne", "0").replace("se", "1").replace("nw", "2") \
.replace("sw", "3").replace("w", "4").replace("e", "5")
def get_tile_xy... |
fab22e32e06bbf079bfd0260f50a2005e235df6d | Allegheny-Computer-Science-101-S2021/cmpsc101-s2021-lab1-repo | /starter-code/tracing/analyze2.py | 134 | 3.640625 | 4 | beta = 0
for i in range(0,3):
for j in range(3,6):
while(j > i):
beta += j - i
j -= 1
beta += i + j
print("beta = ",beta)
|
916e859115143ab95b57a3b5e79a8ac6b6d79962 | leesangh92/python | /21.5.7/(21.5.7)practice_64p.py | 1,012 | 3.765625 | 4 | '''
def fun1():
print('fun1 함수입니다.')
def fun2(x):
print(id(x))
for i in range(x):
print('{}번째 fun2 함수 호출'.format(i+1))
def fun3(x, y):
print('{} + {} = {}'.format(x, y, x+y))
def fun4(x, y, z):
print('{} + {} + {} ={}'.format(x, y, z, x+y+z))
return None
def fun5():
... |
cd20f202d1dcaac059fc6f78535394dc728fb77e | cmpickle/python | /classFun.py | 267 | 3.875 | 4 | class person:
def __init__(self, name, age):
self.name = name
self.age = age
def toString(self):
print(self.name + " is " + str(self.age) + " years old.")
def main():
a = person("Shawn", 25)
a.toString()
print(a.name)
if __name__ == "__main__":
main() |
15e69afb33ebd9ac349b0116075d4ac4ffbd7673 | jakezhuyi/COMP321_Assignments | /datastructure_260621270.py | 2,610 | 3.890625 | 4 | from sys import stdin
queue = []
stack = []
pri_queue = []
queue_status = True
stack_status = True
pri_queue_status = True
# checks to see if list is empty
# and if the element matches
def removeTup(line, queue_status, stack_status, pri_queue_status):
tup = line.split()
if(queue_status == True):
if(len(queue) ... |
c7aebbf67d392d3febbb9d2a5a26cdbb9be8378c | hackdou/Python_Sec_Demo | /Tools/GUI转码器/tkinter库用法.py | 865 | 3.765625 | 4 | import tkinter as tk
def main():
string = var_txt1.get()
string = "this is a test: " + string
var_txt2.set(string)
# 定义GUI主体框架
window = tk.Tk()
window.title('转码器')
window.geometry('610x650')
# 定义输入的变量
var_txt1 = tk.StringVar()
var_txt2 = tk.StringVar()
# 设置画布
tk.Label(window, text... |
a64dea16976e233cd3caca11ab784665c10d6625 | Mechanistic/Mexican_Train | /Domino_class.py | 580 | 3.640625 | 4 | #Domino
import itertools
class Domino(object):
"""one domino has 2 numbers"""
def __init__(self, number1, number2):
self.num1 = number1
self.num2 = number2
def get_numbers(self):
return (self.num1, self.num2)
def __repr__(self):
return "%s, %s" % (self.num1,self.num2)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.