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 |
|---|---|---|---|---|---|---|
18be03b37b4c9fce720ca3e9618e03368e35ecee | dpoulomi/PythonPractice | /python_practice/coin_change_problem.py | 527 | 3.65625 | 4 | def numberOfWays(coins, total , count):
if(total == 0):
return 1
if(total < 0):
return 0
if(total >= 1 and count <= 0):
return 0
return numberOfWays(coins, total , count - 1) + numberOfWays(coins, total - coins[count - 1] , count)
if __name__ == '__main__':
coins = [2,5,3 ,... |
63289f308a02a6e832363bc64e914754aa5fd913 | dpoulomi/PythonPractice | /python_practice/cutting_rod_dynammic_programming.py | 895 | 3.75 | 4 | import sys
def best_price(price_list, rod_length):
best_price_for_length = [0] * rod_length
best_price_for_length[0] = price_list[0]
#best_price_for_length[1] = max(price_list[0] * 2, price_list[1])
for i in range(1, rod_length):
max_value = - sys.maxsize - 1
for k in range(0, i):
... |
aacfd35d34a58ca5107c4a4d5476df68e07d2492 | dpoulomi/PythonPractice | /python_practice/remove_duplicates.py | 778 | 3.515625 | 4 | def removeDuplicates(givenString):
hash = [0] * 256
fastIndicator = 0
finalIndicator = 0
temp = ''
processedString = convertToMutableString(givenString)
while(fastIndicator != len(processedString)):
temp = processedString[fastIndicator]
if (hash[ord(temp)] == 0):
hash... |
95253d909656df9450edc1dbd6b30968a2ad00fb | ak-b/leetcode | /trees/longest_matrix.py | 1,315 | 3.796875 | 4 | '''
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
'''
class Solution:
def longestIncreasingPath(self, matrix):
... |
2d6bc7d97af812fdbfd45f7e1c548b21f5d68842 | ak-b/leetcode | /dynamic_prog/coin_change.py | 973 | 3.84375 | 4 | '''
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount.
If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of ea... |
3b83fdd6acc76034062a8ebe53c8b8041af1418b | ak-b/leetcode | /arrays_strings/backspace_strcmp.py | 906 | 4.03125 | 4 | '''
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
'''
class Solution(object):
def backspaceCompare(self, S, T):
def build(S):
ans = []
... |
9bf70401bcaa74dce101f1e9d9c4a947dc03100d | ak-b/leetcode | /ll/add_two.py | 1,300 | 4 | 4 | '''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit.
Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itse... |
631932ae66ed8659922bdeded275cedb52754462 | ak-b/leetcode | /trees/decoded_string.py | 1,424 | 3.96875 | 4 | '''
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square ... |
402f723a7c5d62d470efc1ce5490268f4eb8b6c5 | ak-b/leetcode | /arrays_strings/meeting_rooms.py | 3,932 | 3.984375 | 4 | '''
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
NOTE: input types have been changed on April 15, 2019... |
93b02cd749b6663155fc215eb2752e0c83263410 | ak-b/leetcode | /mixedbag/minwin_subseq.py | 555 | 3.875 | 4 | '''
Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.
If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
Inpu... |
43ca80f2f33afb78d7d85775c4c4562b7d2f2563 | mfthomps/Labtainers | /labs/users/shared/_system/usr/bin/eggcheck | 598 | 3.609375 | 4 | #!/usr/bin/env python
import os
import sys
if len(sys.argv) != 2:
print('Usage: eggcheck <file>')
exit(0)
fname = os.path.join('/shared_stuff', sys.argv[1])
if not os.path.isfile(fname):
print('No file found at %s' % fname)
exit(1)
with open(fname) as fh:
has_egg = False
newfile = open('/tmp/tm... |
dd969c4c30007fdc331653a96405d49dc3cba4de | KenRishabh/BtechCSE | /in_list.py | 143 | 4.09375 | 4 | fruits = ["mango", "apple", "grapes", "banana", "kiwi"]
if 'apple' in fruits:
print("apple is present ")
else:
print("Not found") |
6a3406efa1504bbc4cd07f4e4e095b371fb87237 | KenRishabh/BtechCSE | /string_immutable.py | 116 | 3.734375 | 4 | #strings are immutable
string= "string"
print(string[1])
New_string = string.replace("t" ,"T")
print(New_string) |
22c6ac87c8e862e2302215f4b108984530df6e3b | KenRishabh/BtechCSE | /assingment_operator.py | 103 | 3.53125 | 4 | name = "Rish"
# name = name + "abh"
name += "abh"
print(name)
age =18
age *= 3
print(age)
|
4970b9e5372223457eacc3d16baf209c62eda42e | Bakhus/MovieProject | /mojo_df_add_features.py | 995 | 3.921875 | 4 | def add_feature(movies_df):
'''
This function adds neccesary features from transformation of other variables
Argument:
movies_df: dataframe of movies info
Return:
movies_df: dataframe of movies info with more features
'''
movies_df['title length'] = movies_df.apply(lambda x: len(x['tit... |
86f105565f377facdcc6fbc4b03478b622069c66 | Bakhus/MovieProject | /create_season_ind.py | 725 | 3.828125 | 4 | def create_season(combined_df):
'''
This function change release_date to date and create season variables based on released date.
'''
combined_df['release_date']=pd.to_datetime(combined_df['release_date'])
def month_to_season(x):
if x.month <=4:
return 'spring'
elif x.mon... |
9141a7a2234a2d7e4f14e3b97b9847e08938b01f | baropsx2/python | /Test.py | 434 | 3.78125 | 4 | # Variables
entero = 528
cadena = "Es cool programar en python"
booleano = True
tupla = 'perro', 25, 10.1, 'gato'
# Pregunta e Impresión de nombre
nombre = input("¿Cuál es tu nombre?")
print("Hola",nombre,"todo funciona adecuadamente")
# Imprime las 4 variables
print("Éste es un número entero = ", entero)
print("Ésta... |
7cd5a470921e7663a69989a5b6321b92a39aef4a | netpaladinx/AttentiveNet | /src/utils/meters.py | 474 | 3.640625 | 4 |
class AverageMeter(object):
def __init__(self, name):
self.name = name
self.reset()
def reset(self):
self.cur = 0.0
self.sum = 0.0
self.cnt = 0
def update(self, val, n=1):
self.cur = val
self.sum += val * n
self.cnt += n
def __str__(sel... |
680703382eef413d71f6235859c869d406c78454 | frizma/groupArrayElements | /arrayElements.py | 770 | 3.875 | 4 | from math import ceil
def groupArrayElements(arrayElements,n):
try:
listItemCount=ceil(len(arrayElements)/n) #number of items in final lists
return [arrayElements[i:i+listItemCount] for i in range(0,len(arrayElements),listItemCount)]
# for loop increment by "listItemCount"
#spl... |
94c2d72eccd9ff48675cdefa793a7eba3c3309d3 | aniket-2001/python-phone-number-project | /main.py | 1,049 | 3.671875 | 4 | import phonenumbers
from test import number
from phonenumbers import geocoder
ch_number = phonenumbers.parse(number, "CH")
#IN BELOW LINE YOU WILL COUNTRY LOCATION OF PHONENUMBER
print("1.This is your country:\n")
print(geocoder.description_for_number(ch_number,"en"))
print("---------------------------------... |
d9b47de6ecf81723e222993a6e945a67d2e44cb6 | nwant/datamining.bayesclassifier | /bisecting_k_means.py | 11,013 | 3.875 | 4 | #!/usr/bin/env python3
#
# Nathaniel Want (nwqk6)
# CS5342-G01
# Bisecting K Means
# March 21, 2018
#
# Overview: The following program/library implements a basic Bisecting K Means algorithm based on the requirements
# of the first homework project for CS5342 (Spring 2018)
#
# Random Seed:
# The random selection of gen... |
c6eb730046db60c37569f637f5b0b88b8fb9351d | elifsila35/GlobalAIHubPythonCourse | /elifsılatanaydın_globalaihub_Finalproject.py | 1,934 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
question1=str(input("Bu nedir?"))
ans1="elma"
ans1_=ans1.lower()
if question1==ans1_:
y1="okey"
print("okey, you win 10 points")
else:
print("wrong")
question2=str(input("Bu renk hangi renktir? "))
ans2="kırmızı"
ans2_=ans2.lower()
if question2==ans2_:
y... |
7d8ec4e2595c82d264b7a6e3aa2fe4c50b7895c8 | anastasiiakhimich/knm_12__lab_1 | /4_reverse.py | 57 | 3.765625 | 4 | for i in reversed(input('Text: ')):
print(i, end='')
|
f8a3765b97eb842195d80c2ef321968523039736 | LIFA-0808/course_algoritm_Py | /Lesson_1/les_1_task_5.py | 388 | 3.984375 | 4 | # 5. Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
request = int(input('Введите номер буквы в алфавите a-z: '))
if 1 <= request <= 26:
answer = alphabet[request - 1]
print(answer)
else:
print('Неверный ввод')
|
456fa4fa7cc77a6f48f56bf472e65598a3b1dcca | ricko1993/TEST_REFACTORY | /Logic_Test/fibonaci.py | 475 | 4.0625 | 4 | def fibonaci(num):
if (num == 0):
print(0)
return
angka_pertama = 0
angka_kedua = 1
angka_ketiga = angka_pertama + angka_kedua
while (angka_ketiga <= num):
angka_pertama = angka_kedua
angka_kedua = angka_ketiga
angka_ketiga = angka_pertama + angka_kedua
if (abs(angka_ketiga - num) >=
abs(angka_ke... |
dc92f21c368260efe21ff50f0aa928f1cd6fc7ed | neeliooha/DSP_LAB | /lab1/Experiment1_b.py | 167 | 4 | 4 | a=input("enter the a value")
a=float(a)
b=input("enter the b value")
x=input("enter the x value")
p=(a*x)+b
q=(a*x)-b
s=p/q
print "The value of (ax+b)/(ax-b)",s |
80ab8b75f620982ab16686e9246ea7dcfca81434 | FeiyangJin/PiCar-backup | /PythonCSV/input.py | 609 | 3.75 | 4 | #!/usr/bin/python3
import csv
# str = input("Please enter input:\n")
# print("Input:", str)
filename = "sample.txt"
# with open(filename) as f:
# for line in f:
# line_contents = line.strip()
# print(line_contents)
file = open(filename,"r")
line = file.readline()
i = 1
while line:
print("T... |
bb26950a6a070ad66535640f6791c96edd59b9bf | alpaziz/soultions | /lecture_6/strings_speech_sets.py | 878 | 3.84375 | 4 | # Declare function here
def find_common(string_1, string_2):
# Seperate on whitespace and save output
speech_1_list = string_1.split()
speech_2_list = string_2.split()
# Converts lists to sets
speech_1_set = set(speech_1_list)
speech_2_set = set(speech_2_list)
# Save common
common = speech_1_set.in... |
3cac369b719a5f8f21aefa0e6eba9fc683d64d4e | cs-fullstack-2019-spring/python-functions-cw-LilPrice-Code | /Classwork.py | 1,509 | 3.96875 | 4 | def main():
# prob1()
# prob2()
# prob3()
prob4()
def prob1():
x = 0
while x <= number():
print(x)
x += 1
def prob3():
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
userReq = input("Do you want to add, subtract, mul... |
a93928bdd2903eaff9af7bd7f347b0dca686bdbb | jlsalmon/sga | /sga/selection.py | 3,466 | 3.625 | 4 | #-------------------------------------------------------------------------------
# Author: Justin Lewis Salmon <mccrustin@gmail.com>
#-------------------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Les... |
02774b2a40e58bf843a661fde07fc87b91bcdabd | Scientific-Computing-at-Temple-Physics/prime-number-finder-Scadow121 | /primes.py | 1,479 | 4.25 | 4 | # This is a comment. Python will ignore these lines (starting with #) when running
import math as ma
import time
# To use a math function, write "ma." in front of it. Example: ma.sin(3.146)
# These functions will ask you for your number ranges, and assign them to 'x1' and 'x2'
x1 = raw_input('smallest number to ch... |
02f574f8deb18e8abd60e61f90498d8499810398 | EugenePY/hrdc | /hrdc/util/named_constant.py | 1,722 | 3.515625 | 4 |
class NamedConstant:
def __init__(self, name, value):
self.name = name
self.value = value
def __int__(self):
return self.value
def __str__(self):
return self.name
def __lt__(self, other):
return int(self) < int(other)
def __eq__(self, other):
retu... |
0f74e726083ffbcf8cf3c1293bb6bbfa8c835026 | BillyBarbaro/rank_aggregation | /create_ranking.py | 1,666 | 3.671875 | 4 | """
Program to create a set of ranked lists of a given number of objects,
to be used for testing rank aggregation code.
Author: Sibel Adali
Creates partial rankers between num_objects/2 to 3*num_objects/4 objects
completely randomly.
Usage python create_ranking outfilename numobjects numrankers
... |
38ced7a254e1721597f6200a1fd73412cc0ca894 | KeoghRee/python_learn | /exercise/去除首尾空格.py | 109 | 3.640625 | 4 | # -*- coding: utf-8 -*-
def trim(s):
while s[:1] == ' ':
s = s[1:]
while s[-1:] == ' ':
s = s[:-1] |
35b77c4c4b264a709a749f31678e372a570c8682 | CHENG-Package/Python | /Python从入门到实践4.13.py | 164 | 3.921875 | 4 | food=('汉堡','芝士披萨','薯条','三明治','炸鸡腿')
for foods in food:
print(foods)
print('')
P=food
for P in food[:2]:
print(P)
|
fc4c5fecc85173ddae70a186f2bed43c0d118a2d | CHENG-Package/Python | /Python从入门到实践7.4-7.7.py | 1,215 | 3.75 | 4 | T='输入一些你想要的披萨配料:'
ingredients_list=[]
while True:
CM=input(T)
if CM == '退出':
break
else:
ingredients_list.append(CM)
print('我们会为你添加',ingredients_list,'配料')
print("\n输入'退出',结束你想要添加的配料")
continue
print('--------------------------------------')
age=in... |
f862fbb0d2ebc93e57d6e571899c699563c5d86b | anthonyhertadi/Python-Course | /Day 2/conditional.py | 541 | 4.125 | 4 | # == comparison
# = assignment operator
cuaca ="ga hujan"
if cuaca == "hujan" or cuaca == "Hujan":
print("BAWA PAYUNG CUK!!!")
elif cuaca == "tidak tahu":
print("Jaga-jaga aja bor")
else:
print("Gausa Bawa Payung, Bego!")
nilai = 80
#!= =tidak sama dengan
if nilai >= 75 and nilai <= 90:
print("L... |
14adfba88d0281315790aa94534cc564aeed4602 | skan/training_python | /python/python/exercices/2_01.py | 906 | 3.84375 | 4 | # -*-coding:UTF-8 -*
# ex 3 ?
def tabe(base, debut, fin, inc):
mult = debut
while mult < fin:
print("{} x {} {}".format(base,mult,base*mult))
mult += inc
def cube(x):
return x*x*x
def exercice_3():
tabe(7,2,13,2)
a = 9
print ("cube de {} = {}".format(a,cub... |
4ef90219b8671dee22231091699a6005ed7d71d4 | skan/training_python | /python/python/exercices/supplement/ex02.py | 148 | 3.515625 | 4 | TVA = 1.18
while (1):
ht = float(input ("donner le prix ht: "))
if (ht == 0):
break
print ("\t ---> ttc = {}".format (ht*TVA))
|
053b6a6b727899650851c047e9a959ac4140b71e | skan/training_python | /python/python/basics/iterateurs.py | 690 | 3.78125 | 4 | #-*- coding: utf-8 -*-
import os
# une liste est un itérateurs
#liste = [1,2,3,4,5,6,7,8,9,10]
# Créer une classe itérateur
class MonIter():
current=0
def __init__(self,stop):
self.stop=stop
def __iter__(self) :
return self
def next(self) :
self.curren... |
8f7efad55ecb3b21a1f447dd168228db06a6955d | VincentBellue/stage_m2_bellue_vincent | /ancienne_version/scripts/scripts_vec_statique/script_base_colloc_vec_statique.py | 3,123 | 3.546875 | 4 | import argparse
usage = """<documentation>"""
parser = argparse.ArgumentParser(description = usage, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("input", type = str, help="Chemin du fichier input (tsv)")
parser.add_argument("output", type=str, help="Chemin du fichier output (tsv)")
args = parser.... |
986351a9b67aeebf4611b3bb818a227ea242b2d3 | bjwhite-fnal/striped | /striped/common/MyThread.py | 2,636 | 3.5 | 4 | from threading import RLock, Thread, Event, Condition
Waiting = []
In = []
def synchronized(method):
def smethod(self, *params, **args):
#print "@synchronized: wait %s..." % (method,)
q = "%s(%x).%s" % (self, id(self), method)
Waiting.append(q)
with self:
Waiting.remove... |
60ecc60c1659a8c128205f92423e9355afb12a81 | greg-petersen/AEQTakeHome | /Castles/castle.py | 1,491 | 3.609375 | 4 | """castle.py has two functions. calculate_number_of_castles and a main function."""
import random
def calculate_number_of_castles(land):
"""Returns number of castles that can be built on input land array."""
print(land)
direction = 0 # 0 represents start, 1 means up, -1 means down
previous_plot = Non... |
c598300abd94c42fbeb800c8f26e7c1510c5f10c | junoon53/battleship | /game.py | 1,597 | 3.90625 | 4 | import random
class Game(object):
"""Constructs a two player game"""
def __init__(self, player_a, player_b, board_a, board_b, verbose=True):
"""Init function for the Game Class """
self.players = [player_a, player_b]
self.boards = [board_a, board_b]
self.verbose = True
... |
fe87f7e7b99c53851e97769382f05b691edb9179 | toomuchmath/advent_of_code_2020 | /day03/day03.py | 1,140 | 3.53125 | 4 | def get_input(filename):
with open(filename) as f:
lines = f.read().split('\n')
return lines
def coordinates(row, x_increment, y_increment):
y = row * y_increment
x = (row * x_increment) % 31
return x, y
def count_trees(split_lines, x_increment, y_increment):
row_c... |
0bd16218a3c79e5f1e9d5475a28381aaf9fcd300 | plotnik102rus/Stady_repo | /task 3-3.py | 358 | 4.03125 | 4 | #Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(x, y, z):
num_1 = min(x, y, z)
num_sum = (x+y+z) - num_1
return num_sum
print(my_func(100, -1, -6)) |
fbad48fbea9ac598eba30be8e879c75550ab8997 | plotnik102rus/Stady_repo | /6_1.py | 1,186 | 3.625 | 4 | # Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
# Атрибут реализовать как приватный.
# В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый.
# Продолжительность первого состояния (красный) составляет 7 секунд,
# второго... |
f1ac4e45bc78b065f5cb55fde220b57f011d71e9 | plotnik102rus/Stady_repo | /Task 2-5.py | 735 | 4.28125 | 4 | #Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга.
# Если в рейтинге существуют элементы с одинаковыми значениями,
# то новый элемент с тем же значением должен разместиться после них.
my_list = [9, 6, 5, 3... |
bbbd2b7414c72e997d0cc05a5b75b224da8a95fe | Imafont/D002-2019 | /L1/Wei Wen Hao Q2.py | 423 | 3.921875 | 4 | from math import*
def calculations(x):
print("The answer to questions 2 is:")
print(8*3.57)
print(5 + 30*20)
print((5 + 30)*20)
print(1+ (2 + 20*3)/(4*2))
print(1+2*10)
print(int(29/4)+1)
def square_area(x):
r = sqrt(100/pi)
square = (2*r+1)**2
print "The radius of ... |
05f647cb38f59a65f7fe2ad2d3415e53036a69f2 | Imafont/D002-2019 | /L5/Wei Wen Hao L5bonus.py | 2,238 | 3.53125 | 4 | def sodukucell(cells):
print("-" * 26)
for i in range(0, 6):
for j in range(0, 6):
print("| %s " % cells[i][j], end="")
print("|")
print("-" * 26)
def check_number(cells):
if (' ' not in cells[1]) and (' ' not in cells[2]) and (' ' not in cells[3]) and (' ' not ... |
29f6514032f059d6d23be756f9cd369e03609c98 | binuthomaz/Misc | /monty.py | 1,199 | 3.671875 | 4 | import random
def montyTrial():
car_door = random.randint(1, 3)
# print("Car door:",car_door)
participant_first_choice = random.randint(1, 3)
# print("Participant First Choice:",participant_first_choice)
host_proper_choice = False
while not host_proper_choice:
host_choice = random.rand... |
8373004116be48f082485a58ac46d8ff5f2157b5 | hmunduri/PythonOOP | /tasks/task.py | 472 | 3.71875 | 4 | # Task 1
Class - Account
Function
open_account ()
deposit_money()
withdraw_money()
view_balances()
#Task 2
python bank.py
"welcome to BOFA"
Options:
1.Open Account
2.Money Deposit
3.Money withdrawal
4. View Balance
5. Request Loan
Please choose the options: 1
please enter the minimum ammount: 100
#minimum bal... |
a1b046530bf211a353f6d3fd7dbbc9b7a134020d | test-learn/github-learn | /helloWorld.py | 1,533 | 4.3125 | 4 | print("Hello World!!!")
print("This is my first python program")
intVal = 5
floatVal = 4.54
boolVal = True
print(boolVal)
boolVal = False
print(intVal)
print(floatVal)
print(boolVal)
# single line comment
"""
Saare jahaan se achha
"""
print("Adding above 2 numbers = ", intVal+floatVal)
operator1 = 2
operator2 =... |
9405e9122fea2bc2f1e118f1fece7b9666cc5ceb | BaptisteDixneuf/python-test | /exercice11/ex011.py | 449 | 3.953125 | 4 | a="Ma jeunesse ne fut qu'un tenebreux orage,\
Traverse ca et la par de brillants soleils ;\
Le tonnerre et la pluie ont fait un tel ravage,\
Qu il reste en mon jardin bien peu de fruits vermeils."
mon_dict = {}
for character in a :
character = character.lower()
print(character)
if mon_dict.get(charact... |
fda8f3c20e23a832654326b6d2db0492d1ec0565 | BaptisteDixneuf/python-test | /04_tuple.py | 70 | 3.578125 | 4 | my_tuple = (1,2,3)
for i in my_tuple:
print(i)
print(my_tuple[0]) |
73c5f1e8a1c9c727c7e969d61e0f4166ebc47bb0 | BaptisteDixneuf/python-test | /exercice9/exercice9bonus.py | 218 | 3.875 | 4 | n = input("Quelle table voulez vous afficher ?\n")
nombre = int(n)
for i in range(1, nombre):
for j in range (nombre, 1, -1):
#print (i , j)
if(i+j == 8):
print("(", i , ", " , j ,")") |
ae378025dd0a2c164c4742e56dd70d1a0908d18b | BaptisteDixneuf/python-test | /exercice14/exo14.py | 427 | 3.546875 | 4 | def trier_liste(*args):
liste_pair = []
liste_impair = []
print(*args)
for item in args:
if item % 2 == 0 :
liste_pair.append(item)
else:
liste_impair.append(item)
liste_pair.sort
liste_impair.sort
joined_list = liste_pair + liste_impair
print (jo... |
3b7ec7522103f8d09d04e3955ffc1167c1aca47d | abdulwasayrida/Python-Exercises | /Exercise 6.18.py | 569 | 4.21875 | 4 | #Exercise 6.18
#Display a matrix of 0s and 1s
#Rida Abdulwasay
#1/12/2018
def printMatrix(n): #Create a function
from random import randint
for side1 in range (n):
for side2 in range (n):
print(randint(0, 1), end=" ") #randint generates the random number sequence
print(" ")
... |
e65af2007a3a9096a6dc4569338d5b84aa4e93fa | abdulwasayrida/Python-Exercises | /RegularPolygon.py | 1,418 | 4.3125 | 4 | #Exercise 7.5
#Geometry: n-sided regular polygon
#Rida Abdulwasay
#1/14/2018
import math
#Create a Class named RegularPolygon
class RegularPolygon:
def __init__(self, n = 3, side = 1, x = 0, y = 0):
self.__n = n
self.__side = side
self.__x = x
self.__y = y
#Create a function to t... |
a8245ea6bd6ab2a938dd2a94c1d2f443e55de059 | abdulwasayrida/Python-Exercises | /Exercise 7.3.py | 688 | 4.0625 | 4 | #Exercise 7.3 (Continued)
#The Account Class
#Rida Abdulwasay
#1/13/2018
#Import Account
from Account import Account
def main ():
#Set the ID, Balance, and Annual Interest Rate
account = Account(1122, 20000, 4.5)
#Set The Withdrawl to $2,500
account.withdraw (2500)
#Set The Deposit to $3... |
23ebf6103e927ea58302f57258cb19ef96079f0e | abdulwasayrida/Python-Exercises | /Exercise 4.23.py | 985 | 4.21875 | 4 | #Exercise 4.23
#Geometry: point in a rectangle?
#Rida Abdulwasay
#1/8/2018
import turtle
#Prompt the user to enter a point
x , y = eval(input("Please enter a point with two coordinates:"))
#Draw the rectangle
turtle. color ("blue")
turtle. penup ()
turtle. forward (2.5)
turtle. left (90)
turtle. pendown()
turtle. fo... |
b675742fc9a9c28c8cede1009b47aa35e89042fe | Pheotixx/Bank-ATM | /atm.py | 885 | 3.734375 | 4 | import random
class Atm(object):
def __init__(self,cardNumber, pin,userName):
self.cardNumber = cardNumber
self.pin = pin
self.userName = userName
def cashWithdrawal(self):
withdrawalMoney = input("How much money do you want to withdraw? ")
print("Withdrawing "+... |
58e3bb8facf5ab09c99667c096d148a2f3b39f99 | amrutheshwaro/sl-lab | /a1.py | 933 | 4.03125 | 4 | a = []
b = int(input("Enter the size of the list.\n"))
print("Enter", b, "numbers.")
for i in range(b):
a.append(int(input()))
print("Maximum element in the list is", max(a))
print("Minimum element in the list is", min(a))
new_element = int(input("Enter the new element to be inserted.\n"))
pos = int(input("Enter ... |
11d8982132a849a44a59ba4fdabffc2726a35b21 | Ahuvim/MyAssistantBot | /joke.py | 320 | 3.59375 | 4 | import requests
from random import choice
def joke(user_input,res):
num_jokes = res["total_jokes"]
results = res["results"]
if num_jokes > 1:
return choice(results)["joke"]
elif num_jokes == 1:
return results[0]["joke"]
else:
return f"There is no joke about {user_input}"
|
2d046db1cd47660ed19b7a0d03835285d3f50d3a | Aleeeeex-xu/spider-test1 | /untitled/match_test.py | 215 | 3.71875 | 4 | import re
patten = re.compile('he')
match1 = patten.match('hello hell world are you kiding me?')
match = re.match('he','hello hell world are you kiding me?')
print match.string
print match.re
print match1.string |
a318e8defdebe2bf892b094c9ce6d3fa584420ad | davidngu3/cracking_the_code_interview | /1-8_zero-matrix.py | 894 | 4 | 4 | # 1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
# column are set to O.
import unittest
def zero_matrix(matrix):
zero_rows = set()
zero_cols = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0... |
7f1e95216f4766ef5489b6e3215eec597fcca47e | davidngu3/cracking_the_code_interview | /1-2_check-permutations.py | 1,731 | 3.9375 | 4 | # 1.2 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other.
# IDEAS:
# Sort both and check equality: O(Alog(A) + Blog(B))
# Bitmap of characters: O(A + B)
# Hashset: O(A + B)
def checkPermutations(string1, string2):
charHash = {}
# optimisation: permutation... |
18d97e92db43807f83fc54bdd8e7fb9ae48d8b84 | davidngu3/cracking_the_code_interview | /3-3_stack_of_plates.py | 1,662 | 3.953125 | 4 | class StackNode:
def __init__(self, data, next_node=None):
self.data = data
self.next = next_node
class Stack:
def __init__(self, top=None):
self.top = top
def push(self, data):
newNode = StackNode(data)
if self.top:
newNode.next = self.top
s... |
a947b5056d77c1dcb67ece941a86ce3afd26cdf2 | Faranaz08/assignment2 | /decimaltobin.py | 226 | 4.21875 | 4 | # decimal to binary usingfunction
def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2 ,end=' ' )
# decimal number
dec = int(input("enter a decimal number"))
convertToBinary(dec)
print() |
54e078526ad01368fbe9c59839211afb70a2b0b6 | 274337383/OPENCV | /huifu.py | 856 | 3.671875 | 4 | # -*- codeing = utf-8 -*-
# @Time : 2021/8/7 8:41
# @Author : 张涛
# @File : huifu.py
# @software : PyCharm
# 批量修改一个文件下的文件后缀
import sys
import os
def Rename():
# Path = "F:\\test\\" # windows下的文件目录
Path = input("请输入你需要操作的目录(格式如'F:\\test'):")
filelist = os.listdir(Path)
for files in filelist:
Ol... |
68ad6ac438ebb8e083ffbb1986a03ca253fe4982 | chengming-1/python-turtle | /W3/lab-3/counter.py | 99 | 4.03125 | 4 | count = input("What number should I count to? ")
for num in range(int(count)):
print(num)
|
cfb62228f83d8c41678f1d6baf6934d583c5b333 | chengming-1/python-turtle | /W9/structured-data/pizza.py | 472 | 3.859375 | 4 | import random
def print_pizza_order(pizza):
print("I would like a", pizza['size'], "pizza on a", pizza['crust'], "crust")
print("With", pizza['toppings'], "on it")
monday = {'size': "small", 'crust': "traditional", 'toppings': "extra cheese"}
friday = {'size': "large", 'crust': "deep dish", 'toppings': "... |
e6a084c2bf6c0c34e3ffcd81ec94d893412a74db | chengming-1/python-turtle | /W7/lab-7/names.py | 612 | 4.1875 | 4 |
# Create an empty dictionary
names = {}
names['Wash'] = 'Rick'
names['Geier'] = 'Caitlin'
names['DiLisio'] = 'Armand'
names['wang']='chengming'
a = input("Enter the last name of a student: ")
b = input("Enter the First name of a student: ")
names[a]=b
while True:
last_name = input("Enter a stude... |
90110e5df6d7b68824d91ef4a2d2c36150e44ca1 | chengming-1/python-turtle | /W7/lab-7/mascots.py | 340 | 3.6875 | 4 |
mascots = {
"MSU": "Spartans",
"Michigan": "Wolverines",
"Wisconsin": "Badgers",
"Ohio State": "Buckeyes",
"Penn State": "Nittany Lions",
"Indiana" : "Hoosiers"
}
answer = input("What university do you want to know the mascot for?")
print("People who go to "+ answer +" are called"... |
6a298888b5c61715d72ac7681d73b8d259c5e1b8 | chengming-1/python-turtle | /W5/studio-5/guestbook.py | 970 | 3.953125 | 4 | from turtle import *
names=[]
penup()
left(90)
forward(300)
left(90)
forward(300)
pendown()
write("Please enter your full name,enter ""end"" to show the whole guestbook", font=("Helvetica", 10, "italic"))
penup()
left(90)
forward(60)
pendown()
while True:
penup()
forward(20)
pendown()... |
8fd65a32466b8cb02eae4257de980c3b49f734e1 | chengming-1/python-turtle | /W12/lab-12/problem.py | 496 | 3.921875 | 4 | def flashcard(prompt,expected_answer):
cards = {}
cards[prompt]= expected_answer
question='What is the capital of',prompt,'?'
expected_answer = cards[prompt]
answer = input(question)
if answer.lower() == expected_answer.lower():
print("Correct!")
else:
print("Sorry, ... |
e92da8c323b96a5f2992a7166e747d4e130ecc26 | priyankmalviya/hall-p2 | /src/preprocess_unet.py | 2,746 | 3.640625 | 4 |
import preproc as pre
import numpy as np
def normalize_img_unet(data):
'''
This function takes as input the data as list of images and normalizes it.
'''
normalize_unet_data = []
for j in range(0,len(data)):
min_val = np.amin(data[j]) # finding the maximum value of the image
max_... |
09b19aa33e576b71a463bd1aced49b14e2e0d74b | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH03/Exercise/page_85_exercise_04.py | 657 | 4.125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Assume that the variables x and y refer to strings. Write a code segment that prints these strings in
alphabetical order. You should assume that they are not equal.
Solution:
The sorted words are:
bui
khang
le
ngoc
"""
# Program to sort alphabetically the wor... |
53878427622bba5b8e795204524588c123540e36 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_203_exercise_02.py | 719 | 4.25 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton.
(Hint: The estimate of the square root should be passed as a second argument to the function.)
Solution:
2.0000000929222947
"""
approximating = 0.000001
... |
b23bb4110b87d50d561acb33994bd8acdd3fd476 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH05/Exercise/page_145_exercise_01.py | 501 | 4.03125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Assume that the variable data refers to the list [5, 3, 7]. Write the values of the following expressions:
a. data[2]
b. data[-1]
c. len(data)
d. data[0:2]
e. 0 in data
f. data + [2, 10, 5]
g. tuple(data)
Solution:
Result the output:
a. 7
b. 7
c. 3
d. [5, 3]
e. ... |
34df6e92f6125e3408e46221b645c44b2855e728 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Exercise/page_182_exercise_02.py | 569 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: The factorial of a positive integer n, fact(n), is defined recursively as follows:
fact(n) = 1 , when n = 1
fact(n) n * fact (n-1) , otherwise
Define a recursive function fact that returns the factorial of a given positive integer
Solution:
Ent... |
1e5c4c045f1dba4a593e9ed1592c8e6da66720b8 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH02/Ch_02_Projects/2.3/fivestar.py | 906 | 3.875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Five Star Retro Video rents VHS tapes and DVDs to the same connoisseurs who like to buy LP record albums.
The store rents new videos for $3.00 a night, and oldies for $2.00 a night. Write a program that the clerks at Five
Star Retro Video can use to calculate the ... |
70f14fa043fd43405c2ad2d9196c714b21dd395c | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Exercise/page_125_exercise_03.py | 452 | 4.0625 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Assume that a file contains integers separated by newlines. Write a code segment that opens the file and
p-oprints the average value of the integers.
Solution:
The average is 38.5
"""
count = 0
sum = 0
inputFile = open("myfile2.txt",'r')
for line in inputFile:... |
81125a2c8610d4531755bb4a53cb19aa3d946c96 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_132_exercise_02.py | 640 | 4.40625 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a script that inputs a line of encrypted text and a distance value and outputs plaintext using a
Caesar cipher. The script should work for any printable characters
Solution:
Enter the coded text: khoor#zruog
Enter the distance value: 3
hello world
"""
# R... |
7a5c1a0d7c416a8f88934c5b6daecb4c36fefa45 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_204_exercise_09.py | 623 | 4.125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a program that computes and prints the average of the numbers in a text
file. You should make use of two higher-order functions to simplify the design.
Solution:
Enter the file name: textnumber.txt
The average is 3.0
"""
def main():
fileName = input(... |
6c7d29e55f6046277c7bef3576d5a068c275bdc1 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_203_exercise_05.py | 822 | 3.921875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: A list is sorted in ascending order if it is empty or each item except the last one is
less than or equal to its successor. Define a predicate isSorted that expects a list
as an argument and returns True if the list is sorted, or returns False otherwise.
Solution... |
47c65a3c577e406863dba437b479719540e39061 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH03/Projects/page_99_exercise_02.py | 1,005 | 4.3125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should
indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle,
the square of one side equals the sum... |
6873aa32b9630205bbc7475864686dd85187beaa | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_132_exercise_06.py | 1,004 | 4.375 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5
to code a new encryption algorithm. The algorithm should add 1 to each character’s numeric ASCII value, convert
it to a bit string, and shift the bits of thi... |
81627d0a80c0c03f3027ff7296a3638a447c37e7 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_133_exercise_09.py | 941 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a script named copyfile.py. This script should prompt the user for the names of two text files.
The contents of the first file should be input and written to the second file.
Solution:
Enter the input file name: test9.txt
Enter the output file name: test9_... |
fc90debc52d5f84e0d03ab770ba10746405d657f | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH07/Exercise/page_218_exercise_03.py | 480 | 4.46875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Add a function named circle to the polygons module. This function expects the same arguments as the square
and hexagon functions. The function should draw a circle. (Hint: the loop iterates 360 times.)
Solution:
"""
import turtle
def polygon(t, length, n):
... |
26ce3efa3df58e629c706ad5da9b8457ba0e9d52 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Exercise/page_199_exercise_02.py | 317 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write the code for a filtering that generates a list of the positive numbers in a list
named numbers. You should use a lambda to create the auxiliary function.
Solution:
[1, 79]
"""
numbers = [1, -2, -66, 79]
result = list(filter(lambda x: x > 0, numbers))
print... |
e003f0a4399191ecfd6785e4748a9a3602d78e5e | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH01/Exercise/page_29_exercise_04.py | 719 | 3.890625 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Explain what goes on behind the scenes when your computer runs a Python program.
Solution:
- The interpreter reads the statements and check for syntactical errors. If found any error then it halts the
process and return the error message.
- If a Python exp... |
5c5fc3250152575883481aca9ee77e0a632f7c95 | Dukiemar/RSA-Encryption | /RSA_Encryption.py | 2,632 | 4.34375 | 4 | import random
def PGP_encryption():
p=input("enter the 1st prime number:")#prompts the user to enter the value for p
q=input("enter the 2nd prime number:")#prompts the user to ented the value for q
message=input("enter message:")
def isPrime(n): #this function ristricts the user to only enter p... |
6fa5c25578edbd78ccadcba5815df7bc7fc9562a | IKnoble/bookstore | /frontend.py | 3,660 | 3.625 | 4 | from tkinter import *
import backend
#A function that select the desired row to be deleted
def get_selected_row(event):
try:
# creating a global variable
globals selected_tuple
index=list1.curselection()[0] #this grabs the id of the selected_tuple
selected_tuple=list1.get(index)... |
36384e6a9b1f876bbc995b34d7d9ffd1c1845fdd | Raparker88/Self-taught-progammer-projects | /triangle object.py | 217 | 3.578125 | 4 | class Triangle:
def __init__(var,h,b):
var.height=h
var.base=b
print("created!")
def area(var):
return (var.height*var.base)/2
triangle1=Triangle(4,6)
print(triangle1.area())
|
fdcb0fafe5862f3e4a1b6d07463b4135346fffa4 | Raparker88/Self-taught-progammer-projects | /square list.py | 316 | 4 | 4 | class Square:
square_list=[]
def __init__(self,s):
self.side=s
self.square_list.append(self)
def __repr__(self):
print("""{} by {} and {} by {}""".format(self.side,self.side,self.side,self.side))
square1=Square(2)
square2=Square(3)
square3=Square(4)
print(square1)
|
684c89876b19c9a5589d49c243c8d237c2709141 | iuvLuyonghao/api_test | /util/rcc_phone.py | 611 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def creat_phone():
#第二位数
second = [3,4,5,7,8][random.randint(0,4)]
#第三位数
third = {
3:random.randint(0,9),
4:[5,7][random.randint(0,1)],
5:[i for i in range(0,10) if i != 4][random.randint(0,8)],
7:[6, 7, 8][rand... |
cd72315e93ba75c2553d18f249e7337ba97d7ade | Zabava-Anna/QAP-34 | /Class_print_params.py | 1,070 | 3.84375 | 4 | # Создайте класс любых геометрических фигур, где на выход мы получаем характеристики фигуры. Каждый экземпляр должен иметь атрибуты,
# которые зависят от выбранной фигуры. Например, для прямоугольника это будут аргументы x, y, width и height.
# Кроме того вы должны иметь возможность передавать эти атрибуты при создан... |
0a0ce1f6c3c1241a52b7f01c5b0882973cf7f641 | Davies-Career-and-Technical-High-School/1-4-activity-input-and-output-JermsterOrtega | /question6.py | 143 | 4 | 4 | firstname = input("Please input your first name: ")
lastname = input("Please input your last name: ")
print(lastname + "," + " " + firstname) |
a23284b126ebe27d34d5a47196df797fa3059e01 | nvk1152/python-tasks | /Day5-Tasks/listCommands.py | 140 | 3.78125 | 4 | import sys
n = input('Enter number:')
print(n)
print(f"Total Number Of Arguments Are {len(sys.argv)-1}")
print(f"Arguments Are {sys.argv}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.