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
2c0c67a3a450a75472a3393d74db0f7dc106b2b9
mlstack/e200-tm
/code/e200-predict_simple_linear_regression.py
4,709
3.953125
4
#! /c/Apps/Anaconda3/python """ [Title] Understanding Learning Process [Author] Yibeck Lee(Yibeck.Lee@gmail.com) [Program Code Name] e200-predict_simple_linear_regression.py [Description] - 교육생 실습용 [History] - 2019-05-01 : 최초 작성 - 2019-05-05 : Naming 표준화 개선 [References] - https://www.tensorflow.org - https:...
7a132fc02073113a1d2a39245b183b7350ed5625
ddelgadoJS/GameOfLife
/Algorithm.py
2,619
3.71875
4
from random import randint # Input: rows of grid, columns of grid. # Output: list of desired size, with random life organisms. # Creates array to contain the organisms. def createGrid(rows, columns): grid = [[0 for i in range(rows)] for j in range(columns)] for i in range(0, rows): for j in r...
a3e557867002df8136d341752f1664adc0e09009
Pato9/platzi-python
/introduccion_pensamiento_logico/fibonacci.py
330
3.984375
4
""" recursividad ejemplo fibonacci """ def fibonacci(n): """ Este metodo es demasiado ineficiente """ if n == 0 or n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) n = int(input('Ingrese un numero mayor a 0:')) if n>0: print(f'En el mes {n} habra un total de {fibonacc...
b15223561a2a94b5e76f30e405826e84071c6b7e
Pato9/platzi-python
/estadistica-computacional/probabilidades.py
2,476
3.625
4
import random def mayor_a_numero(cantidad_tiros,numero): dado = [1,2,3,4,5,6] numeros = [] for i in dado: if i>numero: numeros.append(i) if numero>0 and numero<7: total_dados = len(dado) total_posibilidades = len(numeros) print(f'{total_posibilidades}-{t...
b7e1cd08479672a4d231a4b8e7b12c61b195e32c
Pato9/platzi-python
/estadistica-computacional/barajas.py
1,333
3.609375
4
import random import collections PALOS = ["corazon","trebol","diamante","pica"] VALORES = ['as','1','2','3','4','5','6','7','8','9','10','J','Q','K'] def formar_baraja(): cartas = [] for palo in PALOS: for valores in VALORES: cartas.append((palo,valores)) return cartas def ob...
d3eda4714e91b13bd5e007a57af5be14aacd9a78
Pato9/platzi-python
/introduccion_pensamiento_logico/aproximaciones.py
448
3.8125
4
""" aproximacion de soluciones """ objetivo = int(input('Ingrese un numero : ')) epsilon = 0.01 paso = epsilon**2 respuesta = 0.0 while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo: print(abs(respuesta**2-objetivo)) respuesta += paso if abs(respuesta**2 - objetivo) >= epsilon: ...
3af0b975d8fe1dd1f85a860fce8f9438933f9648
Rajat6697/hackerrank-30days-coding-challenge
/Day-3/apple_and_orange.py
1,324
4.03125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countApplesAndOranges' function below. # # The function accepts following parameters: # 1. INTEGER s # 2. INTEGER t # 3. INTEGER a # 4. INTEGER b # 5. INTEGER_ARRAY apples # 6. INTEGER_ARRAY oranges # ...
ba9f96ccc40785bc8d4b07da88221b56f66585a3
PRAVEEN-ARAVENDAN/Self-Learning
/Python Data Structures/Praveen_Stack_Using_Linked_List.py
1,710
3.765625
4
''' STACK OPERATIONS s :- stack n :- node that is being pushed push(s,n) :- pushed at the top of the stack pop(s) :- removes the top element and returns it Note :- A stack is both Abstract Data Type(ADT) and Data Structure. ADT :- Abstract Data type (ADT) is a type (or class) for objects whose behaviou...
e047b285aa5bf1b187187c52a22fae191836ed0f
chubaezeks/Learn-Python-the-Hard-Way
/ex19.py
1,804
4.3125
4
#Here we defined the function by two (not sure what to call them) def cheese_and_crackers (cheese_count, boxes_of_crackers): print "You have %d cheese!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" #We take tha...
5716d35b256e1fd21e84c40b28f1389817ebd777
saikotprof/thinkdiff
/coding-problems/binary-search.py
478
3.921875
4
def binary_search(arr, item): low = 0 high = len(arr) - 1 while low <= high: mid = int((low + high) / 2) if arr[mid] == item: return mid elif arr[mid] < item: low = mid + 1 else: high = mid - 1 return -1 if __name__ == '__main__': ...
8700663af1c7747f2a4a06f8526928122fd7b0c9
sadfool1/Sudoko_solver
/object-oriented-sudoku.py
4,700
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 31 21:26:25 2020 @author: jameselijah """ import numpy as np import random as rn import math import sys import traceback class board_creation: def __init__ (self): board = [ [1,3,2,4,5,6,7,8,9], ...
f7d2559874c974c92376fcdc0df311ae3fd05a41
DiegoCodes/Tarea_03
/TiendaDeVideo.py
593
3.6875
4
#encoding: UTF-8 #Autor: Diego Perez AKA DiegoCodes #Calculador de Precio por Peliculas #Suma el costo de las peliculas multiplicandolas por su precio correspondiente def calculateRentCost(new,normal): total = (45*new)+(27*normal) return total def main(): new = int(input("Ingrese cantidad de peliculas...
11bd5c5854a6b42e651779862a4b7a5e6716b098
ziyunhai/zhuhai_air_show
/code/dataexport/Python/CrossBuild/extracter/nicefloat.py
3,576
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- import math class nicefloat(float): @staticmethod def str(num): if not num or num+1 == num or num != num: return float.__repr__(num) f, e = math.frexp(num) if num < 0: f = -f f = int(f*2**53) e -= 53 ...
965cd05ce217b1b5d27cefb89b62935dc250a692
hmkthor/play
/play_006.py
590
4.40625
4
""" Change a Range of Item Values To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: """ thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermel...
a297dc7d2f114f089a2bda19c9267a9c3c133b00
honism/CP3-Thanaphol-Chaisorana
/Exercise21_Thanaphol_C.py
1,314
3.671875
4
from tkinter import * def Click(event): new_height = float(textboxHeight.get()) new_weight = float(textboxWeight.get()) BMI = new_weight/((new_height/100)**2) if BMI > 30.0: result.configure(text="BMI = %f = %s"%(BMI,"อ้วนมาก")) elif 25.0<=BMI<=29.9: result.configure(text="BMI = %f...
f33d33a878f1a604bda43830403b2429b43a8039
srinidhi82/LPTHW
/strings3.py
361
3.765625
4
days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMarch\nApril\nMay" #Below print here uses \ character to escape double quotes print ("I am \"Super\" tall") print("The days are:" , days) print ("here are the months:", months) print(""" Hey babe! I know what it says!! You said so e'h ...
3dacd128c23c8f43e64922ca50e1b90def030ba4
jignatius/QuickWeather
/QuickWeather/QuickWeather.py
1,517
3.8125
4
#! python3 # QuickWeather.py - Prints the weather for a location from the command line import json, requests, sys def current(location): # Download the JSON data from OpenWeatherMap.org's API url = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&APPID=2c72b19f0de8d493671eb73e9c4cf39c" % (loc...
359ce1c69a952d51fd9024adade90be51e6ebb00
LiuPengPython/algorithms
/algorithms/strings/is_rotated.py
324
4.3125
4
""" Given two strings s1 and s2, determine if s2 is a rotated version of s1. For example, is_rotated("hello", "llohe") returns True is_rotated("hello", "helol") returns False accepts two strings returns bool """ def is_rotated(s1, s2): if len(s1) == len(s2): return s2 in s1 + s1 else: return F...
661264a31181a11a7f61e209d0a93914081355b6
fabiogaluppo/AdventOfCode2020
/day_20.py
9,157
3.5625
4
#python day_20.py < .\input\input20.txt import sys import math import functools import itertools def readAllLines(): return [line.rstrip() for line in sys.stdin] TOP, RIGHT, DOWN, LEFT = 0, 1, 2, 3 def flip(rows): isString = isinstance(rows[0], str) if isString: rows = [list(row) for row in row...
a807409aea1617cedddcf09b6c6223b56affe77b
Si047p/movie_trailer
/media.py
650
4.0625
4
""" Defines media types with their attributes """ class Movie(): """Class stores the information related to a movie. Attributes: movie_title: The movie's title. poster_image: URL to the movie's poster or box art. trailer_youtube: URL to the movie's trailer on YouTube """ ...
09764df12da53d7bbdcc732d52aa73c8938b42ed
togrba/dbtech
/lab2/menutest.py
19,649
3.734375
4
#!/usr/bin/python import pgdb import matplotlib import matplotlib.pyplot as plt import numpy as np from sys import argv class Program: def __init__(self): #PG-connection setup # local server: params = {'host':'localhost', 'user':'postgres', 'database':'postgres', 'password':''} self.conn = ...
11465b97d86206fa2612a413f467bf000e1ae393
dscpesu/PESU-Chatter-Bot
/cleanup.py
513
3.703125
4
def clean(fname): c="" with open(fname,'r', encoding='utf8', errors ='ignore') as fin: fstring = fin.read().lower() # print(fstring) for i in range(len(fstring)-1): if fstring[i].isalpha() or fstring[i].isdigit() or fstring[i]=='.' or fstring[i]==',' or fstring[i]=="'"or fstring[i]==...
95c5317ca607b0c938c49ed2a35cde86280b9aed
fsf-silva-ferreira/python-projects
/2 - app_python/aula7_calculadora2.py
851
3.984375
4
#Função: Retorna valor #Método: Não retorna valor class Calculadora: #O método ini não é obrigatório # def __init__(self): # #o init não pode ficar vazio, por coloca-se o pass # pass def soma(self,valor_a,valor_b): return valor_a + valor_b def subtracao(self,valor_a,valor_b): ...
0ed8f79cb1d0d5e71e96066811c0211cca5d53ef
fsf-silva-ferreira/python-projects
/2 - app_python/aula9.py
2,691
3.640625
4
#Recomendado colocar o import no topo do arquivo #Assim, ele pode ser utilizado por qualquer método ou função import shutil def escrever_arquivo(nome_arquivo, texto): arquivo = open(nome_arquivo, 'w') arquivo.write(texto + '\n') arquivo.close() def atualizar_arquivo(nome_arquivo, texto): arquivo = o...
9c38e7c7a66f7984d2f0179d9212791762314781
mjbouvet/REU-Summer-Project
/AccelLimiting.py
8,378
3.5
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import matplotlib.animation as anim from matplotlib.animation import FuncAnimation plt.rcParams['animation.ffmpeg_path'] = r'H:\Programs\FFmpeg\bin\ffmpeg.exe' FFMpegWriter = anim.writers['ffmpeg'] Writer = anim.FFMpegWriter(fp...
b1a9fee52ca6eae1ee380a0d95491d735c7360bd
jeantardelli/wargameRepo
/wargame/designpatterns/strategies_traditional.py
1,633
4.15625
4
"""strategies_traditional Example to show one way of implementing different design pattern strategies in Python. The example shown here resembles a 'traditional' implementation in Python (traditional = the one you may implement in languages like C++). For a more Pythonic approach, see the file strategies_pythonic.py...
792cf649ad2b7e7933e62c9cd9944a1563e5eb17
jeantardelli/wargameRepo
/wargame/gameutils.py
2,569
3.609375
4
"""wargame.gameutils This module contains some utility function for the game Attack of the Orcs This modue is compatible with Python 3.5.x and later. It contains supporting code for the book, Learning Python Application Development Packt Publishing. This is my version of the code, it is pretty much similar to the or...
58647b7160c95a670f32f010947259d04515f706
jeantardelli/wargameRepo
/wargame/designpatterns/pythonic_adapter_foreignunitadaptermulti.py
1,300
3.65625
4
"""python_adapter_foreignunitadaptermulti This method represents an adapter class that will make other game units compatible between themselves. """ class ForeignUnitAdapterMulti: """Generalized adapter class for 'fixing' incompatible interfaces. :arg adaptee: An instance of the 'adaptee' class. For example,...
93b2af4c8f1a23483747d04ea3902c644b581543
jeantardelli/wargameRepo
/wargame/performance-study/pool_example.py
1,201
4.375
4
"""pool_example Shows a trivial example on how to use various methods of the class Pool. """ import multiprocessing def get_result(num): """Trivial function used in multiprocessing example""" process_name = multiprocessing.current_process().name print("Current process: {0} - Input number: {1}".format(proc...
d37a677d52bcb30328947235f0198a9447ddeb34
jeantardelli/wargameRepo
/wargame/GUI/simple_application_2.py
1,025
4.125
4
"""simple_application_2 A 'Hello World' GUI application OOP using Tkinter module. """ import sys if sys.version_info < (3, 0): from Tkinter import Tk, Label, Button, LEFT, RIGHT else: from tkinter import Tk, Label, Button, LEFT, RIGHT class MyGame: def __init__(self, mainwin): """Simple Tkinter G...
3934697b86a6ce694c2f2304c9ed4f5147665362
tiago-gmfrr/PreviousClassesTmp
/Work/Telecom/huffman.py
2,672
3.515625
4
import math import sys class Node: def __init__(self, value, char, left=None, right=None, parent=None, code=None): self.value = value self.char = char self.right = left self.left = right self.code = code self.parent = parent def setChildren(self, left = None, right = None): self.right = ...
ba49bd16e51daf62fdd46883e5593212aa28f9ec
no-bugs-only-features/Operating_Systems-CSCI_3753
/csci3104/Assignment2/Derek_Gorthy_Trie_Traversal/trieClass.py
5,070
4.03125
4
#LastName: Gorthy #FirstName: Derek #Email: derek.gorthy@colorado.edu from __future__ import print_function import sys # We will use a class called my trie node class MyTrieNode: # Initialize some fields def __init__(self, isRootNode): #The initialization below is just a suggestion. #Chan...
ee74967cf453cda9aedab57e104f512513684445
sakbarpu/mapsd
/create_list_of_countrynames_different_langs.py
993
3.921875
4
''' Using the country_list library create a list of all countries in many different languages (~620). Store them in a disk. (ONE TIME EXECUTION) ''' import sys, os from country_list import available_languages from country_list import countries_for_language out_dir = sys.argv[1] #create a dict for each language. for ...
174b3d0663c7e18f5ff4b3308ae34ed48300fee5
RobDBennett/cs-module-project-hash-tables
/applications/no_dups/no_dups.py
558
3.78125
4
def no_dups(s): clean = [] if s == "": return "" else: for word in s.split(): if word in clean: continue else: clean.append(word) answer = "" for word in clean: answer += word answer += " " return answer.str...
704b019ab855616adc2760ee6727a4ac6177bc8d
aleozlx/htcondor-workshop
/Mon/2.3/count.py
563
3.515625
4
#!/usr/bin/env python import os import sys import operator if len(sys.argv) != 2: print 'Usage: %s DATA' % (os.path.basename(sys.argv[0])) sys.exit(1) input_filename = sys.argv[1] words = {} my_file = open(input_filename, 'r') for line in my_file: line_words = line.split() for word in line_words: ...
240c664a43e9066b04d56b0c1df6526708691196
VoThanhDanh95/JAIST_internship
/python/tictactoe_com_vs_player.py
7,727
3.84375
4
import random NTRIALS = 1000 # Number of trials to run SCORE_CURRENT = 1.0 # Score for squares played by the current player SCORE_OTHER = 1.0 # Score for squares played by the other player def drawBoard(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print('...
2d7914e1feecc6a733a027503d4e46ba1f9a178b
VoThanhDanh95/JAIST_internship
/python/qlearning_tictactoe.py
11,117
3.59375
4
import random NTRIALS = 500 # Number of trials to run NUMBER_OF_GAMES = 200000 FIRST_TURN = 'player' # ALPHA = 0.3 # GAMMA = 0.9 # EPSILON = 0.3 ALPHA = 0.01 GAMMA = 0.9 EPSILON = 0.5 def drawBoard(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | ...
311401eb3c2861110b9cf9a1f60fb5ceb532e974
NastyaMelnik57/Coursera
/Algorithms/PointsCoverSorted.py
648
3.53125
4
import sys #we want to divide children in groups due to their ages in such way that the #largest difference in age of any two children in one gorup will be at most 1# #and we also want to minimize the number of groups #The task is equal to cover points on the axe with segments of length 1 def MinGroupsNaive(C): R ...
c9a0fa2e3411fd1bb7789b2cb7619ef2dec427be
elaine84/evolve
/code/error.py
598
3.515625
4
import numpy as np def sq_err(w, u, rotation, cor): """ cor: the correlation matrix (of the axis aligned) Gaussian distribution. So cor is diagonal. We assume that each entry of cor is between 0.1 and 1 rotation: the rotation matrix applied to vectors drawn from N(0, cor) w, u : vectors in the transformed (rota...
87354e098b723749ba468f150239dc8f78e6f263
eamonbracht/Deforestation-Neural-Network
/raster.py
3,631
3.5
4
import rasterio import rasterio.plot import pyproj import numpy as np import matplotlib import matplotlib.pyplot as plt from rasterio.windows import Window class Raster: """Raster is used to manage importing, manipulating and visualizing raster files.""" def __init__(self, filepath, coords): """ ...
c72fb1953ee65169041fa399508fbd5204986270
yeti98/LearnPy
/src/basic/TypeOfVar.py
978
4.125
4
#IMMUTABLE: int, ## Immutable vs immutable var #Case3: # default parameter for append_list() is empty list lst []. but it is a mutable variable. Let's see what happen with the following codes: def append_list(item, lst=[]): lst.append(item) return lst print(append_list("item 1")) # ['item 1'] print(append...
e37708d07875b90881d73d15dc6418878e174d37
erv4gen/Archive
/old_files/fun.py
897
3.671875
4
''''' измени алгоритм так, чтобы внути цикла рисовалось все правильно ''' import os import sys import random as r def forest(amount): foresthigh = [r.randrange(2,15) for i in range(amount)] myforest = ["" for i in range(amount)] for i in range(0,max(foresthigh)): branch = 1 for j in rang...
1212f1f829be75fb4a3d42186e61774b0c2fbee5
amandamurray2021/Programming-Semester-One
/labs/Topic08-Plotting/plotSquare.py
259
4.09375
4
# Q5 # Write a program that plots the function y = x² # Author: Amanda Murray import matplotlib.pyplot as plt import numpy as np xpoints = np.array(range(1,101)) ypoints = xpoints * xpoints # multiply each entry by itself plt.plot (xpoints, ypoints) plt.show()
0a050628c16cbebab0494a6b059db22633ff5c9a
amandamurray2021/Programming-Semester-One
/labs/Week04-flow/average.py
577
4.0625
4
# This program keeps reading numbers until the user enters 0 # It should then print out each of the numbers entered and the average of them. # Author: Amanda Murray numbers = [] # first number then we check if it is 0 in the while loop number = int(input("enter number (0 to quit): ")) while number != 0: numbers....
e6d4e5704ff566eef48395633589e37bce88c83a
amandamurray2021/Programming-Semester-One
/labs/Week04-flow/round.py
495
3.953125
4
# This program rounds a student's decimal point percentage mark # and then prints out the corresponding grade # Author: Amanda Murray percentage = float(input("Enter the percentage: ")) if percentage < 39.4: # 39.4 or less print ("Fail") elif percentage <= 49.4: # between 39.5 to 49.4 print ("Pass") elif per...
f797517592b2d09d2227375cdd81614b3da3b912
amandamurray2021/Programming-Semester-One
/labs/Topic07-Files/writeNumber.py
375
3.875
4
# Q2(b) # Write a function that reads in a number and overwrites the file with that number (count.txt). # Test the program to check that the file has been changed. # Author: Amanda Murray filename = "count.txt" def writeNumber(number): with open (filename, "wt") as f: # write takes a string so we need to c...
0243e8d54259a3cecd9e84443bae674a66f090f7
amandamurray2021/Programming-Semester-One
/labs/week06-functions/menu2.py
801
4.34375
4
# Q3 # This program uses the function from student.py. # It keeps displaying the menu until the user picks Q. # If the user chooses a, then call a function called doAdd (). # If the user chooses v, then call a function called doView (). def displayMenu (): print ("What would you like to do?") print ("\t (a) Ad...
ee17da886d3a69800522063531b656b37723620a
amandamurray2021/Programming-Semester-One
/labs/Topic08-Plotting/MakeList4.py
614
4.0625
4
# Q4 # Modify the program so that it increases all of the salaries by 5%. # Store these numbers in a different array. # Author: Amanda Murray import numpy as np minSalary = 20000 maxSalary = 80000 numberOfEntries = 10 np.random.seed(1) # seeding the random number generator ensuring data is the same each time the pr...
206871298a6a25d6cde83d275cd2a074f1cce895
amandamurray2021/Programming-Semester-One
/labs/Week03/string.py
148
3.546875
4
# string.py # Lab 3.3 # This program reads in a string and outputs it # Author: Amanda Murray message = 'John said\t"hi"\nI said\t\t"bye"' print (message)
a3ca7ebf208720a4113b073b25815c7323f7b106
amandamurray2021/Programming-Semester-One
/pands-problem-sheet/secondstring.py
455
3.9375
4
# Weekly Task 3 # This program asks the user to input a string # It outputs every second letter from the string in reverse order # Author: Amanda Murray sentence = input("Please enter a sentence: ") print (sentence [::-1][::2]) # Example given: The quick brown fox jumps over the lazy dog. # We reverse the sentence by ...
b46a272da0167029a379ba99f8ad5dbd0e7ff482
amandamurray2021/Programming-Semester-One
/labs/Topic07-Files/createFile.py
142
3.515625
4
# Q2 # This program will create a count.txt file # Author: Amanda Murray with open ("count.txt", "x") as f: data = f.write("0") print (data)
65f762930b668b660ee2db90895a468a359bd32f
amandamurray2021/Programming-Semester-One
/pands-project2021/petallength.py
1,617
4.0625
4
# This program plots a histogram with petal length in cm on the x-axis and the amount of irises on the y-axis. # Using Seaborn's "hue" parameter, we pass the Iris species (class) as a third variable and save the resulting graph as a .png. # Author: Amanda Murray import matplotlib.pyplot as plt # a low level graph plo...
f2b11078b232660a006f6eafb0338f23c173b70f
GavrilS/python-mini-projects
/mad-libs-generator/mad_libs_generator.py
1,467
3.859375
4
import random def create_stories(): weird_news = 'A sub was arrested this morning after he sub in front of sub. sub, had a history of sub, but' \ ' no one - not even his sub ever imagined he\'d sub with a sub stuck in his sub.' \ " I always thought he was sub, but I never thought ...
965ac8e3426b2700779db405a9f8da2bf479f17c
cwchange/interview-question
/num1/question_4.py
737
3.640625
4
""" 4. Given: words = [‘one’, ‘one’, ‘two’, ‘three’, ‘three’, ‘two’] Remove the duplicates. """ #Solution number one, by using numpy build in function. import numpy as np words = ['one', 'one', 'two', 'three', 'three', 'two'] new_words=np.unique(np.array(words)) print new_words #soltion number two class q_4: ...
a4f2a7688618ebd42ef67a9f350e55bb21089491
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/01 - Temel Bilgiler - Seviye 1/04 - percentage.py
365
3.859375
4
""" Bir sayı ve yüzde alan ve bu sayının yüzdesini veren bir fonksiyon yazın. """ def percentage(num, percent): return num * (percent/100) print(percentage(100,60)) print(percentage(10, 50)) print(percentage(10, 30)) print(percentage(10, 20)) print(percentage(5, 10)) print(percentage(5, 30)) print(percen...
581152e31c7db41497c55661eee0ad92026487cf
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/09 - Math Seviye 2/02 - basicCalculator.py
477
4.3125
4
"""İki sayı ve bir operatör (+, -, *, /) alan ve hesaplamanın sonucunu döndüren bir fonksiyon yazın.""" def calculate(num1, operator, num2): if operator == "+": return num1 + num2 elif operator == "-": return num1 - num2 elif operator == "*": return num1 * num2 elif op...
3eb35bdb0ee2418cf7bdfdc6970ddbaf05137a1b
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/12 - Dictionaries Seviye2/08 - wordCountTracker.py
375
3.703125
4
"""Kelime Sayımı İzleyici Bir metin dizesi verildiğinde, dizede count her kelimenin kaç kez göründüğünü izleyen bir sözlük döndürün. """ def word_count(text): my_string = text.split() count = {} for item in my_string: if item in count: count[item] += 1 else: count[i...
1f4677231483102e14e550023ca914280acf3a5c
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/06 - Lists Seviye 1/05 - insertLast.py
387
4.125
4
""" Alıştırma 4.1.5: Son Ekle Listenin son elemanı olarak insert_last eklenen adında bir fonksiyon yazın x. Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım.""" def insert_last(my_list, x): if len(my_list) >= 0: my_list.append(x) ...
7285749a1416052d7e08b52cbed0f5ea4b431c07
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/11 - Lists Seviye2/01 - prependGood.py
483
3.6875
4
""" İyinin Başına Hazırla prepend_good Listenin her öğesinin başına “good” dizesini getiren bir işlev yazın . Not: Geçirilen listenin her öğesinin bir dize olduğunu varsayabilirsiniz. Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def pr...
4cf599680e61c36244b7539c0695d60b6cb47853
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/01 - Temel Bilgiler - Seviye 1/08 - divisibleByValue.py
342
3.875
4
""" Değere Bölünebilme İki tamsayı alan bir fonksiyon yazın. İşlev, ilk tamsayının ikinci tamsayıya bölünüp bölünemeyeceğini kontrol edecek ve bir boole değeri döndürecektir. """ def divisible(num, divisor): if num % divisor == 0: return True else: return False print(divisible(10,10)) print(...
40b495b2c03ef38929a129592c032ff53c8b53b7
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/06 - Lists Seviye 1/02 - removeLast.py
399
3.890625
4
"""remove_last Listeden son elemanı kaldıran bir fonksiyon yazın . Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def remove_last(my_list): if len(my_list) > 0: my_list.pop(-1) return my_list else: return...
6a74c4041ca5744dfd4baf0838379b07d08b1a5b
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/04 - Math Seviye 1/05 - finalVelocity.py
423
3.75
4
""" Son Hız Fizikte, bir nesnenin sabit ivmeyle hareket ederken son hızını (veya hızını) bulmak için aşağıdaki denklem kullanılabilir: vf = vi + at burada: vf= son hız vi= ilk hız a= hızlanma t= zaman İlk hız, ivme ve zaman verildiğinde, son hızı döndürecek bir fonksiyon yazın. """ def calculat...
d39156f96eeac77c4a9e1606b3566ae0afbb4f84
berkcangumusisik/CourseBuddiesPython101
/1. Hafta/05 - Lab Saati Uygulamaları/ornek1.py
1,012
4.40625
4
"""Python Hafta 1 - 1: CourseBuddies üniversitesi öğrencilerinin mezun olup olamayacağını göstermek için bir sistem oluşturmaya çalışıyor. Öncelikle durumunu öğrenmek isteyen öğrencinin, ismini yaşını ve not ortalamasını (0 - 100 arası) girmesi gerekiyor (input() fonksiyonu ile kullanıcıdan alıcak). eğer kullanıcının y...
7df313a3df931a978cd78c18ac1176d4c681dba0
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/03 - Strings - Seviye1/07 - replaceWithA.py
265
3.8125
4
""" A ile değiştirin Size merkezinde sesli harf bulunan 3 harfli kelimeler verilir. Kelimeyi 'a' ile değiştirilen sesli harfle döndüren bir işlev oluşturun. """ def replace_with_a(str): return str.replace(str[1:2],"a") print(replace_with_a("sey"))
0c8874c6ed0902384e7ba0790e5e1b28741868ba
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/13 - Lists Seviye 3/07 - sumTheLenghts.py
413
4.21875
4
""" Uzunlukları Topla Bir sum_the_lengths listedeki tüm dizelerin uzunluğunu toplayan adlı bir işlev yazın . Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def sum_length(my_list): length = 0 for string in my_list: length...
c3f675e03651eb66f2b4444368cbe3d404ec4be3
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/05 - Döngüler Seviye 1/05 - average.py
377
3.703125
4
""" Ortalama Bu alıştırmada, başlangıç ​​değerinden bitiş değerine (her iki bitiş noktası dahil) kadar bir dizi sayının ortalamasını döndüreceksiniz. Örnek: find_average(10, 20) --> 15 find_average(0, 1000) --> 500 """ def find_average(start, end): ortalama = start -1 + end+1 ort = ortalama / 2 return o...
029a98514a807917eb98b16dced8b95bd842ef3d
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/10 - Döngüler Seviye 2/03 - isDivisable.py
480
4.0625
4
"""Bölünebilir mi?4 puan Bu alıştırmada size bir bitiş değeri ve bir bölen veriliyor. Bölen ile bölünebilen pozitif tam sayıların sayısını bitiş değeri dahil olmak üzere döndürür. Örnek: is_divisible(10, 2) --> 5 is_divisible(10, 3) --> 3 """ def is_divisible(end, divisor): count = 0 for i in range(1 , end+...
d26127cfacd2c5fce83c76931223a72c5df39aa7
nitishk111/InfyTQ-Python-Assignment
/InfyTQ_Assign20_3.py
435
3.515625
4
#PF-Prac-20 def ducci_sequence(test_list,n): #start writing your code here for i in range(n+1): a=test_list[0] test_list[0]=abs(test_list[1]-test_list[0]) test_list[1]=abs(test_list[2]-test_list[1]) test_list[2]=abs(test_list[3]-test_list[2]) test_list[3]=abs(test...
52e071a021c0b301e9e35df872f201bb7611fc09
nitishk111/InfyTQ-Python-Assignment
/Assignment14.2.py
436
3.9375
4
marks_table={'John':86.5,'Jack':91.2,'Jill':84.5,'Harry':72.1,'Joe':80.5} top=3 print("Top {} scorer of subject--".format(top),end=" ") for i,j in sorted(marks_table.items(),key=lambda x:x[1]): if top>0: print(i,end=" ") top-=1 print("\nAverage score of all students: ",end=" ") average=0...
ee460ae9496830b62e21cb0af8eab25212034757
nitishk111/InfyTQ-Python-Assignment
/Assignment8.2.py
687
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 22 07:53:58 2020 @author: Nitish """ i=0 def num_convert(a): global i i+=1 if i%2==0: return a else: return int(a) speciality={'P':'Pediatrics','O':'Orthopedics','E':'ENT'} s=list(map(num_convert,input("Enter id and...
df132a59706cc953c09afdc91bdddf692e11a5a4
nitishk111/InfyTQ-Python-Assignment
/Assignment11.2.py
515
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 27 02:02:08 2020 @author: Nitish """ def fact(num): if num==0: return 1 else: return fact(num-1)*num num_list=list(map(int,input("Enter list: ").split())) strong_num=list() for i in num_list: b=0 j=i while i>0: ...
dd32bd386f65c98a15f23d9a62b563eb8e48b96e
joscelino/Calculadora_estequiometrica
/Formula_Clapeyron/clapeyron_dinamica.py
1,121
4.125
4
variable = int(input("""Choose a variable: [1] Pressure [2] Volume [3] Number of moles [4] Temperature """)) R = 0.082 if variable == 1: # Inputs V = float(input('Volume (L): ')) T = float(input('Temperature (K): ')) n = float(input('Number of moles: ')) # Formula P = (n * R * T) / V #...
1672bf091704e5347c6cce0fdee1b6f04de07b11
PureChocolate/aoc_2019
/day_1/fuel.py
307
3.6875
4
import math; total = 0 def fuelReq(m): global total if((math.floor(m/3) - 2) < 0): total += 0 else: m = int((math.floor(m/3)) - 2) total += m fuelReq(m) with open("masses.txt") as f: for line in f: line = int(line) fuelReq(line) print total
9684c8cde1681d9555563861cb92e332dee3f1a5
kenan666/Study
/算法总结/旋转链表.py
1,627
3.546875
4
''' 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输入: 0->1->2->NULL, k = 4 输出: 2->0->1->NULL 解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步: 0->1->2->NULL 向右旋转 4 步: 2->0->1->NUL...
8777dc9d9f622913fa80a73cbe61aa2ddfed7ecc
kenan666/Study
/算法总结/全排列2.py
832
3.875
4
''' 给定一个可包含重复数字的序列,返回所有不重复的全排列。 示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] ''' # 回溯法 def permuteUnique(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] visited = set() def backtrack(nums, tmp): if len(nums) == len(tmp): res.append(tmp) retur...
4dc64704e0577f4d03eeab4e3c55e4272c45b844
kenan666/Study
/算法总结/矩阵查找target.py
1,529
3.75
4
''' 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: 每行中的整数从左到右按升序排列。 每行的第一个整数大于前一行的最后一个整数。 示例 1: 输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 输出: true 示例 2: 输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 输出: false ''' def searchMatrix(s...
44f01bdd44239347a783d80b5b75f6e646f52029
kenan666/Study
/算法总结/三角形最小路径和.py
1,244
3.71875
4
''' 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 例如,给定三角形: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 ''' #利用DFS深度优先遍历,从上到下扫描所有路径 def minimumTotal(self, triangle: List[List[int]]) -> int: self.res = float("inf") row = len(triangle) def helper(level,i,j,tmp): ...
fb3fbd522eed6139a5098cb1a3c00cb964c6c20e
kenan666/Study
/算法总结/滑动窗口最大值.py
3,892
3.5625
4
''' 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回滑动窗口中的最大值。  示例: 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 输出: [3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 ...
3cc45146c9591b81518c36e858f88834a8eb3dd2
kenan666/Study
/算法总结/乘积最大子序列.py
1,009
3.53125
4
''' 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 示例 1: 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6。 示例 2: 输入: [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 ''' ''' 由于负值最小值 * 负数可能会变成最大值,正值最大值 * 负数也可能会变成最小值,所以我们还要多一步骤保留最小值。 设 A[i] 为以 i 截止之子序列最大积,得转移公式A[i] = max(A[i - 1] * j, j) 考虑最小值成负数,故写成 A[i] = max(A[i - 1] * j...
9c970cc27fdb11814ece3e945cd43fbba26630cf
kenan666/Study
/算法总结/二叉树相关例子.py
10,981
3.75
4
''' 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] ''' # 解1 递归 def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] def helper(root): if not root: return helper(root.left) res.append(root.val) helper(root.right) ...
a87fdf82d6f35de3a48b9788a4a904f1428372cc
kenan666/Study
/算法总结/二叉搜索树_节点删除.py
18,047
3.53125
4
#----------二叉搜索树 知识点-------- ''' 二叉查找树(Binary Search Tree),也称为二叉搜索树、有序二叉树(ordered binary tree)或排序二叉树(sorted binary tree), 是指一棵空树或者具有下列性质的二叉树: 1、若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值; 2、若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值; 3、任意节点的左、右子树也分别为二叉查找树; 4、没有键值相等的节点。 插入、删除、查找时间复杂度为 O(logN) * 最坏 O(n) ''' # ------二叉搜索...
5162f393d11269f5242661d63feb8f52335f9d05
SBentley/random-gen
/random-gen.py
617
3.734375
4
from random import random class RandomGen(object): # Values that may be returned by next_num() _random_nums = [-1,0,1,2,3] # Probability of the occurence of random_nums _probabilities = [0.01,0.3,0.58,0.1,0.01] def next_num(self): ran = random() print(ran) lower = 0 ...
febf90deca77f9cba1d60c646d24f7a9dab06ef6
skyczhao/analysis-tools
/utils/dicts.py
889
3.703125
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Dicts # # @author tobin # @since 2018-06-22 """ 词典工具类 """ def double_set(d, k, v_k, v_v): """ 往词典对应key添加k-v :param d: 词典 :param k: 键 :param v_k: 值的key :param v_v: 值的value :return: """ if isinstance(d, dict): if k not in d: ...
0f578a88114c31c6e6c982a42ed2ebf895f2908d
h3ll5ur7er/GoogleCTF2019Writeup
/BeginnersQuest/52_FriendSpaceBookPlusAllAccessRedPremium/pal_prime_finder.py
434
3.609375
4
def is_palindrome(n:str): for i in range(len(n)//2): if n[i] != n[-(i+1)]: return False return True with open("/root/Downloads/2T_part1.txt", "r") as primes: with open("palprimes.txt", "w") as palprimes: for line in primes.readlines(): numbers = line.split() ...
745459107fc78e26612fdcd9b6ca56830de9a005
VincentVelthuizen/Menace
/user_interface/command_line.py
945
3.765625
4
import user_interface class CommandLine(user_interface.UI): symbol = [" ", "X", "O"] def render(self, board=None): row_strings = [] for row in range(3): values = [self.symbol[board.cell((row, col))] for col in range(3)] row_strings.append(" " + " | ".join(values) + " ...
65f5ea882966a4b45913a081aa988142e3e35906
anaferreirapy/Python-para-Zumbis-2020
/Lista 1 - Início/L1 - ex11.py
207
3.75
4
#Sabendo que str( ) converte valores numéricos para string, calcule quantos dígitos há em 2 elevado #a um milhão. a = 2 ** 1000000 b = len(str(a)) print('2 elevado a 1000000, possui ',b,' dígitos.')
c3f231f64df2d9ec0c4167d6d9372380f7233496
anaferreirapy/Python-para-Zumbis-2020
/Lista 2 - Condicionais/L2 - ex3.py
991
3.65625
4
#João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de #seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do #estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você ...
94c010ca3c5552c7179cf220bdc566f66363f5ef
anaferreirapy/Python-para-Zumbis-2020
/Exercícios de aula/Condicionais/minutos telefone - if.py
584
3.546875
4
#Considere a empresa de telefonia Tchau. #ABaixo de 200 minutos, a empresa cobra R$ 0,20 por minuto. #ENtre 200 e 400 minutos, o preço é de R$ 0,18. #Acima de 400 minutos o preço por minuto é de R$ 0,15. #Calcule sua conta de telefone. min = int(input("Informe a quantidade de minutos consumidos:")) if min < 200: v...
48ae1758c2351c27e71dfef24736c2d23b2ea9e7
anaferreirapy/Python-para-Zumbis-2020
/Lista 2 - Condicionais/L2 - ex7.py
625
3.984375
4
#Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a #ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida #em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a ...
a56090aeb44d8a7969610f12e490c7644300f6e6
AshBringer47/kpi_labs
/Lab 6/Lab 6.py
412
3.59375
4
import os def main(): print_sum() def print_sum(): try: a = float(input("Gunawardana Shiron. IS-92. Please enter a, b, c.\na = ")) b = float(input("b = ")) c = float(input("c = ")) T = ex_sum(a, b, c) print(T) except KeyboardInterrupt: print("\nProgram execu...
3312f9fb4b30547b407ecfe0657dee5b55c1907b
bethanw10/advent-of-code
/Day 6 - Universal Orbit Map/Day6.py
2,874
3.5
4
class OrbitMap: def __init__(self, name): self.name = name self.children = [] self.parent = None def __repr__(self): return f"{self.name}" def find(self, name): if self.name == name: return self else: for child in self.children: ...
cbb075dff8a66b6438f708eb2055954c4d553d8c
AlonsoZhang/PythonHardWay
/ex25n.py
1,317
4
4
import ex25 sentence = "All good things come to those who wait." # words = break_words(sentence) words = ex25.break_words(sentence) sorted_words = ex25.sort_words(words) ex25.print_first_word(words) # 打印了个All ex25.print_last_word(words) # 打印了个wait. ex25.print_first_word(sorted_words) # 打印了个All。 ex25.print_last_word(...
2211dca301494ad9e517f0098e01263c047806a0
VB-Cloudboy/PythonCodes
/03-InputOutput/01-IO_Statement.py
689
3.921875
4
# A series of Input-Output Statement #01-Playing with String player = str(input("Enter a Player Name: ")) print('you just wrote: ', player) #02-Playing with Numbers player = int(input("Enter a Player Jersey Number: ")) print('you just wrote: ', player) #03-Palying with Multiple Numbers batsmen01 = str(input("Enter P...
2df05235e11b4f969f147ffa6dcde19ceb0c0dec
VB-Cloudboy/PythonCodes
/10-Tuples/02_Access-Tuple.py
403
4.125
4
mytuple = (100,200,300,400,500,600,700,800,900) #1. Print specific postion of the tuples starting from Right print(mytuple[2]) print(mytuple[4]) print(mytuple[5]) #2. Print specific postion of the tuples starting from Left print(mytuple[-3]) print(mytuple[-5]) print(mytuple[-4]) #3. Slicing (Start: Stop: Stepsize) ...
9cb69c3b0fdea7975347c1a00d28853b4b0c52a5
BillNguyen1999/Jumbled-Words
/se3xa3-project/src/main_start.py
3,207
3.875
4
## @file main_start.py # @author Muneeb Arshad, Shesan Balachandran, Bill Nguyen # @title main_start # @date April 4, 2021 from tkinter import * # Global Variables gameMode = "" difficulty = "" username = None ## @brief start_main_page # @details function is used to start and display the main menu page...
066eb690c9b39caaa1ee8729195360eb7d9f641e
maddyv/DSUPython
/connectstr.py
939
3.84375
4
def connectstr(): st=input("Enter the connect string: ") d1={"server":'',"dbname":'',"user":'',"passwd":''} i1=int(0) # Init counter and index vars i2=int(0) ctr=int(0); for j in range(0,len(st)): # Loop to check for = characters if st[j]=='=': ctr+=1 # char counter ...
7e1cb17eb84bb8c89eb3b7953d591e80df57fcc6
xinzhuanjing/Python
/data_type/eq.py
316
3.65625
4
class T: def __init__(self, data): self.data = data def __eq__(self, a): print("This is in __eq__") if self.data == a.data: return True; else: return False if __name__ == "__main__": a = T(1) b = T(1) print(a == b)
22b03632f410db181d6619a49ecb0c7850ee2369
xinzhuanjing/Python
/class/attribute_control.py
3,195
3.90625
4
# class Test: # A = 10 # def __init__(self): # self.a = 1 # def __getattribute__(self, item): # print("This is in __getattribute__") # return object.__getattribute__(self, item) # print("Instance: a = %s" % Test().a) # print("Instance: A = %s" % Test().a) # print("Cl...
d2796e2e828c103194efb8389ca6e8be1d642b8f
xinzhuanjing/Python
/class/class_object_instance.py
3,211
4.15625
4
# class Test: # def __init__(self, a, b): # self.add_a = a # self.add_b = b # def add(self): # return self.add_a + self.add_b # ##################################### # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(se...
60c6f0559d062bf319c84fc064b6422a0e160021
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day02/if1.py
408
4.0625
4
if 3 > 10: print('yes') print('ok') else: print('no') # 任何非0数字都是True,值为0是False if -0.0: print('yes') if 0.1: print('0.1 yes') # 任何非空对象都是True,空是False: []/()/{}/'' if ' ': print('space ok') ##################################### a = 10 b = 20 if a < b: smaller = a else: smaller = b prin...