blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e1b45642c72d8e7014e7b003ae2ce9803d598d93 | Bhaskarsaikumar/ANN-Hidden-layers | /ann.py | 951 | 3.953125 | 4 | # Artificial Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13]
y = dataset.iloc[:, 13]
#Create dummy variables
g... |
6de04b3796e40f3807206d5aeeed6b10d03b99e6 | divi9626/Treaps_data_structure | /Treaps_A5.py | 2,585 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 14:54:51 2021
@author: divyam
"""
class Treapnode:
def __init__(self,val,priority = None):
self.val = val
self.priority = priority
self.left = None
self.right = None
def insert(root,val,priority):
if root is None:
... |
43f5cbed35048a8a63fde1a886b487a4b5bcb0af | Kgg9/Stock-Market-Project- | /Custom_Functions.py | 761 | 3.546875 | 4 | import datetime
from dateutil import parser
# custom recursive binary search specialized for date, since it is faster because default python list.index() uses linear search
def binarySDate(stockDateArray,dateInput, start, end):
# list doesn't need to be sorted since it is already sorted in descending order
if... |
7c1bff85c0462afa7cce327344780c3386099028 | cmarquezb/InicialPython | /Arboles.py | 2,956 | 3.625 | 4 | #Arboles Binarios
class Nodo:
def __init__(self, listacampos = None, derecha = None, izquierda = None):
self.listacampos = listacampos #todos los cmpos que quisieramos DNI, Nombre, Apellido
self.derecha = derecha
self.izquierda = izquierda
def __str__(self):
return "%s" ... |
606f2f5f50444a5ff5aab9fff6850a9b4f02bb6c | dixitomkar1809/GeeksForGeeks | /sortanarray.py | 1,106 | 3.84375 | 4 | # https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0
#code
def quickSort(a, l, r):
if l < r:
q = partition(a, l, r)
quickSort(a, l, q-1)
quickSort(a, q+1, r)
def partition(a, l, r):
pivot = a[r]
i = l - 1
for x in range(l, r):
if a[x]<=pivot:
... |
7c9d1b58ddb4bb8be94d0fcd87b481991bdfaf11 | dixitomkar1809/GeeksForGeeks | /linkedList.py | 494 | 3.96875 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next= None
def traverse(self):
node = self
while node != None:
print(node.val)
node = node.next
if __name__=="__main__":
node1 = Node(12)
node2 = Node(99)
node3 = Node(37)
node1.nex... |
6a321c251d9e92be252a04fc826c32590e3eaf2e | 1piotrnowicki1/infoshare_cwiczenia | /zjazd_2_cwiczenie_8 - Throw a coin/coin _heads_streak_counter_solution1.py | 1,086 | 3.984375 | 4 | """
Napisz funkcję która:
- Symuluje rzut monetą
- Rzuca monetą określoną ilość razy i zwraca najdłuższy ciąg orlów
Zeby bylo prosciej, mozecie przyjac ze wartosc Reszki to 0, a orła 1
"""
import random
def rzut_moneta():
return random.choice([0, 1])
def rzut_moneta_n_razy(n):
current_streak, longest_s... |
c9aeb0a7831ebe92a455a24f605fb4393eff0182 | 1piotrnowicki1/infoshare_cwiczenia | /zjazd_3/realizacja_zamówień_online.py | 1,080 | 3.5 | 4 | """
Jesteś właścicielem/-elką małego biznesu który prowadzisz online i dużą częścią Twojego dnia jest realizacja zamówień.
Żeby ułatwić swoją pracę, postanowiłeś/-aś napisać funkcję, która pomoże zdecydować czy realizacja zamówienia jest możliwa.
Funkcja przyjmie trzy argumenty:
- towar: dict – słownik reprezentujący... |
b03b801ffd8ae2bf86bca603272d6b846fc222a6 | Andrejs85/izdruka | /funkc_uzd.py | 1,739 | 3.71875 | 4 | """
#funkcija atgriež 10% no a un 20% no skaitļa b
def procenti(a, b):
return a*10/100, b*0.20
print(procenti(100,1000))
#Uzraksti funkciju var_pagulet, kas atgriež True, ja ir brīvdiena un False, ja ir darbdiena.
def var_pagulet(diena):
if diena==brivdiena:
return True
else:
return Fals... |
b339e1b0f40936bbb6974725c525364fa0667a49 | Andrejs85/izdruka | /for_cikls.py | 1,706 | 4.1875 | 4 | #iteracija - kadas darbibas atkartota izpildišana
mainigais=[1,2,3]
for elements in mainigais:
print(elements) #darbibas kas javeic
#izdruka list elementus
myList=[1,2,3,4,5,6,7,8,9,10,11,12]
for sk in myList:
print(sk)
for _ in myList:
print("Sveiki!") #var nerakstit cikla mainiga nosaukumu
#izdruka tik... |
8dbb3d1114d2ecfd1f58cc5b76aa886a904c400c | Andrejs85/izdruka | /funkc_return.py | 962 | 3.71875 | 4 | def saskaiti_skaitlus(sk1, sk2):
#rez=sk1+sk2
return sk1+sk2
rez1=saskaiti_skaitlus(2,3)
rez2=saskaiti_skaitlus(2.3, 35.8)
rez3=saskaiti_skaitlus(2.5, 13)
print(rez1+rez2+rez3)
#parbauda vai ir pāra skaitlis
def parbaudi_pari(skaitlis):
return skaitlis%2==0
print(parbaudi_pari(20))
print(parbaudi_par... |
443dba8faebc29982c87d80868f027d23e253443 | SANDAG/QA | /Internal_Projects/2022-21 Forecast_Automation/scripts_2.0/data_qc_funcs.py | 690 | 3.796875 | 4 | import pandas as pd
import numpy as np
# TODO: Build a function that can identify the level of the data
def percentile_outlier_check(df, column, lower_percentile, upper_percentile, level):
"""Returns a dataframe that lies outside the lower and upper percentiles given by the analyst."""
lower_value = np.perce... |
aa374e01ef9a0c11a96d244fd60fb33496bdac59 | spartam/basic_python_course | /code/auxilary_functions.py | 339 | 4.03125 | 4 | def even(x):
return x % 2 == 0
def odd(x):
return not even(x)
def divideable_by(number, divider):
return number % divider == 0
if __name__ == '__main__':
print(even(20))
print(odd(20))
print(odd(5))
print(even(5))
print(divideable_by(20, 3))
print(divideable_by(21, 3))
print(divideable_by(5, 3))
print(di... |
24c2ccca9b1798668222d118458f0ab3b2fd2bf6 | brnstz/highlit | /base.py | 2,980 | 3.515625 | 4 | #!/usr/bin/python
import sys
from optparse import OptionParser
# This array acts as a mapping from decimal values to encoded characters
DEC_TO_ENC = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
MAX_BASE = len(DEC_TO_ENC)
# Reverse the mapping from encoded characters to decimal values
ENC_TO_DEC... |
de93c0f0c9fbcca763ee3920c3f77457ac445cd3 | Khushalsawant/multithreading-Tutorial | /tutorial_G.py | 2,244 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 19:26:32 2019
@author: KS5046082
"""
'''
Thread-local data is data whose values are thread specific.
To manage thread-local data, just create an instance of local (or a subclass) and
store attributes on it
'''
#https://docs.python.org/3/library/threading... |
79d8085cb879c116c4092396ecc83fa1b7f2b5d2 | SanaaShah/Python-Mini-Assignments | /6__VolumeOfSphere.py | 290 | 4.5625 | 5 | # 6. Write a Python program to get the volume of a sphere, please take the radius as input from user. V=4 / 3 πr3
from math import pi
radius = input('Please enter the radius: ')
volume = 4 / (4 * pi * 3 * radius**3)
print('Volume of the sphere is found to be: '+str(round(volume, 2)))
|
4ac590cb424a5d27fc41ccfe671b7c42db027139 | SanaaShah/Python-Mini-Assignments | /30__OccurenceOfLetter.py | 331 | 4.21875 | 4 | # 30. Write a Python program to count the number occurrence of a specific character in a string
string = input('Enter any word: ')
word = input('Enter the character that you want to count in that word: ')
lenght = len(string)
count = 0
for i in range(lenght):
if string[i] == word:
count = count + 1
p... |
53577eb885ed53f2ba4c0d09fa7a0262ff6fdb2f | SanaaShah/Python-Mini-Assignments | /2__checkPositive_negative.py | 350 | 4.4375 | 4 | # 2. Write a Python program to check if a number is positive, negative or zero
user_input = float(input('Please enter any number: '))
if user_input < 0:
print('Entered number is negative.')
elif user_input > 0:
print('Entered number is positive')
elif user_input == 0:
print('You have entered zero, its ne... |
f81383ec7b0b8be08c8c40ec057866c6b4383879 | SanaaShah/Python-Mini-Assignments | /1__RadiusOfCircle.py | 299 | 4.53125 | 5 | # 1. Write a Python program which accepts the radius of a circle from the user and compute the area
from math import pi
radius = float((input('Please enter the radius of the cricle: ')))
print('Area of the circle of radius: '+str(radius) + ' is found to be: '+str(round((pi * radius**2), 2)))
|
5855c748d9bbf39f21b17c8e7474a54c3876e8da | SanaaShah/Python-Mini-Assignments | /31__GCD.py | 375 | 3.921875 | 4 | # 31. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
if num1 > num2:
num1, num2, = num2, num1
for i in range(num1, 0, -1):
if num1 % i==0 and num2 % i == 0:
resu... |
06827bf14302ec76a9b9d64a66273db96e3746fa | duplys/duplys.github.io | /_src/recursion/is_even.py | 557 | 4.59375 | 5 | """Example for recursion."""
def is_even(n, even):
"""Uses recursion to compute whether the given number n is even.
To determine whether a positive whole number is even or odd,
the following can be used:
* Zero is even
* One is odd
* For any other number n, its evenness is the same as n-2
... |
888eb60d4b5d14ebb3d5f1b591eed108762a7eec | bernard-david/bank_account | /bank_account.py | 1,392 | 3.9375 | 4 | class BankAccount:
accounts = []
def __init__(self, int_rate = 0.01, balance = 0):
self.int_rate = int_rate
self.balance = balance
BankAccount.accounts.append(self)
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
... |
04a03702a50541371901b405923ee3d58c5c185e | nuttanon001/FirstPython | /FirstPython/FirstPython/FirstLearning/datetime_1.py | 661 | 3.625 | 4 | import datetime
#Print Date Now
print(datetime.datetime.now())
#Set datetime
dt = datetime.datetime(2016,10,21)
print(dt);
#Time delta
delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8)
print(delta.days, delta.seconds, delta.microseconds)
#Total seconds
print('Total Sec:',delta.total_seconds())
#delta ... |
b8e4617a9d524888d0706e6d502dd7eb47d57c79 | nuttanon001/FirstPython | /FirstPython/FirstPython/SecondLearning/dog_class.py | 623 | 3.984375 | 4 | class Dog():
"""description of dog"""
def __init__(self,name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a gog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
... |
877144fe4accfde93cd443fe7fc4e4bb2a203b76 | MateuVieira/Python | /An Introduction to Interactive Programming in Python (Part 1)/Week_1/Week_1b/Program.py | 12,498 | 4.0625 | 4 | # ------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------
# Compute whether an integer is even.
###################################################
# Is even formula
# Student should enter function on th... |
bc24b47dc28c354bd8515d81d49d2bab16f45578 | Param9498/Artificial-Intelligence-Projects | /Project 1 - Sudoku/AIND-Sudoku/solution_backup.py | 8,901 | 3.71875 | 4 | import sys
assignments = []
boxes = []
row_unit = []
col_unit = []
square_unit = []
unit_list = []
units = {}
peers = {}
diag_unit = []
hasBeenInitialized = False
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it upda... |
05b3486a38e4d9c5b57aca987fa4db8c45885316 | bjozwicki/projects | /Prime check/Prime check_v1.py | 702 | 3.6875 | 4 | """ Prime generator
Changes:
Basic prime check
AVG = 128,0s
"""
from math import sqrt
from time import time
def is_prime(x):
if x < 2:
return False
for n in range(2, x):
if x % n == 0:
return False
return True
def prime_generator():
count = 0
... |
d50a4caeae0595d00d3cf27934bd1cc7cc70f5d0 | Jose-Padilla971805/Tarea_Menu4 | /taller3.py | 1,387 | 3.84375 | 4 | import os
def ejercicio3():
class Banco:
def __init__(self):
self.cliente1=Cliente("jose")
self.cliente2=Cliente("pablo")
self.cliente3=Cliente("luis")
def operacion(self):
self.cliente1.depositar(1500000)
... |
464078ad86e8bdad48a8e892633d981e43981cf7 | Bthorb/grade | /gradeConvert.py | 533 | 3.734375 | 4 |
#grade โปรแกรมแปลงเกรดที่อยู่ในรูปตัวอักษรเป็นตัวเลข cr : Benjaporn Kittivichainchai 61172310280-8 CPE.61231
grade = input("Your score = ")
def grade1(grade):
if grade == "A" :
print ("80-100")
elif grade == "B" :
print ("70-79")
elif grade == "C" :
print ("60-69")
eli... |
2f8406cb760b02b69b5be9ba7cc417939e56553d | dragonsun7/dsPyLib | /demo/thread/thread_queue.py | 1,010 | 3.625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'Dragon Sun'
__date__ = '2022-05-17 11:06:18'
"""
线程,利用队列
"""
import queue
import threading
import time
class Worker(threading.Thread):
def __init__(self, name: str, q: queue.Queue):
super(Worker, self).__init__()
self.name = name
self.q = q
... |
c367b8ab67edd0f7b91e38bb16078c3c0be5ac22 | dragonsun7/dsPyLib | /dsPyLib/utils/number.py | 1,868 | 3.8125 | 4 | # -*- coding:utf-8 -*-
__author__ = 'Dragon Sun'
__date__ = '2020-05-20 14:35:38'
from math import nan, isnan
def is_odd(n: int) -> bool:
"""
判断是否为奇数
"""
return n % 2 == 0
def is_even(n: int) -> bool:
"""
判断是否为偶数
"""
return not is_odd(n)
def get_decimal_digit(f: float) -> int:
... |
e3d3ca4aeaa513526556d6cef56a87abab455070 | ronnix/50-shades-of-fizzbuzz | /2_test_names.py | 506 | 3.703125 | 4 | # Refactor tests to better express the different categories
def say(n: int) -> str:
if (n % 15) == 0:
return "fizzbuzz"
if (n % 3) == 0:
return "fizz"
if (n % 5) == 0:
return "buzz"
return str(n)
def test_say_the_number():
assert say(1) == "1"
def test_say_fizz_if_multi... |
c3a181aea806b68ce09197560eeb485ca6d8419d | jamesb97/CS4720FinalProject | /FinalProject/open_weather.py | 1,535 | 4.25 | 4 | '''
Python script which gets the current weather data for a particular zip code
and prints out some data in the table.
REST API get weather data which returns the Name, Current Temperature,
Atmospheric Pressure, Wind Speed, Wind Direction, Time of Report.
'''
import requests
#Enter the corresponding api key from... |
022297bf19b6395f6f1aa7985f5f01bf54a33b09 | stnamjef/algorithms | /python3/graph_coloring.py | 749 | 3.5625 | 4 | def promising(i, color):
switch = True
j = 0
while j < i and switch:
if adj[i][j] == 1 and color[i] == color[j]:
switch = False
j += 1
return switch
def graph_color(i, color):
if promising(i, color):
if i == n - 1:
print('sol [ ', end='')
... |
90e4ae18d1365e49615f75953f43b7482a0f0b73 | MariosPitsali/battleship | /battleship.py | 2,001 | 3.921875 | 4 | #so, we are going to create a version fo the battleship game
#at first it will serve one player
from random import randint
from battleship_classes import Carrier, Battleship, Cruiser, Destroyer, Submarine
import battleship_classes
def create_board(x=5):
lst = ["O" for y in range(x)]
return lst
def check_... |
0e01612493b7e2b6a62e9f07411e7befb5380ac8 | ovimura/cs541-ai | /final/draft3/gthrandom.py | 1,577 | 3.53125 | 4 | #!/usr/bin/python3
# Random-move Gothello player.
import random
import sys
import gthclient
me = sys.argv[1]
opp = gthclient.opponent(me)
client = gthclient.GthClient(me, "localhost", 0)
def letter_range(letter):
for i in range(5):
yield chr(ord(letter) + i)
board = {letter + digit
for lette... |
3cd1dcfc9b03d500b343c59004adbe6dde3b5806 | ovimura/cs541-ai | /final/final/submission-gothello-player/minimax.py | 7,162 | 3.59375 | 4 | # CS541: AI
# Author: Ovidiu Mura
# Implementation of the Minimax algorithm with the alpha, beta pruning
from copy import deepcopy
import time
import random
from game_rules import *
class State(object):
def __init__(self):
'''
The constructor
'''
self.last_move = None
self.... |
f100da53354a4058eed4116ef0570b665256e3f1 | StankovicAleksa/SEA-SAGE | /schoof/field/int_q/int_q.py | 1,658 | 3.890625 | 4 | r"""In this file required methods and classes for handling
modular arithmetic are defined"""
from field import Field,FieldElement
class F_qField(Field):
def __init__(self,q):
self.q=q
def add(self,el_1,el_2):
val=el_1.val+el_2.val
if ( val > self.q) :
val-=self.q
ret... |
c293d1d260b8ec0e9bd9e476fd3db93d566670cb | beatthem/roman_and_arabic | /roman_numbers/roman_to_arabic.py | 3,882 | 3.96875 | 4 | """
Roman numbers to arabic converter.
LICENSE: MIT
Author: Ruslan Khalikov <khalikoff@gmail.com>
"""
# class RomanNumbers():
from collections import defaultdict
TUPLE_ROMAN = (
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000),
)
TUPLE_ADDITIONAL = (
('G',... |
d686e4c0ffb9bc3c84b5f7059892d7a7d53d1336 | praroh2/McqTester | /helper.py | 2,103 | 3.765625 | 4 | import encrypt as e
import json, random, copy
def askQ(Precord, Pkey):
"""
Decrypts the contents of the question, displays it and takes input.
"""
global Gscore, Gtotal
print('\n#################################################################\n')
Lrecord = e.decryptRecord(Precord, Pkey)
L... |
18200cb8e9e584fe454d57f3436a9184159388b8 | ayoubabounakif/edX-Python | /ifelifelse_test1_celsius_to_fahrenheit.py | 811 | 4.40625 | 4 | #Write a program to:
#Get an input temperature in Celsius
#Convert it to Fahrenheit
#Print the temperature in Fahrenheit
#If it is below 32 degrees print "It is freezing"
#If it is between 32 and 50 degrees print "It is chilly"
#If it is between 50 and 90 degrees print " It is OK"
#If it is above 90 degrees prin... |
7a15380cd4a2b7639f2be1607fc8105a1f3bc8ef | ayoubabounakif/edX-Python | /dict_value_containing_key.py | 327 | 3.953125 | 4 | def return_keys(dict, value):
sorted_list = []
keys = dict.keys()
for k in keys:
if value in dict[k]:
sorted_list.append(k)
sorted_list.sort()
return sorted_list
dict = {"rabbit" : [1, 2, 3],
"kitten" : [2, 2, 6],
"lioness": [6, 8, 9]}
print (return_keys(dic... |
53785f092aca8c0d7efc31a896af49fe7d736f71 | ayoubabounakif/edX-Python | /functions_monthly_payment_for_loan.py | 538 | 3.703125 | 4 | def monthly_loan(principal, annual_interest_rate, duration): # Function w 3 arguments
r = (annual_interest_rate / 100) / 12 # Define r
n = (duration * 12) # Define n
if r == 0: # Check if r equals 0
monthly_payment = principal / n # If it is, do the following
else: # If r i... |
bd6d2c0ea0e678bc732dfbe3261d9f4f55e20da7 | ayoubabounakif/edX-Python | /zip.py | 188 | 4.03125 | 4 | x = [1, 2, 3, 4, 5]
y = ['a','b','c','d']
zipped = list(zip(x, y))
print("The result of the operation is:", zipped)
|
b9804e7911242e9c4eae1074e8ef2949155d60e0 | ayoubabounakif/edX-Python | /sorting.py | 515 | 4.125 | 4 | # Lets sort the following list by the first item in each sub-list.
my_list = [[2, 4], [0, 13], [11, 14], [-14, 12], [100, 3]]
# First, we need to define a function that specifies what we would like our items sorted by
def my_key(item):
return item[0] # Make the first item... |
69a013cc70ae9b6dff07cb3f7cf3c7061bf7e234 | ayoubabounakif/edX-Python | /midterm_exam_part4_list_of_primes.py | 707 | 3.859375 | 4 | def list_of_primes(n):
output_list = []
for i in range(2, n):
#print (i)
isPrime = True
for num in range(2, i):
#print (num)
if i % num == 0:
print (i%num)
isPrime = False
if isPrime:
output_list.a... |
f3019b4227dfd2a758d0585fb1c2f9e27df1b8e9 | ayoubabounakif/edX-Python | /quizz_1.py | 275 | 4.28125 | 4 | #a program that asks the user for an integer 'x'
#and prints the value of y after evaluating the following expression:
#y = x^2 - 12x + 11
import math
ask_user = input("Please enter an integer x:")
x = int(ask_user)
y = math.pow(x,2) - 12*x + 11
print(int(y))
|
1f60330816a225aa8c4372994e8f4f2266c783bd | ayoubabounakif/edX-Python | /find_a_word_in_a_crossword.py | 2,500 | 3.6875 | 4 | def find_word_horizontal(crosswords, word):
if not crosswords or not word: # If empty then return None
return None
for index, row in enumerate(crosswords):
temp_str = ''.join(row)
if temp_str.find(word) >= 0:
return [index,temp_str.find(word)]
def find_word_vertical(crosswor... |
7013c99a792f116a7b79f4ad1a60bfb3f4b1a8a2 | ayoubabounakif/edX-Python | /quizz_2_program4.py | 1,141 | 4.34375 | 4 | #Write a program that asks the user to enter a positive integer n.
#Assuming that this integer is in seconds,
#your program should convert the number of seconds into days, hours, minutes, and seconds
#and prints them exactly in the format specified below.
#Here are a few sample runs of what your program is suppos... |
c56b0c77f3975bf01aeea306bf097e05fd753cdb | ayoubabounakif/edX-Python | /functions_sgi_sco_4.py | 843 | 3.984375 | 4 | # 4. Something goes in, something comes out.
''' This is probably the most meaningful scenario where the function
takes some arguments and performs some task using those
arguments and returns some result as well. '''
def calculate_area(length, breadth):
area = length * breadth
perimeter = 2*length... |
5f4a7dc2f0477162c179ccb915e7ef4fd0bbc395 | ayoubabounakif/edX-Python | /midterm_exam_part8_unique_common_elements.py | 761 | 4.03125 | 4 | ###### MY CODE ######
def unique_common(a, b):
test_list = []
for i in a:
if i in b:
test_list.append(i)
if not test_list:
return None
common_list = []
for i in test_list:
if i not in common_list:
common_list.append(i)
return sorted... |
940e284ec16e99a3349d00e0611e487cdce976f1 | ayoubabounakif/edX-Python | /quizz_3_part3.py | 397 | 4.1875 | 4 | # Function that returns the sum of all the odd numbers in a list given.
# If there are no odd numbers in the list, your function should return 0 as the sum.
# CODE
def sumOfOddNumbers(numbers_list):
total = 0
count = 0
for number in numbers_list:
if (number % 2 == 1):
total += ... |
3bf6f6395bfae5f4581cacc645f214ecc5b8f618 | ayoubabounakif/edX-Python | /dictionary_methods.py | 447 | 3.96875 | 4 | numbers={1: 2, 3:4}
numbers.pop(3)
print (numbers)
d={"uno":["one",1],"dos":["two",2],3:["tres","three"]}
print (d.pop("dos"))
d={"uno":["one",1],"dos":["two",2],3:["tres","three"]}
print (d.get(3,'cat'))
numbers={"one": "uno", "two": "dos", "three": "tres"}
print (numbers.get("one","test"))
d={"uno":"one","dos":"t... |
9774dac844cb3985d733af0c87e697b85f93be88 | ayoubabounakif/edX-Python | /for_loop_ex2.py | 296 | 4.3125 | 4 | #program which asks the user to type an integer n
#and then prints the sum of all numbers from 1 to n (including both 1 and n).
# CODE
ask_user = input("Type an integer n:")
n = int(ask_user)
i = 1
sum = 0
for i in range(1, n+1):
sum = sum + i
print (sum)
|
3de935bb1e24cc122553fca385d13be12e65e5e7 | ayoubabounakif/edX-Python | /list_to_tuples_&&_calculate_grades_&&_formatted_print_&&_calculate_expenses.py | 4,614 | 3.953125 | 4 | # Commented codes will output and Error
"""my_string = "x = {1:5.2f} and y = {0:3d}".format(14, 3.5)
print(my_string)
my_string = "x = {} and y = {}".format(5, "pet")
print(my_string)
# my_string = "x = {} and y = {}".format(2.3)
# print(my_string)
my_string = "x = {2} and y = {1}".format("cat", 2.3,... |
6b3d189815e6fee1169f72bed1d402504cd142d9 | ayoubabounakif/edX-Python | /sum_of_a_2D_list.py | 247 | 3.71875 | 4 | ###### MY CODE ######
def sum_2d(list):
sum = 0
for row in range(len(list)):
for column in range(len(list[0])):
sum = sum + list[row][column]
return sum
print (sum_2d([[-18, 20, 13, 44], [-12, -6, 13, -44]]))
|
3de9211ef9945e78db5734f3349e2bab22cb36b9 | ayoubabounakif/edX-Python | /2d_list_of_col_max.py | 347 | 3.9375 | 4 | def max_col_2d(list):
output_list = []
for col in range(len(list[0])):
column_max = 0
for row in list:
if row[col] > column_max:
column_max = row[col]
output_list.append(column_max)
return output_list
print (max_col_2d([[1, 1, 1, 12], [10, 2, 2, 2], [3, 3... |
0225a9fc2483858298001a287a9e9d3afe3d78e9 | RayWillett/Euler | /e6 | 268 | 3.71875 | 4 | #!/usr/bin/env python3
def sumOfSquares(r):
sum = 0
for i in range(1, r+1):
sum += i**2
return sum
def squareOfSum(r):
sum = 0
for i in range(1, r+1):
sum += i
return sum**2
print(sumOfSquares(100) - squareOfSum(100))
|
5330bfb69e80d8fa0589c0aa6ddeadf44beb7ddb | fingerman/python_fundamentals | /python-fundamentals/exam_Python_09.2018/4.Books.py | 4,079 | 3.796875 | 4 | '''
Problem 4. Books
Input / Constraints
You are asked to write a program for a bookstore. Your task is to create a software, which tells the sellers if there is a requested book in stock or not. If there is you should sell it and at the end of the workday the software should list all sold books and the sum of their pr... |
0d91ac265f2efc25902758f309817b33515a272f | fingerman/python_fundamentals | /python_bbq/Project_Modules/my_modules/vsearch.py | 318 | 3.78125 | 4 | #################
def search4vowels(phrase: str) ->set:
"""Return any vowels in phrase"""
vowels = set('aeiouAEIOU')
return vowels.intersection(set(phrase))
def search4letters(phrase: str, letters: str) ->set:
"""Return letters found in string"""
return set(letters).intersection(set(phrase))
|
099d6d3f902db44ebbc8078a68ef87acc9029a25 | fingerman/python_fundamentals | /python_bbq/OOP/_OOP_Inheritance_Ex1.py | 172 | 4.03125 | 4 | class A:
X = 0 # X will be overwritten at each object creation
def __init__(self, v=0):
self.Y = v
A.X += v
a = A()
b = A(1)
c = A(2)
print(c.X) |
69b29ccaa611a0e92df5f8cd9b3c59c231847b72 | fingerman/python_fundamentals | /python-fundamentals/4.1_dict_key_value.py | 1,032 | 4.25 | 4 | '''
01. Key-Key Value-Value
Write a program, which searches for a key and value inside of several key-value pairs.
Input
• On the first line, you will receive a key.
• On the second line, you will receive a value.
• On the third line, you will receive N.
• On the next N lines, you will receive strings in the following ... |
2bec4f16f93d55723446179bc12aa4a57ea59ce8 | fingerman/python_fundamentals | /python_bbq/OOP/oop_getter_setter.py | 332 | 3.75 | 4 | class Member:
def __init__(self, age = 0):
self._age = age
# getter method
def get_age (self):
return self._age
# setter method
def set_age (self, x):
self._age = x
Uwe = Member()
# setting the age using setter
Uwe.set_age(21)
# retrieving age using getter
print(Uwe.get_age ())
prin... |
822ba7ba635ee6ac011ad1ba43d5874cfc04be0b | fingerman/python_fundamentals | /python_bbq/OOP/Modules/auto_private.py | 468 | 4.03125 | 4 | class AutoPrivate:
def __init__(self, speed=0): # self is the current object/instance
self.__speed = speed # both speeds are different things. Second speed is the value of speed
def speed_up(self, speed):
self.__speed += speed
return self.__speed
# cannot give - car.spe... |
949e23d9fafea186e93910522bba041d8cef2220 | fingerman/python_fundamentals | /python_bbq/Exceptions/raise_Exception_as.py | 237 | 3.625 | 4 | try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise Exception("That is not a positive number!", "Get out of here!")
except Exception as ve: # prints the error
#print(ve)
print(len(ve.args)) |
2d56591dc280d9862ffe84fc61eba9f524cffade | fingerman/python_fundamentals | /intro/7_4_loop2_even_power.py | 92 | 3.90625 | 4 | n = int(input())
num = 1
print(num)
for i in range(1, n, 2):
num = num*4
print(num)
|
b6972b86bbbaec28dba923e77c57791c6a5fa582 | fingerman/python_fundamentals | /python_bbq/Exceptions/try_except_else.py | 419 | 3.84375 | 4 | def reciprotial(n):
try:
n = 1/n
except ZeroDivisionError:
print("Not Reciprotial")
return None
else:
print("Everything went Fine")
return n
finally:
print("Programm finished execution")
print(reciprotial(2))
print(reciprotial(0))
'''
code in the else c... |
41b3d14d2ff362836aaf33ab6d7af0382b240d22 | fingerman/python_fundamentals | /python_bbq/1tuple/tup_test.py | 580 | 4.40625 | 4 | """
tuples may be stored inside tuples and lists
"""
myTuple = ("Banane", "Orange", "Apfel")
myTuple2 = ("Banane1", "Orange1", "Apfel1")
print(myTuple + myTuple2)
print(myTuple2[2])
tuple_nested = ("Banane", ("Orange", "Strawberry"), "Apfel")
print(tuple_nested)
print(tuple_nested[1])
print(type(tuple_nested[1]))
... |
1d4fe678b49eeea6e449a4cf2b97b7a9ba77d99a | fingerman/python_fundamentals | /python-fundamentals/exam_Python_08.2018/4.GladiatorArena.py | 5,149 | 3.890625 | 4 | class Gladiator:
def __init__(self, name):
self.name = name
self.techniques = {}
# add his technique or update his skill, only if the current technique skill is lower than the new value.
def add_skill(self, technique_new, skill_new):
if technique_new not in self.techniques:
... |
5bc59048efd64a2a629eae559c8165d4bfc7e154 | fingerman/python_fundamentals | /python_bbq/1lists/list_comprh_if_else_1.py | 220 | 3.75 | 4 | list = []
for x in range(10):
list.append(1 if x % 2 == 0 else 0) # that s generator in the parentheses
print(list)
# ---------------------------
lst = [1 if x % 2 == 0 else 0 for x in range(10)]
print(lst)
|
9bc8dcc609cd1f3b293d9951e3c26415516d1b62 | fingerman/python_fundamentals | /intro/1.4_loop_rectangle.py | 85 | 3.53125 | 4 | b1 = float(input())
b2 = float(input())
h = float(input())
print((b1 + b2) * h / 2)
|
c16d0634448865eeabe9f4f418785f1b9f262569 | fingerman/python_fundamentals | /python_advanced/iterator_.py | 1,268 | 3.8125 | 4 | class Iterable:
def __init__(self, start, end):
self.value = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current
# Aufga... |
67aba8144cf2bb61f3f0ab2c4e47f3fbbf1b9de9 | fingerman/python_fundamentals | /python_bbq/OOP/oop_inher_mult.py | 615 | 3.859375 | 4 | '''
We can say that Python looks for object components in the following order:
inside the object itself;
in its superclasses, from bottom to top;
if there is more than one class on a particular inheritance path, Python scans them from left to right.
'''
class Left:
Var = 'L'
VarL = 'LL'
def fun(self):
... |
f508eb506fb30f8298fa205b7e54323159bcb304 | fingerman/python_fundamentals | /python_bbq/1lists/list_comprehension.py | 448 | 3.59375 | 4 | list_str = ['berLin', 'HamBurg', 'PytHoN iSt coOl', 'Katze iSt Kein hunD']
wordsA = [[i] for i in list_str]
print(wordsA)
wordsB = [i.split(' ') for i in list_str]
print(wordsB)
wordsC = [i.capitalize() for i in list_str]
print(wordsC)
print("#-----------------------------------")
l = [j for i in range(2, 8) for j... |
79a1a8068f0e22ebfc6be926bb578734676d001f | fingerman/python_fundamentals | /python_bbq/enumerate.py | 91 | 3.65625 | 4 | alphabet = ['a', 'b', 'c', 'd', 'e', 'f']
for k, v in enumerate(alphabet):
print(k, v) |
b0936ba1bc7bc61bec45b91ebb9467b0da6cd47e | fingerman/python_fundamentals | /python_bbq/OOP/008 settergetter.py | 1,220 | 4.46875 | 4 | class SampleClass:
def __init__(self, a):
## private varibale or property in Python
self.__a = a
## getter method to get the properties using an object
def get_a(self):
return self.__a
## setter method to change the value 'a' using an object
def set_a(self, a):
sel... |
067b0df2dce9f8d346e63dfcf27d8ad435556e87 | fingerman/python_fundamentals | /python_bbq/yeld_fruits.py | 247 | 3.515625 | 4 | def fruits():
yield "Mango"
yield "Orange"
yield "Apple"
yield "Strawberry"
allf = fruits()
for i in allf:
print(i)
def foo():
for i in range(0, 10):
yield i
print(foo())
for i in foo():
print(i)
print(foo()) |
62f70f2253e5a34085dde004f5456f3a983444f9 | fingerman/python_fundamentals | /python-fundamentals/exam_Python_08.2018/try.py | 372 | 3.8125 | 4 | class Gladiator:
def __init__(self, name, technique, skill):
self.name = name
self.technique = technique
self.skill = int(skill)
def __hash__(self):
return self.name.__hash__
def __eq__(self, other):
return self.name == other.name
line = input()
gladiators_list = ... |
0492e7e7cc6d822d2be3fe1768fc9ba438df16bf | fingerman/python_fundamentals | /python-fundamentals/exam_tasks/progF_task3_07.2017.py | 3,788 | 3.828125 | 4 | '''
Input
Pesho-Java-84
Gosho-C#-70
Gosho-C#-84
Annabel-C#-84
Kiro-C#-94
exam finished
Output
Results:
Kiro | 94
Gosho | 84
Pesho | 84
Submissions:
C# - 3
Java - 1
'''
class Student:
def __init__(self, name):
self.name = name
self.results = {}
# add his language and/or update points, only... |
45b01f271a65e346353cc5fcd18383ff480b8c9d | fingerman/python_fundamentals | /python-fundamentals/exam_Python_09.2018/1.DateEstimation.py | 1,251 | 4.4375 | 4 | '''
Problem 1. Date estimation
Input / Constraints
Today is your exam. It’s 26th of August 2018. you will be given a single date in format year-month-day. You should estimate if the date has passed regarding to the date mention above (2018-08-26), if it is not or if it is today. If it is not you should print how many ... |
abc46b6da5e8ebbd8f7e6f02add08ab8e9b81982 | fingerman/python_fundamentals | /intro/7_5_loop2_2k+1.py | 112 | 3.71875 | 4 | n = int(input())
num = 1
print(num)
for i in range(0, n):
num = num*2+1
if num <= n:
print(num)
|
d1d7f48647893caeefd979258abd684763d507ba | rgbbatista/devaria-python | /exercícios 2.py | 1,859 | 4.25 | 4 |
'''Escrever um prog que recebe dois num e um operador
matemático e com isso executa um calculo corretamente'''
def soma(num1 , num2): # criando função
print('Somando', num1 + num2)
resultado = num1 + num2
return resultado
def subtracao(num1 , num2): # criando função
print('Subtraindo', num1 - num2)
... |
23cf7b7d330dc02542dd9b00d1dafbb0f5bd9eec | RobertSzefler/summercamp2015 | /solutions/dbapi_task1.py | 351 | 3.5 | 4 | from MySQLdb import connect
connection = connect(host='localhost', user='test', passwd='test', db='test')
cursor = connection.cursor()
cursor.execute('''
SELECT name FROM persons p
WHERE p.id NOT IN (
SELECT person1_id FROM friends UNION SELECT person2_id FROM friends
)
ORDER BY p.name
''')
for row in cursor.fetc... |
ec67e60dc31824809ecf5024ce76c1708a46b295 | rmalarc/is602 | /hw1_alarcon.py | 1,967 | 4.28125 | 4 | #!/usr/bin/python
# Author: Mauricio Alarcon <rmalarc@msn.com>
#1. fill in this function
# it takes a list for input and return a sorted version
# do this with a loop, don't use the built in list functions
def sortwithloops(input):
sorted_input = input[:]
is_sorted = False
while not is_sorte... |
1ead53f839aedb80b3d3360ad1d1c972710a2d69 | Austinkrobison/CLASSPROJECTS | /CIS210PROJECTS/PROJECT3/DRAW_BARCODE/draw_barcode.py | 2,588 | 4.15625 | 4 |
"""
draw_barcode.py: Draw barcode representing a ZIP code using Turtle graphics
Authors: Austin Robison
CIS 210 assignment 3, part 2, Fall 2016.
"""
import argparse # Used in main program to obtain 5-digit ZIP code from command
# line
import time # Used in main program to pause program before exit
impo... |
65473926534dee31931a32f645585bd798fde1cd | JocelynLuizzi/NBABubbleAdvantage | /webscraper.py | 4,252 | 3.53125 | 4 |
# https://jaebradley.github.io/basketball_reference_web_scraper/api/
from basketball_reference_web_scraper import client
from basketball_reference_web_scraper.data import Outcome, OutputType, TEAM_TO_TEAM_ABBREVIATION
import pandas as pd
import datetime as dt
def get_full_season_scores(year):
'''
creates a... |
c7c9caa908cf51aa0a9b13be6fa6bf9ed8729729 | masterliu/helloword | /part 100/part32.py | 121 | 4 | 4 | # -*- coding: UTF-8 -*-
a = ['one', 'two', 'three']
# 切片处理,将列表的数据反转
for i in a[::-1]:
print (i)
|
ddffc0912884d8c214da7441eeec4b7e049e4e1a | masterliu/helloword | /tyr_except.py | 239 | 3.65625 | 4 | # -*- coding: UTF-8 -*-
# 触发 eoferror异常
import sys
try:
s = input('enter something--->')
except EOFError:
print('\n Why did you do an EOFonme?')
sys.exit()
# except:
# print '\n some error/exception occurred.'
print('Done')
|
57dd61265f84262b65700ef50f1b4fe665de59c0 | masterliu/helloword | /part 100/part28.py | 433 | 3.5 | 4 | # -*- coding: UTF-8 -*-
# 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。
# 问第4个人岁数,他说比第3个人大2岁。问第三个人,
# 又说比第2人大两岁。问第2个人,说比第一个人大两岁。
# 最后问第一个人,他说是10岁。请问第五个人多大?
def age(n):
if n == 1:
c = 10
else:
c = age(n - 1) + 2
return c
print age(5)
|
9422a1eb8a9fa9766ba27812bd55bb6f81263f98 | masterliu/helloword | /part 100/part25.py | 133 | 3.65625 | 4 | # -*- coding: UTF-8 -*-
# 求 1+2!+3!.....+20!
n = 0
s = 0
t = 1
for n in range(1,21):
t *= n
s += t
print 'sumer is %d'% s
|
955d0b3fc23a9a9db23ae14f0480c24997721a8c | masterliu/helloword | /fishc/fishc4.py | 248 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
# o = []
# num = 0
# for n in range(0, 100):
# if n % 2 == 0:
# o.append(n)
# num += 1
#
# else:
# print(n)
i = 0
while i <= 100:
if i % 2 != 0:
print(i, end=' ')
i += 1
else:
i += 1
|
274051fafb686decda51f45c767a27ddfd77e5f4 | masterliu/helloword | /other/part15.py | 440 | 3.96875 | 4 | # -*- coding: UTF-8 -*-
# x起始,Y是借用,z是目的
# 汉诺塔 游戏
def hanoi(n, x, y, z):
if n == 1:
print(x, '---->', z)
else:
# 将n-1个盘子从X移动到Y
hanoi(n - 1, x, z, y)
# 将最底下的最后一个盘子从X移动到z
print((x, '--->', z))
# 将y上的N-1个盘子移动到z
hanoi(n - 1, y, x, z)
n = int(input('input nu... |
fbe981c8541478a05269e5e417a712d49a7abd61 | masterliu/helloword | /part 100/part27.py | 292 | 3.921875 | 4 | # -*- coding: UTF-8 -*-
# 利用递归函数,将输入的字符,以相反的顺序打印出来.
def output(s, l):
if l == 0:
return
print (s[l-1])
output(s, l-1)
s = str(raw_input('input a string:'))
# 3.0的python,raw_input取消,由input()替换
l = len(s)
output(s, l) |
f2a5acb7d0c570fb74186abeecb7d412de17c3b2 | LeahSchwartz/CS101 | /APTProblemSets/Set4/MinCostPalindrome.py | 863 | 3.5 | 4 | '''
Created on Oct 13, 2017
@author: leahschwartz
'''
def getMinimum(s, oCost, xCost):
pos = 0
answer = 0
sList = list(s)
while True:
if pos >= len(sList):
break
if sList[pos] == "?":
if sList[-pos - 1] == "x":
sList[pos] = "x"
an... |
f6aa5e301d9ec35883bc949ae0792c109694b33e | LeahSchwartz/CS101 | /APTProblemSets/Quizzes/PotentialValue.py | 211 | 3.609375 | 4 | '''
Created on Sep 24, 2017
@author: leahschwartz
'''
def compute(itema, itemb):
answer = (5* float(itema) / 3) + ((float(itemb)**2)/7 )
return answer
if __name__ == '__main__':
print compute(9, 3) |
311bd682edc41b6a10fb86b764758329cb93d4e9 | LeahSchwartz/CS101 | /APTProblemSets/Set5/AnagramFree.py | 240 | 3.609375 | 4 | '''
Created on Oct 18, 2017
@author: leahschwartz
'''
def getMaximumSubset(words):
return len(set(["".join(sorted(w)) for w in words]))
if __name__ == '__main__':
print getMaximumSubset(["abcd","abac","aabc","bacd"])
|
68634cfe1786aa3552d42a476b07f9959c1c2e02 | LeahSchwartz/CS101 | /APTProblemSets/Set5/BagFitter.py | 528 | 3.65625 | 4 | '''
Created on Oct 24, 2017
@author: leahschwartz
'''
def bags(strength, food):
foodDict = {}
answer = 0
for group in food:
if group not in foodDict:
foodDict[group] = 1
else:
foodDict[group] += 1
for item in foodDict:
answer = answer + int(foodDict[item]... |
6419af2d0a143f916cbd755ebab85f72310b14e7 | LeahSchwartz/CS101 | /APTProblemSets/Set5/EatingGood.py | 414 | 4 | 4 | '''
Created on Oct 24, 2017
@author: leahschwartz
'''
def howMany(meals, restaurant):
answerList = []
for item in meals:
itemSplit = item.split(":")
if itemSplit[1] == restaurant and itemSplit[0] not in answerList:
answerList.append(itemSplit[0])
return len(answerList)
... |
c925457aa1a4f5304cd7f17c6910d51483308f7d | LeahSchwartz/CS101 | /APTProblemSets/Quizzes/DifferentEnds.py | 476 | 3.921875 | 4 | '''
Created on Sep 24, 2017
@author: leahschwartz
'''
def countVowelWords(phrase):
total = 0
phrase = phrase.split()
for word in phrase:
if isVowel(word[0]) and isVowel(word[-1]):
if word[0] != word[-1]:
total = total + 1
return total
def isVowel(ch):
if ch in... |
344e97d50d390cc876bcea297fbb935ebbc1c634 | vineetkoppalkar/COMP-472 | /grid.py | 4,849 | 3.859375 | 4 | import math
class Grid:
grid_cells = None
width = 0
height = 0
def __init__(self, width, height):
self.width = width
self.height = height
self.grid_cells = self.setup_board()
def setup_board(self):
grid = []
for i in range(self.height):
gridline... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.