blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
16cbc0091c515abe692652ab893ee6516385747a | martincastro1575/python | /8.- Functions/Try yourself/8.4 LargeShirts.py | 318 | 3.640625 | 4 | def make_shirt(size, msg_printed = 'I love Python'):
'''Display information about sise a msg of the t-shirt'''
print(f"\nThe tshirt's size is: {size.upper()}")
print(f"\nThe tshirt's message is: {msg_printed.title()}")
make_shirt('l')
make_shirt('m')
make_shirt(size = "s", msg_printed = "I am happy!!!") |
ec1475fe1db63622502e55ec26c0747e106c2c15 | xiangcao/Leetcode | /Python_leetcode/84_largest_rectangle_histogram.py | 936 | 3.859375 | 4 | """
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
"""
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
... |
d741758100c657a58c3e65aacb9b9df9ce4c236e | Ninjak0/100-Days-of-Code-with-Python | /Days/04-06_Collections/Day4.py | 2,297 | 4.09375 | 4 | from collections import namedtuple, defaultdict, Counter, deque
import random
# --Practice using namedtuples--
User = namedtuple("User", "name role weapon")
bobby = User(name="Bobby", role="Rogue", weapon="Dirk")
# Using F-String (fun and easy to read!)
print(f"{bobby.name} is a {bobby.role} that uses a {bobby.... |
6e0c1c3f72c3c934255f0ccd1838ef63762f1f0b | TMJUSTNOW/Master-Degree-Diary | /Kernel Methods/Kaggle Data Challenge Code/fisher_vector.py | 3,423 | 3.578125 | 4 | """
Fisher Vector.
See https://hal.inria.fr/hal-00779493v3/document page 14 algorithm 1 for more details.
"""
import numpy
from gamma import gamma
from gmm import Gmm
class FisherVector:
"""
nclasses: number of classes (assumed between 0 and nclasses - 1)
dim: dimension of the space in which the data liv... |
02db122c5534bc19e94e77980dfac1a8aa02ac15 | DarkShadow4/Python | /files and exceptions/exceptions/examples/exceptions.py | 2,817 | 4.0625 | 4 | #### #### #### #### EXCEPTIONS #### #### #### ####
#### #### COMMON EXCEPTION OBJECTS #### ####
# ZeroDivisionError
# FileNotFound
#### #### USING TRY-EXCEPT BLOCKS #### ####
#### EXAMPLE 1 (TRY-EXCEPT) ####
try:
print(5/0)
except ZeroDivisionError:
print "infinite"
#### EXAMPLE 2 (TRY-EXC... |
e627600c30cac4b34bb9365c5a3d7bda9b5a2e9b | Redwoods87/CS167 | /mystery.py | 1,053 | 3.96875 | 4 | """
Author username(s): johnsoam
Date: 10/24/16
Assignment/problem number: Exam 2
Assignment/problem title: Decoding code
"""
def commonChars (stringOne, stringTwo):
"""
Finds the common characters at the beginnings of two strings.
Parameters:
stringOne: a string
stringTwo: a second s... |
7c89845c07cd2eca76b8da739f9954f1f92820ef | sarahDH615/python_challenge | /PyPoll/main.py | 5,164 | 4.15625 | 4 | import os
import csv
#setting empty list for holding votes/candidate names
votes = []
#path for csv file
csvpath = os.path.join("Resources", "election_data.csv")
#opening csv file w/ reader
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
#for loop for collecting the votes/cand... |
5f179f26b3439db5a374e666244392d7567d2c40 | waacher/xor | /toHex.py | 366 | 3.765625 | 4 | import codecs
import base64
def ascii_to_hex(text):
return ''.join('{0:02x}'.format(ord(c)) for c in text)
def base64_to_hex(x):
return codecs.encode(codecs.decode( bytes(x, 'utf-8'), 'base64'), 'hex').decode().rstrip() # python 3?
if __name__ == '__main__':
print(ascii_to_hex("Hello World"))
print(b... |
649115e9182a90f44b0393707b84db439a83e562 | felipegruoso/dojos | /12_leap_year/leap_year.py | 633 | 3.6875 | 4 | def is_leap_year(number):
return divided_by_four(number) and (not divided_by_one_hundred(number) or divided_by_four_hundred(number))
def divided_by_four(number):
return divided_by(number, 4)
def divided_by_one_hundred(number):
return divided_by(number, 100)
def divided_by_four_hundred(number):
return... |
68818947cf6ddf59141b09370bbb332a9c00ac73 | sampsonliao/cst311.TCP.CliServ | /PA2Server_Liao_Ochoa.py | 2,021 | 3.796875 | 4 | #server.py
#In this program we are using threads because we are receiving two messages
#from two clients. We have to send back an acknolegment of who sent a message
#first. If we did not implement threads this program will not determine who
#sent the first message but instead it would determine who connected first.
imp... |
fceb0d965cbb24710afe372b17519e253dcd7ad2 | RSreeCharitha/dsa | /py/sll.py | 2,790 | 3.921875 | 4 | #!/bin/env python3
class Node:
def __init__(self, data):
self.data=data
self.next=None
class sll:
def __init__(self):
self.head=None
def __len__(self):
last = self.head
count =0
while True:
if last is None:
break
count... |
9aa26150dc87cf8a949bf011cd04589a86847078 | harounixo/GOMYCODE | /check-point 3.py | 849 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[20]:
def test(items):
tot = 1
for i in items:
tot=i*tot
return tot
print (test([2,3,6]))
# In[28]:
def test(elem):
return elem[1]
liste = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
liste.sort(key=test)
print (liste)
# In[59]:
d1... |
faaa222667fc52b7e716fdf5d7b071b218509bf9 | bommankondapraveenkumar/PYWORK | /code52.py | 623 | 3.859375 | 4 | import math
def lettergrade():
while True:
G=input("enter the grade:")
L=int(G[0])
D=G[1]
S=int(G[2])
print(f"{L}{D}{S}")
if(L==4):
if(S==0):
print("A+")
elif(L==3 and S==7):
print("A")
elif(L==3):
if(S==3):
print("B+")
elif(S==0):
print("B")
elif(L==2 and S=... |
9e01f557ddc5e4d0cfd965efeb3d911628b1baf4 | RahulChowdaryN/Cracking-The-Coding-Interivew-Solutions | /LinkedLists/2.5_sum_lists.py | 2,218 | 4.125 | 4 | import unittest
class Node:
def __init__(self,value):
self.val = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_elements(self,value):
new_node = Node(value)
current = self.head
if current is None:
self.h... |
b5f2e33450c0e97e4febe9c5266944abad146c30 | SakamotoMari/UCDV_Practice | /networks/matrix_to_gv.py | 2,323 | 3.921875 | 4 | # coding:utf-8
import pandas as pd
import sys
# we load the data into a dataframe
collaborations_df = pd.read_csv('selected.csv', encoding='utf-8', header=0, index_col=0)
# the first thing we need to write is this:
initial_sting = "graph {"
# so we print it out
print(initial_sting)
# iterate over the rows of the d... |
afc076392167e38940e20c786b314e3a87914fa9 | Aasthaengg/IBMdataset | /Python_codes/p02887/s992034776.py | 106 | 3.546875 | 4 | import itertools
a=int(input())
b=input()
list2 = [k for k, v in itertools.groupby(b)]
print(len(list2))
|
d303f3371b567ebe5d2198547d7e73f7d8594263 | cuonngo/CS161---Intro-Program-Prob-Solving | /Hw1/echoextreme.py | 276 | 3.953125 | 4 | # Copyright (c) 2011 Cuong Ngo
# Input a string and output in yelling.
response = input("Yell something: ")
upper = response.upper()
lower = response.lower()
yell = (upper + "!!!1!")
yell1 = (lower + "!\".'..")
print(yell, yell1)
input("\n\nPress enter key to exit.")
|
8e782432f5001595d56ff197fd1a53eecf24b432 | blacktyger/epicradar | /mining/validator.py | 2,055 | 3.5625 | 4 | import datetime
class Field:
def __init__(self, name, request, type='string', init_value=None,
value=None, p=False):
self.name = name
self.type = type
self.request = request
self.p = p
self.init_value = init_value
self.value = value
self.pro... |
4a4044902868430bcd3c96d1acf7952acb9614f2 | jaredparmer/ThinkPythonRepo | /birthday.py | 716 | 3.59375 | 4 | import random
from list_fns import has_duplicates
def random_sample(sample_size):
t = []
for i in range(sample_size):
x = random.randint(1, 365)
t.append(x)
return t
def simulation(num_simulations, sample_size):
count = 0
for i in range(num_simulations):
t = random_sample(s... |
0ebbf6491dec4690c9a20636cef3d94874319b02 | emma-wall/election-analysis | /PyPoll.py | 3,315 | 3.890625 | 4 | import csv
import os
# Retrieve data
#Assign a variable for the file to loan and the path
file_to_load = os.path.join("Resources", "election_results.csv")
#Assign a variable to save the file to a path
file_to_save = os.path.join("Analysis","election_analysis.txt")
#Initialize votes variable (has to be before open beca... |
2c14c82d061eb7906594dbab189a30a2f7179ba5 | Dmitrii2020/DataScience | /Python_1.py | 1,794 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# Для тройки ближайших значений определить является ли цифра посередине больше левого значения и меньше правого значения
# In[38]:
get_ipython().run_cell_magic('time', '', "a = [1, 4, 6, 4, 6, 9, 1]\nc = []\ni = 0\nwhile i < len(a) - 2:\n # print(i)\n if a[i] < a[i + 1] a... |
666d54b3852cb2249f2e32130eb46741d2b0e10f | seyidaniels/data-structures-practice | /linkedlist/linkedlist_implementation.py | 3,919 | 4.125 | 4 | class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
def getNode(self, index):
if index > self.length() - 1:
return -1
if self.head != None:
current = self.head
i = 0
... |
7fbc48891ec59ace50ae99ef36204d137cf2fffa | HasheebKazi/algorithms | /sorting/radixsort.py | 3,036 | 3.84375 | 4 | # OLD STYLE INTEGER SORT without lists
# we will sort integers in the range 0 to 10,000
def integer_sort(arr):
# calculate number of buckets needed to sort and allocate them
countingArr = [0]*10001;
# count each integer
for i in range(len(arr)):
countingArr[arr[i]] = countingArr[arr[i]] + 1;
... |
bfce21c427abc6ec6d8ad7f13003178793cee7b3 | Sraj11/Python-Tutorial | /assignment1.py | 1,052 | 4.59375 | 5 | '''Calculating the BMI using the formula weight/height^2'''
weight=int(input('Enter your weight (in kgs)'))
unit_of_height=input("What is your preferred unit of height? Type F for feet and inch and M for meters")
if unit_of_height=='F':
print('You will enter your height given as feet and inches.')
feet=int(i... |
2f17c755ece0ea76c6d17834ce8bf32921fd0ebb | ih64/XRB-phot | /pyraf-2.1.7/lib/pyraf/irafhelp.py | 15,517 | 3.65625 | 4 | """Give help on variables, functions, modules, classes, IRAF tasks,
IRAF packages, etc.
- help() with no arguments will list all the defined variables.
- help("taskname") or help(IrafTaskObject) display the IRAF help for the task
- help("taskname",html=1) or help(IrafTaskObject,html=1) will direct a browser
to displ... |
453a9786c33f147dfc62bf10af2c6d100aee13c6 | NagaTaku/atcoder_abc_edition | /ABC056/a.py | 147 | 3.609375 | 4 | a, b = input().split()
if a == 'H':
ans = b
elif a == 'D':
if b == 'H':
ans = 'D'
elif b == 'D':
ans = 'H'
print(ans) |
76e8937298a10222e8a6714f039a6f444b806656 | ChangxingJiang/LeetCode | /1101-1200/1137/1137_Python_1.py | 354 | 3.65625 | 4 | class Solution:
def tribonacci(self, n: int) -> int:
ans = [0, 1, 1]
for i in range(3, n + 1):
ans.append(ans[-3] + ans[-2] + ans[-1])
return ans[n]
if __name__ == "__main__":
print(Solution().tribonacci(n=0)) # 0
print(Solution().tribonacci(n=4)) # 4
print(Soluti... |
0b4ecacd44bf9dc2e9f6315948db30987a836bcf | nihao-hit/jianzhiOffer | /test21.py | 710 | 3.625 | 4 | '''调整数组顺序使奇数位于偶数前面'''
class Solution:
@classmethod
def isEven(cls,num):
'''
:type num:int
:rtype:bool
'''
return num%2 == 0
def oddEven(self,nums,fn):
'''
:type nums:list[int]
:rtype:list[int]
'''
def swap(nums,l,r):
... |
73f9180b49009c4a52be068f633f177124ec4c97 | parthu12/DataScience | /daily practise/try.py | 206 | 3.890625 | 4 | a=int(input('enter a num'))
try:
if a>4:
print('>4')
else:
print('<4')
except valueerror:
print('value in digit')
finally:
print('success')
|
80ca68835d93968cfbec2b8eebb2a23e90379364 | Elegant-Smile/PythonDailyQuestion | /Answer/ken/20190610_find_first_no_repeat.py | 510 | 3.9375 | 4 | def find_first_no_repeat(my_str: str) -> str:
temp = []
re_temp = []
for ch in my_str:
if ch not in temp:
temp.append(ch)
else:
re_temp.append(ch)
for ch in temp:
if ch not in re_temp:
return ch
if __name__ == '__main__':
string_input = i... |
c433ed8d667fda35b21f192c43ca9bac3cb5f453 | AJ3525/Python-Practice | /practice1.py | 479 | 4.125 | 4 | # print(2**3) # 2^3
# print(5 % 3)
# '''나머지 구하기'''
# print(10 % 3)
# '''1'''
# print(5//3)
# '''몫 구하기'''
# print(10//3)
from random import *
# print(int(random()*10)+1)
# print(int(random()*10)+1)
# print(int(random()*10)+1)
# print(int(random()*45)+1)
# print(int(random()*45)+1)
# print(int(random()*4... |
71504576117659f082c6c93e8591997932411c78 | clovery410/mycode | /python/chapter-1/discuss3-2.2.py | 506 | 3.859375 | 4 | # 2. Using a lambda function, complete the make_offsetter definition so that it returns a function. The new function should take one argument and returns that argument added to some num.
def make_offsetter(num):
"""
Returns a function that takes one argument and returns num + some offset.
>>> x = make_off... |
409494815efadb80445cad1f5ee5e72a283b4178 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0351_0400/LeetCode369_PlusOneLinkedList.py | 958 | 3.609375 | 4 | '''
Created on Mar 29, 2017
@author: MT
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def plusOne(self, head):
if not head: return ListNode(1)
newHead = self.reverse(head)
c... |
cd95b29dd1aab4068b0c4f7501896271ab4b325e | Wartical/Hangman | /Hangman/task/hangman/hangman.py | 2,339 | 3.84375 | 4 | import random
def reveal_attempted_letters(mystery_word, attempted_letters):
revealed_word = ''
for letter in mystery_word:
is_found = attempted_letters.count(letter) > 0
if is_found:
revealed_word += letter
else:
revealed_word += '-'
return revealed_word
... |
7e65090963da9ee72c1dec934f8740812340ae25 | fionnmcguire1/LanguageLearning | /PythonTraining/Solutions/AirportRoutes.py | 1,333 | 3.953125 | 4 |
class Airport(object):
def __init__(self):
self.routeMap = dict()
def addRoute(self,src,dest):
if src in self.routeMap.keys():
self.routeMap[src].append(dest)
else:
self.routeMap[src] = [dest]
def printAllRoutes(self,source,destination,previous_journeys=[... |
da5b5a5c728f54d7b5d2e4ab917ea839d7911c22 | martinleeq/python-100 | /day-08/question-067.py | 719 | 3.84375 | 4 | """
问题67
给定一个排好序的列表,使用二分查找法找到给出的数,打印其位置信息
"""
def binary_search(target, a_list, start, end):
if start == end:
if a_list[start] == target:
return start
else:
return -1
mid = (int)((start + end) / 2)
if a_list[mid] == target:
return mid
elif a_list[mid... |
8e18bf9cc041596acb023cd5d68c0933f432f6cd | hitsumabushi845/Cure_Hack | /addSongInfoToDB.py | 1,167 | 3.65625 | 4 | import sqlite3
from createSpotifyConnection import create_spotify_connection
def add_songinfo_to_db():
db_filename = 'Spotify_PreCure.db'
conn = sqlite3.connect(db_filename)
c = conn.cursor()
spotify = create_spotify_connection()
albumIDs = c.execute('select album_key, name from albums;')
s... |
c9dccda957e0393188b42ef4bb8d0217065cc377 | ganyuanyuan/myLeetCode | /092.ReverseLinkedListII.py | 1,013 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
pre1, p1 = None, head
for _ in range(m-1):
pre1 = p1
p1... |
6d706b1b7fa36db6dde5f0c30d07253428493e33 | xDiesel76/wordapp | /test.py | 200 | 3.65625 | 4 | task_content = input('Word: ')
f = open('words.txt', 'r')
for i in f.read().split():
if len(i) == len(task_content):
print(i)
break
else:
print('no word found') |
7d66872f3d92606ad0b28767f7cd19dda6e193ac | jimgitonga/tic_tac_toe_game | /tic_tack_toe.py | 2,387 | 3.78125 | 4 | board=[" " for i in range(16)]
def print_board():
row1="| {} | | {} | | {} |".format(board[0],board[1],board[2],board[3])
row2="| {} | | {} | | {} |".format(board[4],board[5],board[6],board[7])
row3="| {} | | {} | | {} |".format(board[8],board[9],board[10],board[11])
row4="| {} | |... |
ab821e649f559975327d43a2de74083a10f44e3b | marquesarthur/programming_problems | /interviewbit/interviewbit/arrays/merge_overlapping_intervals.py | 1,119 | 3.890625 | 4 | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @return a list of Interval
def merge(self, intervals):
if intervals is None:
return []
i... |
ff89f23833efde0dbb2f2f04aa90e1b4f139b36c | AmreshSinha/shiny-journey | /Nested Lists Python Hackerrank.py | 1,257 | 3.703125 | 4 | # https://www.hackerrank.com/challenges/nested-list/problem?h_r=next-challenge&h_v=zen
if __name__ == '__main__':
arr = []
arr1 = []
arr2 = []
n = int(input())
# For Making Arrays of [name,score] , [name], [score]
for _ in range(n):
name = str(input())
score = float(input())
... |
a95c761d36b4798714db64fd1aeffc29d0751d15 | shubam-garg/Python-Beginner | /Advanced_Python_2/08_practice_test2.py | 220 | 4.21875 | 4 | name=input("Enter name: ")
marks=int(input("Enter marks: "))
phone_number=int(input("Enter phone number: "))
print("The name of the student is {}, his marks are {} and phone number is {}".format(name,marks,phone_number)) |
d1ac2fe60d6162b9b7933fe489aa019ea91097b8 | marianelacd/Mision_02 | /velocidad.py | 488 | 3.84375 | 4 | # Autor: Marianela Contreeras Domínguez, A01374769
# Descripcion: Programa para calcular la distancia y tiempo que recorre un auto.
# Escribe tu programa después de esta línea.
velocidad = float (input("velocidad (en km/h):"))
distancia1= velocidad*6
distancia2 = velocidad*3.5
tiempo = 485/velocidad
print ("Dist... |
53d28d86511b3d8a1689ca45c90051b4a22e5312 | Jsanzo97/PracticasPDP | /Juego/Juego.py | 31,227 | 3.859375 | 4 | #Autores: Jose Manuel Illan Cuadrado y Jorge sanzo Hernando
#Grupo T3, segunda entrega
#Realizado en Eclipse Mars.2 (4.5.2) en Windows
#Introduccion: El programa consta de 4 clases distintas(una por cada ventana creada) que se iran
#mostrando segun se ejecute, al final del codigo se encuentra el main que efectua ... |
89e05d37607fb3622345df8444b1b02944aa979f | gthank/advent-of-code-2020 | /advent_of_code_2020/d8p2.py | 4,818 | 3.65625 | 4 | """Solver for Day 8, Problem 2 of Advent of Code 2020."""
def load_boot_code():
"""Read the boot code from the assembly dump.
Will return a ``list`` of "instructions", i.e.,
a 3-tuple of ``(instruction_number, opcode, arg)``.
"""
boot_code = []
with open("assembly.txt") as f:
for inst... |
16121bc7d2a3bcc19c0890a774bdbe9bfb3ea686 | jonatan-castaneda/challenges | /ChallengeShapes/Figure.py | 773 | 3.703125 | 4 | from Triangle import Triangle
from Circle import Circle
from Square import Square
class Figure():
def __init__(self, name):
self. name = name
def getFigure(self, name):
if name == "Triangle":
return Triangle()
elif name == "Circle":
return Circle()
elif ... |
8558e26aef86ecbcf2e89b6237ce245eccaf8cd5 | allan-muhwezi/slides | /python/examples/functions/default.py | 282 | 3.578125 | 4 | def prompt(question, retry=3):
while retry > 0:
inp = input('{} ({}): '.format(question, retry))
if inp == 'my secret':
return True
retry -= 1
return False
print(prompt("Type in your password"))
print(prompt("Type in your secret", 1))
|
e3124d703b5f04ab55d0e6beace6d05803439b35 | aucan/LeetCode-problems | /14.LongestCommonPrefix.py | 685 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 14:17:10 2020
@author: nenad
"""
# Time: O(n * min(len(all words)))
class Solution:
def longestCommonPrefix(self, strs) -> str:
if len(strs) == 0:
return ""
i = 0
minLen = len(min(strs, key=len))
f... |
1d31e401cacd30ee6a2f7d85794d04fb960ffc05 | leandrotominay/pythonaprendizado | /aula12/gerenciadorPagamentos.py | 1,156 | 3.921875 | 4 | # Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de
# pagamento
# À vista dinheiro ou cheque: 10% de desconto.
# À vista no cartão: 5% de desconto.
# em até 2x no cartão: preço normal.
# 3x ou mais no cartão: 20% de juros.
print("Seja bem-vindo à Loja \033... |
9d4c978ba94a4b77f241c7cc118c2fdfa0ee990e | monpro/algorithm | /src/contest/166/group-the-people-given-the-group-size-they-belong-to.py | 899 | 3.609375 | 4 | import collections
class Solution:
def groupThePeople(self, groupSizes):
group = collections.defaultdict(list)
n = len(groupSizes)
for i in range(n):
group[groupSizes[i]].append(i)
result = []
for key in group:
indexes = group[key]
for i in... |
522f42a614665c9075debdff7f16d2b4486a4773 | Aasthaengg/IBMdataset | /Python_codes/p03227/s623633246.py | 55 | 3.515625 | 4 | S = input()
print(S) if len(S) == 2 else print(S[::-1]) |
58c900a6dbfb6130a4f7bad50a06b2a5d030b8f3 | MasonCLipford/Programs | /bfs_no_path_no_graph.py | 3,634 | 3.734375 | 4 | # This is an alternate approach to the word ladders problem that does not
# explicitly create a graph. Instead, when we need the children of a node,
# we generate them right then. This is a little faster than the other way that
# creates a graph because it avoids setting up the entire graph at the start
# (includ... |
4e5e241437f76a043ed6deb2efbcd143cc94b4a3 | rnayan78/Hackerrank-Data-Structure-Solution | /sparse Arrays.py | 1,803 | 4.21875 | 4 | """
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings.
For example, given input and , we find instances of ', of '' and of ''. For each query, we add an element to our return array, .
Function Descriptio... |
2287cc941b4798589932e8fda8ea02b9e4f0803f | rajat3105/Algorithms | /babylonian.py | 268 | 4.1875 | 4 | def root(n):
x=n
y=1
e=0.001 # e difines the accuracy level
while(x-y>e):
x=(x+y)/2
y=n/x
return x
n= int(input("Enter the number whose square root you need to found : "))
print("Root is: ", round(root(n),3))
|
2fbfb1530e1681a72b7f8f9104f38abdce9aeb4d | chinaylssly/fluent-python | /descriptor/LineItem_descriptor1.py | 1,602 | 4.125 | 4 | # _*_ coding:utf-8 _*_
class Quantity:
##描述符基于协议实现,无需创建子类(无需继承自别的类)
def __init__(self,storage_name):
self.storage_name=storage_name
#Quantity实例有个storage_name属性,这是托管实例中存储值的属性的名称
def __set__(self,instance,value):
##尝试为托管属性赋值时,会调用__set__方法。这里,self是描述符实例(即Lineitem.weight或LineItem.pr... |
2fcebae58c18031e160e850f9201822d355cafd0 | jiecaoc/WorkSample | /SampleWork/sample_AI_ML/utils.py | 709 | 3.625 | 4 | # some common functions and varibles that will be
# shared in different program
import csv
from classes import *
attris = ['Alt', 'Bar', 'Fri', 'Hun', 'Pat', 'Price', 'Rain', 'Res', 'Type', 'Est', 'classification']
def importData(file):
"""
create examples from csv format file
input: file name
output: ... |
9adb8144db01ae96d52cf619df2165b13a4be9c5 | LemonPi/discrete-optimization-notes | /knapsack/assignment/solver.py | 5,436 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
import sys
import statistics
import copy
import time
Item = namedtuple("Item", ['index', 'value', 'weight'])
def greedy(items, capacity):
# order by value density and take in order
value = 0
weight = 0
taken = [0] * len(ite... |
eb39b70cadc61580ecd30570b10281f995307ee2 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/bxsmuh001/question1.py | 866 | 3.859375 | 4 | #Assignment 7, Question 1
#Author: Muhammad Sabir Buxsoo (BXSMUH001)
#Class: CSC1015F 2014
#Date Created: 27/04/2014
#This program is designed to output a list of words
#Pre-condition: Input list of words followed by sentinel "DONE".
#Post-condition: Output number of words in same order without repeating words... |
a68b12872f776cfa3945b9642d475c461b352831 | GustavoCunhaLacerda/URI | /URI/Python/NotacaoCientifica.py | 129 | 3.765625 | 4 | x = input()
if x[0] == '-':
x = float(x)
print("{:.4E}".format(x))
else:
x = float(x)
print("+{:.4E}".format(x))
|
db7a7e234712d1bc0693153e51a601028d629805 | delfi23/CS50x-2021 | /pset6/Mario/mario.py | 600 | 4.03125 | 4 | from cs50 import get_int
# Ask user a height
while True:
h = get_int("Height: ")
# If it is between 1-8 then stop while
if (h >= 1 and h <= 8):
break
# Loop reversed
for i in reversed(range(h)):
for j in range(0, (h*2)+2, 1):
if j != h and j != h + 1:
if i <= j and (i +... |
ba94eab4e4ff1ad915521b661860d97e8e6669c8 | SayanDutta001/Competitive-Programming-Codes | /CodeForces Practice/Dragon__Kana_Quest.py | 473 | 3.53125 | 4 | def dragon(h, a, b):
while(a>0 or b>0):
if(h<=0):
return 'YES'
aspell = (h//2)+10
bspell = h-10
#print(aspell, h)
if(aspell>h):
#print(b, h)
h-=(10*b)
b=0
break
#print(h)
if(a!=0):
a-=1
h = aspell
else:
b-=1
h = bspell
if(h<=0):
... |
e5c3294604f61c6247531e503e0d3fb7b55ed4ac | arpitsomani8/Data-Structures-And-Algorithm-With-Python | /Searching/Binary_Search.py | 564 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Arpit Somani
"""
def binary_search(a,x):
first_pos=0
last_pos=len(a)-1
flag=0 #means element is not been found yet.
count=0
while(first_pos<=last_pos and flag==0):
count+=1
mid=(first_pos+last_pos)//2
if(x==a[mid]):
flag=1
print("Element is present at positi... |
ef262e23e68685cb8f69a09aec6b84bab808e86e | guilhermefsc/Curso-em-V-deo---Python | /Mundo 2/ex048 - soma impares multiplos de tres.py | 179 | 3.796875 | 4 | soma = 0
cont = 0
for a in range(1,501,2):
if a % 3 == 0:
soma += a
cont += 1
print('A soma dos {} valores solicitados é de {}.'.format(cont,soma))
|
628de1a72a1a4bb03bbf99d19ced220dd2875f83 | Lay4U/RTOS_StepByStep | /Python for Secret Agents/0420OS_Code/Chapters/Chapter 5/ch_5_ex_2.py | 676 | 4.34375 | 4 | #!/usr/bin/env python3
"""Python for Secret Agents
Chapter 5 example 2.
Import stats library functions from ch_5_ex_1 module.
Import data acquisition from ch_5_ex_1 module.
Compute some simple descriptive statistics.
"""
from ch_5_ex_1 import mean, mode, median
from ch_5_ex_1 import get_deaths, get_cheese
year_death... |
927330942d6ec5d2fa8bfa9e97ae3f5741cf1120 | rayush7/Big_Data_Algorithms | /Assignment_1_MapReduce/Vector_Vector_Multiplication/generate_data_vv.py | 817 | 3.671875 | 4 | # Generate Two Random Vectors of any size and save #
#them in a file, which will be an
#input to Mapreduce Vector Vector Multiplication Task
# Two Vectors are A and B
import numpy as np
#Randomly Select Size of Vector between 1-10
vector_size = np.random.randint(1,10)
#Writing Result to input file
with open('input.... |
c68811b0585a6963fa25ebf9a41cfa8814384462 | RicardoDedubiani/Aulas-Python | /exe031.py | 376 | 3.953125 | 4 | distancia = float(input('Qual a distancia da viagem? '))
if distancia > 200:
print('A viagem possui mais de 200 km e custará: R${:.2f}'.format(distancia * 0.45))
print('Voce terá um desconto por viajar mais de 200 km')
else:
print('A viagem possui até 200 km e custará: R${:.2f}'.format(distancia * 0.50))
... |
88a0d7583e0e5dd8791d4af8c66291d369404d0c | dheerajgopi/think-python | /Chapter6/is between.py | 209 | 3.984375 | 4 | def compare(x,y):
if x > y:
return 1
if x < y:
return -1
else:
return 0
def is_between(x,y,z):
if x <= y and y <=z:
print 'ok'
else:
print 'not ok'
|
62e81875c87303a39062f7424e46e167947e0404 | dwhall/farc | /tests/test_event.py | 775 | 3.828125 | 4 | #!/usr/bin/env python3
import unittest
import farc
class TestEventEquality(unittest.TestCase):
def test_events_equal(self,):
e1 = farc.Event(0, 0)
e2 = farc.Event(1 - 1, 2 - 2)
# First prove the events are separate objects
self.assertNotEqual(id(e1), id(e2))
# Now prove t... |
c300bc029f2c29445bf2e6a850f95f02cfe19145 | fslo1709/PythonSimpleGames | /fca/exercise4_solution.py | 3,719 | 4.4375 | 4 | """You can add your own words to the guesser, you can
play to guess a random letter, and you can remove words
from the game as well.
"""
import random
maxClues = 3
#Base words:
myList = ["car", "computer", "plane", "lion"]
dict1 = {"car": "It's a type of vehicle", "computer": "It has a screen", ... |
65a0b4f0d45aeb3581cfff35f0102d9795041771 | Rishabhjain-1509/Python | /Python Project/Exmaple.py | 184 | 3.875 | 4 | Ar = list()
num = int(input("Enter the number upto which you want to print = "))
Ar.append(int(0))
Ar.append(int(1))
#for i in range(2,num):
Ar[i] = Ar[i-1] + Ar[i-2]
print(Ar) |
cfbef32a67befb2368f1a823d7dc7880c478610a | MrRooots/Project_Euler | /Problem_42.py | 868 | 3.734375 | 4 | # Функция пдсчета веса слова, получает на вход строку, возвращает ее вес
def name_wight_counter(line):
from string import ascii_uppercase
name_weight = 0
for element in line:
if element in ascii_uppercase:
name_weight += ascii_uppercase.index(element) + 1
return name_weight
... |
abeabf36a043eaf9260a16560c97588a0e2005b3 | BubbleXu/leetcode | /110_balanced_binary_tree/balanced_binary_tree.py | 1,218 | 4.28125 | 4 | # Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as:
# a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
#
# Example 1:
# Given the following tree [3,9,20,null,null,15,7]:
#
# 3
# / \
# 9 20
# ... |
ab04bc27c8cad6ded84189548c03647d867c0404 | raghav74/FSlabprograms | /r1b.py | 345 | 3.53125 | 4 | infile=input("Enter the input file name")
finp=open(infile,'r')
outfile=input("Enter the output file name")
foutp=open(outfile,'w+')
if not finp or not foutp :
print("FATAL ERROR")
exit()
for line in finp:
foutp.write(line.strip()[::-1]+'\n')#to strip any whitespaces from starting and ending of each line
fi... |
6f7aa5ebbeccbd1d24dd24218b06d8827c92e82f | zidaneymar/leetcode | /324.wiggle-sort-ii.py | 1,277 | 3.84375 | 4 | #
# @lc app=leetcode id=324 lang=python3
#
# [324] Wiggle Sort II
#
# https://leetcode.com/problems/wiggle-sort-ii/description/
#
# algorithms
# Medium (27.53%)
# Total Accepted: 54.6K
# Total Submissions: 198.4K
# Testcase Example: '[1,5,1,1,6,4]'
#
# Given an unsorted array nums, reorder it such that nums[0] < nu... |
15cac7bc519a38bc53b3559a977ea29491dc04bb | ChangxingJiang/LeetCode | /0201-0300/0280/0280_Python_1.py | 589 | 3.734375 | 4 | from typing import List
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
bigger = True
for i in range(len(nums) - 1):
if bigger:
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
bigger = False
... |
71aa5daa01507759a8319b792c76f65d15df3039 | chrislucas/hackerrank-10-days-of-statistics | /python/PoissonDistribuition/solution/Tutorial.py | 1,948 | 4.28125 | 4 | '''
https://www.hackerrank.com/challenges/s10-poisson-distribution-1/tutorial
'''
from math import e as E
def fast_exp(b, e):
if e == 0:
return 1
elif e == 1:
return b
elif e < 0:
b, e = 1 / b, -e
acc = 1
while e > 0:
if e & 1 == 1:
acc *= b
b *... |
5f4f631697b87198eff250db931913e0fff2f9dd | tim-dev/kidpython | /raw_input.py | 152 | 3.734375 | 4 | answer = raw_input("What is your name?\n")
print "Hello " + answer
answer = raw_input("How are you?\n")
print "You're " + answer + " huh? I'm doing ok"
|
b4ce0fd7c103fe4b1081b319b46c02074f043073 | schiob/TestingSistemas | /ene-jun-2019/Luis Ornelas/Practica 1/Triangulos_Test.py | 586 | 3.734375 | 4 | import unittest
import Triangulos
class TestTriangulo(unittest.TestCase):
def test_area(self):
test_case = [(1,2,3,"No es un Triangulo"),
(3,3,3,"Triangulo Equilatero"),
(4,4,5,"Triangulo Isosceles"),
(4,3,6,"Triangulo Escaleno"),
... |
06d97db4cdd3b41a9dd99707110e7358d69411bd | braydenOrmann/pythonPractice | /printExtension.py | 263 | 4.46875 | 4 | #Write a Python program to accept a filename from the user and print the extension of that.
print("Enter a file name with its extension: ")
file = input()
count = 0
for i in file:
if i == '.':
break
else:
count += 1
print(file[count+1:])
|
d900d32e50a991d93cd8156f04d001c9c460dbb0 | alessandroseidiinoue/Curso-Em-Video---Python | /Exercicios/Ex027.py | 236 | 4.125 | 4 | nome = str(input('Digite o seu nome completo: ')).strip().upper()
n = nome.split()
print('Muito Prazer em te conheçer {} !'.format(nome))
print('O seu primeiro nome é {}.'.format(n[0]))
print('O seu último nome é {}.'.format(n[-1])) |
3a8fa7e0f9e855786401efcfc59f044bc2021b7d | aman1000/Python-Basic-Codes | /Piggy_Bank.py | 378 | 3.921875 | 4 | print("PIGGYBANK")
print("************************")
a=int(input("Enter no. of rs.10 coins:"))
b=int(10*a)
c=int(input("Enter no. of rs. 5 coins:"))
d=int(5*c)
e=int(input("Enter no. of rs. 2 coins:"))
f=int(2*e)
g=int(input("Enter no. of rs. 1 coins:"))
h=int(1*g)
Total=int(b)+int(d)+int(f)+int(h)
print("To... |
91638cc1df6c81d5eee6a794031e6e6f69a5c76e | Jesuisjavert/Algorithm | /dfs_bfs_definition.py | 1,245 | 3.765625 | 4 | def dfs(graph, start_node):
visit = list()
stack = list()
stack.append(start_node)
visit[start_node] = True
while stack:
node = stack.pop()
if node not in visit:
visit.append(node)
stack.extend(graph[node])
return visit
def bfs(graph,... |
9b2e84f07e46eb5868005beb8b24862af1c72457 | zyracuze/python-tdd-pig-game | /test_game.py | 268 | 3.5 | 4 | from unittest import TestCase
import game
class GameTest(TestCase) :
def test_join(self) :
"""Player may join a game og Pig"""
pig = game.Pig('Player A','Player B','Player C')
self.assertEqual(pig.get_players(), ('Player A','Player B','Player C'))
|
644adb7d69ac25e9e72334e41276bf3923e9feda | cognizant1503/Assignments | /Data Structures/day1/day2/Assignment9.py | 811 | 4 | 4 | #DSA-Assgn-9
#This assignment needs DataStructures.py file in your package, you can get it from resources page
from day2.DataStructures import LinkedList
def reverse_linkedlist(reverse_list):
temp=reverse_list.get_head()
list1=[]
while temp!=None:
list1.append(temp.get_data())
... |
ec99888c4dfeeddf3dd53833ac2f4d6fa09d115c | jnthmota/ParadigmasProg | /Exercicio7/Ex6.py | 509 | 4 | 4 | # Defina a função todosnimpares que recebe como argumento uma lista de
# números inteiros o e devolve True se o contém apenas números ímpares e False
# em caso contrário.
# Ex: todosnimpares ([1,3,5,7]) = True
# Ex: todosnimpares ([]) = True
# Ex: todosnimpares ([1,2,3,4,5]) = False
todosnimpares = lambda list: True ... |
b91bc953bd6ffd614ac4fe85666bb3028a96560f | Eleanorica/hackerman-thebegining | /proj04_lists/proj04.py | 3,683 | 4.25 | 4 | # coding=utf-8
# Name:
# Date:
# var = []
# var2 = [1, 2, 3, 4]
# var3 = ["a", "b", "cat", 3]
# index- 0 indexed
# one item
# print var3[2]
# slice of list
# print var2[0:2]
# all but first item
# print var3[1:]
# all but last item
# print var3[:-1]
# replace
# var2[0] = "man"
# print var2
# loop
# to change
# cou... |
78fc668cf9e9d45352e505eff35bd43ba5dbb7d2 | dev-arthur-g20r/how-to-code-together-using-python | /How to Code Together using Python/PYC/palindromic.py | 493 | 3.828125 | 4 | import os
class PalindromicNumber:
def __init__(self,n):
self.n = n
def isPalindromic(self):
copy = self.n
sum = 0
while (copy > 0):
remainder = copy % 10
sum = (sum * 10) + remainder
copy = copy // 10
if (sum == self.n):
return "{} is palindromic.".format(self.n)
else:
return "{} is not p... |
4d582073f159d6aac96f6258923b15e213e9bab2 | KhaledSharif/rubiks-encrypt | /encrypt.py | 1,083 | 3.578125 | 4 | import move
def encrypt(cube, moves):
for rotation in moves:
if rotation.type == move.Move.rotation_row:
cube.rotate_row(rotation.row_or_column, rotation.times)
elif rotation.type == move.Move.rotation_column:
cube.rotate_column(rotation.row_or_column, rotation.times)
... |
cb159ceead8879263f36cbf126cbb55d915d2140 | erickapsilva1/desafios-python3-cev | /Desafios/020.py | 366 | 3.90625 | 4 | '''
O professor quer sortear a ordem de apresentação de trabalhos.
Programa que leia o nome dos alunos e mostre a ordem.
'''
import random
alunos = [input('Aluno 1: '),input('Aluno 2: '),input('Aluno 3: '),input('Aluno 4: ')]
print('Ordem sorteada: ')
for i in range(len(alunos)):
escolha = random.choice(alunos)
... |
fc7aa2e8f4c72ff22f77d9a71a8363c0f3cb5903 | reshmaladi/Python | /Pattern/Inverted_right_angle/With_fixed_digits_decre.py | 204 | 3.9375 | 4 | #!C:\Python34
if __name__ == "__main__":
n =int(input("Enter the numer of rows:"))
for i in range(n+1):
print ((str(n -i ) + " " ) * (n-i))
print ()
'''
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
''' |
671e2196a9b74f867a828fe9a626009e58d5bead | gdribeiro/python-for-informatics-exercices | /ch-7-files/teste.txt | 591 | 4.15625 | 4 | #!/bin/python
# Chapter 7 - Files
# Open the file handler
fhand = open('teste.txt')
# print 'File Type: '
# print type(fhand)
# print 'Filehandler information with dir(): '
# print dir(fhand)
# print 'So far so good...'
#
# count = 0
# for line in fhand:
# count = count + 1
# print line
# print 'Line count:',... |
f841cdfb31ecbe45b362d2c76e5c54de0b75efb7 | hanjiwon1/Algorithm | /baekjoon/python_basic/다이얼.py | 368 | 3.625 | 4 | word = input()
number_dict = {'2': 'ABC', '3': 'DEF', '4': 'GHI', '5': 'JKL',
'6': 'MNO', '7': 'PQRS', '8': 'TUV', '9': 'WXYZ'}
number = ''
for i in word:
for j in range(2, 10):
alpha = number_dict[str(j)]
if alpha.count(i) == 1:
number += str(j)
break
sum = 0
... |
f305bc4364dafda51e91296e2ec2db5fc1e9f207 | mamachanko/2048 | /p2048.py | 5,068 | 3.65625 | 4 | from functools import partial
import random
class GameOverException(Exception):
def __init__(self, board):
self.score = board.score
def board_move(move_func):
def wrapper(*args, **kwargs):
board = args[0]
board.move_count += 1
board_state_before = board.serialize()
r... |
2d5052f6bd4c954274d0b03946fa45abea144af7 | deansx/coding-tests | /replace-words/python/replace-words.py | 6,622 | 3.984375 | 4 | #!/usr/bin/env python
"""replace-words.py is the main executable module for the coding test that
demonstrates simple minded tokenization and some simple data structures.
Process a given sentence into single "word" tokens that can be checked
against a list of many-to-one word maps to see whether any words i... |
1d05f7e14f1f2b553a488a1f8a9b25a75ae4ba1b | AhhhHmmm/MITx-6.00.1x | /Week 3/Hangman/hangmanGuided.py | 3,945 | 4.15625 | 4 | import string
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed,
False otherwise
'''
guessed = True
for letter in secretW... |
541ccf5b5a98eb6f2615edfa0500afd122b8a252 | akshaygoregaonkar/Interview_prep | /Frontend/Genral/tempCodeRunnerFile.py | 298 | 3.65625 | 4 |
# from datetime import datetime,timedelta
# def test(n):
# current=datetime.now()
# delta=timedelta(days=1)
# count=0
# while count<n:
# current+=delta
# count+1
# yield current
# result=test(10)
# for i in result:
# print(i)
|
61eaefd301ee9cb24337e90026ebc7994ddc4b9f | fujunguo/learning_python | /old_boy_exercises/week4/fib.py | 330 | 3.84375 | 4 | # __author__: William Kwok
def fib(m):
n, a, b = 0, 0, 1
while n < m:
yield b # 返回生成器对象
a, b = b, a + b # t = (b, a+b) a = t[0] b = t[1]
n = n + 1
return "Done."
g = fib(20)
while True:
try:
x = next(g)
print("g: ", x)
except StopIteration as e:
print("Generator returns value: ", e.value)
break
... |
51c4f09686dfc3e7b2cf59a1a549ba5ac1fb7806 | shijietopkek/cpy5p1 | /q1_fahrenheit_to_celsius.py | 268 | 4.25 | 4 | # q1_fahrenheit_to_celsius.py
# Fahrenheit to Celsius converter
# get input
Fahrenheit = float(input("Enter Fahrenheit temperature: "))
# convert temperature
celsius = (5/9) * (Fahrenheit - 32)
# output result
print("temperature in celsius is", celsius)
|
67960694089ae68c47fd872c036f4f8c7c17beac | TarunSaravagi/Test | /Class.py | 1,855 | 3.84375 | 4 | #Parent Class
class Student :
' this is commented'
count =0
def __init__ (self,name,roll):
self.name= name
self.roll= roll
Student.count += 1
def display (self):
print ("This is the basic class program:" ,self.name, " roll:" ,self.roll,
" \n also " ,self.count)
#Child Class
class Developer (S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.