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
bb8b28165951ab35aa9237b1cd6be3a0530889c1
a00817392/Quiz09
/ejercicio1.py
533
3.890625
4
print ("Distancia") def square(n): x = n/2 y = x + 1 while (x!=y): z = n/x y = x x = (x + z) / 2 return x def hipo(x1,x2,y1,y2): a = (x2 - x1) b = (y2 - y1) x = (a*a) + (b*b) y = square(x) return y x1 = int(input("Intoduce la posicion de x1 del triangulo:"))...
4fc52260ce25d06966b385abdd2ac6c54b7dcbd9
DunkHimYo/study
/python/palindrom.py
246
3.984375
4
palindrom=input('단어를 입력하세요 : ') check=True for i in range(len(palindrom)//2): if palindrom[i]!=palindrom[len(palindrom)-i-1]: print('회문판별X') check=False if check==True: print('회문판별O')
76b0965c943c4997519fce0e9b639a2b7877687c
DarshanBoghra/Open-Contributions
/new_node_at_the_middle.py
3,325
4.4375
4
#Python program to insert a new node at the middle of the Circular Linked List #The node of list. class Node: def __initialize__(self,value): self.value = value; self.next = None; class CreateList: #Declaring start and end pointer as null. def __initialize__(self): ...
45da5f69b1c28b135d3320d0b944ce181c6a9268
chris-martin/refund-calculation
/python/refund_calculation/history.py
3,297
3.5
4
from __future__ import absolute_import from collections import namedtuple from decimal import Decimal from .windows import Closed, Open zero = Decimal('0') class History(namedtuple('History', ('closed', 'open', 'debt'))): def __new__(cls, closed=None, open=None, debt=None): """ :param closed:...
0092a9a3558c85263feb34f89ecaeaec1b3f37f7
JCur96/CMEECourseWork
/Week2/Code/dictionary.py
2,084
3.875
4
#!/usr/bin/env python3 """ Making a dictionary from a list """ __appname__ = 'dictionary.py' __author__ = 'Jake Curry (j.curry18@imperial.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code/program" taxa = [ ('Myotis lucifugus','Chiroptera'), ('Gerbillus henleyi','Rodentia',), ('Perom...
a6d86c657d21c89ae6086ecd741df2fcefc17b30
JCur96/CMEECourseWork
/Week7/Code/LV1.py
1,875
3.828125
4
# !/usr/bin/env ipython3 """ Coding of the Lotka-Volterra model in python """ __appname__ = 'LV1.py' __author__ = 'Jake Curry (j.curry18@imperial.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code/program" #Imports import scipy as sc import matplotlib.pylab as p import scipy.integrate as integrate #F...
dffcc686d7df5daa825c41ffb4907f7cdd7fe4e2
misaiya99/scipybook2
/codes/05/matplotlib_text.py
549
3.609375
4
# -*- coding: utf-8 -*- """ 在不同的坐标系中添加文字。 """ import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1,1,10) y = x**2 fig = plt.figure(figsize=(8,4)) ax = plt.subplot(111) plt.plot(x,y) for i, (_x, _y) in enumerate(zip(x, y)): plt.text(_x, _y, str(i), color="red", fontsize=i+10) p...
ae4c40bab7553053d56b89cf8b346b257c1f9ad6
tyler-bateman/dailyprogrammer
/smorse/WordTree.py
3,757
4.125
4
# Defines the data structure in which the list of words will be stored. # Words are stored in a tree where the words in each level have one more letter # than the one before. The tree stores all sequences of letters leading up to # a word, so nodes store whether they are a valid word with an isWord field. # # Provi...
62f40aec64258193e15abedd7a346425bbc877b3
pranakum/Python-Basics
/week 2/course_1_assessment_6/q8.py
426
4.34375
4
''' Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the answer to a variable num_words_list. (You should use the len function). ''' original_str = "The quick brown rhino jumped over the extremely lazy fox" #code str = original_str.split() print (str)...
0fc7548c4e29b6d1bd493e83d41ea6914fd72405
swagatk/tf_expts
/TF20/regression/lin_reg_tf2.py
1,627
3.96875
4
''' Tensorflow 2.0 Linear Regression Example ''' import numpy as np import tensorflow as tf import matplotlib.pyplot as plt print("Tensorflow version:", tf.__version__) # actual weight = 2 and actual bias = 0.9 x = np.linspace(0, 3, 120) y = 2 * x + 0.9 + np.random.randn(*x.shape) * 0.3 # Linear Model class Linear...
58dee660224b3d36e6ff3ebea656209554bcbee4
kpsubedi/programming
/python_programming/working_with_algp/code.py
25,621
3.953125
4
################################################ # Binary Search template file from time import time def contains(collection, target): """" Determine whether collection contains target.""" return target in collection def bs_contains(ordered, target): """ Use binary array search to determine if target is ...
c7419697ef5e8273b6083466cfb8426362d2ca4d
ageorgou/advent
/ex2_1.py
726
3.515625
4
import io import pytest def calculate_checksum(list_of_lines): """The checksum of a list of lines.""" checksum = 0 for line_of_numbers in list_of_lines: diff = max(line_of_numbers) - min(line_of_numbers) checksum += diff return checksum def test_checksum(): numbers = [[5, 1, 9, 5]...
9c1f1fbf27312ad34d7995df8edec29059e954f4
rreelachart/cs532-s17
/submissions/assignment 4/getFriendListing.py
910
3.640625
4
#!.usr/local/bin/python2.7 import sys from xml.dom.minidom import parseString def getInfo(xml): dom = parseString(xml) countDict = {} for element in dom.getElementsByTagName("data"): if(element.attributes['key'].value == 'name'): name = element.childNodes[0].data if(element.attribute...
1ebd38baafff89a5ac27361f48ea1160a5edc780
IngabireTina/password-locker
/locker.py
2,067
3.609375
4
import random class User: # created class user users = [] def __init__(self,username,password): #generated new instance of user self.username = username self.password = password def save_user(self): # function to create user credentials User.users.append(...
26de0315c24b949b605af164e6bb227fb03cc5fb
yamad/python
/interleave.py
1,587
3.78125
4
from itertools import zip_longest def interleave2(*iterables): iters = [iter(x) for x in iterables] while iters: for it in list(iters): try: yield next(it) except StopIteration: iters.remove(it) def interleave(*iterables): dummy = object() ...
295b3419836cf3bc3e7662bda3580390237f5745
yamad/python
/shuffle.py
517
3.921875
4
from random import randint def knuth_shuffle(arr): """Knuth-Fisher-Yates shuffle. see Knuth, TAOCP vol 2, Algorithm P invariant: items j->len(arr) are shuffled intuition: in each iteration, a randomly selected item from arr[0:j] is added to shuffled array """ for j in range(len(arr) - 1, 1, -1...
7660c38e1bbdceadbfbb31c28e39fe875bf82231
watatsuki0112/extraprojects
/othellocommands.py
2,919
4.03125
4
import othello def get_row(): while True: try: rows = int(input('ROWS: Please enter an even integer between 4 and 16(inclusive)')) if (rows%2) == 0: return rows else: print('Not an even intege...
ac34a50b78f29204a397f20ba0267ad72d9232be
ictcubeMENA/Training_one
/codewars/7kyu/amrlotfy77/Remove duplicate words/main.py
285
3.890625
4
def unique(integers): final_list = [] for num in integers: if num not in final_list: final_list.append(num) return final_list def unique1(integers): ans = [] for x in integers: if x not in ans: ans.append(x) return ans
e116c854f332fd55bf019b8f285b4d2b3c48f1c9
ictcubeMENA/Training_one
/codewars/8kyu/doha22/kata8/remove/remove.py
190
3.640625
4
def remove(s, n): pass if("!" in s): x=s.replace("!","",n) return x def remove2(s, n): while n > 0: s = s.replace('!','',1) n -= 1 return s
7e909a5d6133700c358a880ab1143fc7188098e1
ictcubeMENA/Training_one
/codewars/8kyu/amrlotfy77/Are You Playing Banjo?/main.py
348
3.8125
4
def areYouPlayingBanjo(name): if name[0] == "R" or name[0] == "r": c = name + " plays banjo" return c else : c = name + " does not play banjo" return c def areYouPlayingBanjo1(name): if name[0].lower() == 'r': return name + ' plays banjo' else: return na...
2a98b42e10385c53ab582fb19561661f28bec573
ictcubeMENA/Training_one
/codewars/8kyu/amrlotfy77/Remove exclamation marks/main.py
231
3.859375
4
def remove_exclamation_marks(s): l = [] for i in s: if i == "!" : continue l.append(i) return ''.join(l) def remove_exclamation_marks1(s): x = s.replace("!","") return x
d59f3ae952ca5d2acc874170408d3aae24581f66
ictcubeMENA/Training_one
/codewars/8kyu/amrlotfy77/L1: Set Alarm/main.py
482
3.65625
4
def set_alarm(employed, vacation): if employed == True and vacation == True : return False if employed == False and vacation == True : return False if employed == False and vacation == False: return False if employed == True and vacation == False: return T...
3a9e1655dc9849f08dfcfca2672ecd06ab5e228d
ictcubeMENA/Training_one
/codewars/7kyu/amrlotfy77/Digital cypher/main.py
1,060
3.515625
4
def encode(message, key): letter_dict = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q'...
794dc5562d294bc2cb7e08b14a26a6738935bb1b
ictcubeMENA/Training_one
/codewars/7kyu/amrlotfy77/Remove Duplicates/main.py
289
3.84375
4
def remove_duplicate_words(s): words = s.split() return (" ".join(sorted(set(words), key=words.index))) def remove_duplicate_words1(s): s = s.split(" ") words = [] for item in s: if item not in words: words.append(item) return " ".join(words)
2cc8046d06deab2ed9e83a308c0fbd151d4152c6
Shijie97/numpy-programing
/ch07/4-someQuestion(2).py
942
3.640625
4
# !user/bin/python # -*- coding: UTF-8 -*- import numpy as np from collections import Counter # collection.Counter的用法 a = [1, 2, 2, 5, 5, 5, 5, 7] b = Counter(a) print(b) # Counter({5: 4, 2: 2, 1: 1, 7: 1}) print(b[5]) # 4 # np.sum的用法,不指定axis,默认矩阵所有元素相加 # axis = 0,计算每列和 # axis = 1,计算每行和 a = np.array...
8adf297b8c082d1e7cf04cb1457906cf60f4e369
Shijie97/numpy-programing
/ch03/5-split.py
362
3.71875
4
# !user/bin/python # -*- coding: UTF-8 -*- import numpy as np a = np.arange(9) # 如果是个数,则代表要分成几份,如果是个数组,则代表切分点,切分点左闭右开 print(np.split(a, 3)) # [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])] print(np.split(a, [4, 7])) # [array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
33d9299788c6ba29860501c479402a717e688faf
Shijie97/numpy-programing
/ch02/1-slice&index(1).py
615
3.515625
4
# !user/bin/python # -*- coding: UTF-8 -*- import numpy as np a = np.arange(0, 10) # 切片,索引从2开始,到8结束(不包括8),步长为2 print(a[2:8:2]) #[2 4 6] print(a[2:-2]) # 2 ~ 7,因为-2代表8,但是又不能包括8 print(a[1:]) # 1 ~ 9 b = np.zeros((10, 8), 'int64') print(b[2:8:2]) # 三行0,和一维一样的套路 # 用...选择某几行或者某几列 a = [[1, 2, 3], [4, 5...
e2343ca0aa0d2b43900ff0bef006b8fcf6e05507
Expan75/codefirst_examples
/app.py
1,975
3.75
4
# Ye old and trusty web development framework. from flask import Flask, render_template, request # this library enables http requests: i.e. to talk to servers via the internet! import requests # this library makes it easier to work with json data import json # Setup for flask to initalise (don't change this) app = ...
119fe716371c7d125e4360b0e3c5d943c7edb8bc
msurendra29/python-hackerrank
/second_max_in_list.py
282
3.609375
4
n = int(input()) array_of_ints = input().split() array_of_ints = [int(i) for i in array_of_ints] temp_list = [] for i in array_of_ints: if ((i in set(array_of_ints)) and (i not in temp_list)): temp_list.append(i) temp_list.sort() print(temp_list[len(temp_list) - 2])
097adfd17583ed8c271eb048e9d5634d63a3c20d
msurendra29/python-hackerrank
/capitalize.py
183
3.953125
4
s = input().strip() for x in s.split(): s = s.replace(x,x.capitalize()) print(s) # my other solution is below #print(" ".join([i.capitalize() for i in input().strip().split()]))
c6f683e0ac2f00fc9608186abc7779f9f344903b
jws067/Terrarium-Pi
/Timerr.py
624
4.09375
4
import time run = raw_input("Start? > ") mins = 0 hrs = 0 # Only run if the user types in "start" if run == "start": # Loop until we reach 60 minutes running while (True): while (mins <= 60): print "Minute", mins # Sleep for a minute time.sleep(60) ...
9ef7c0d2171141fd93d23489d1bf3785016efc96
rayahmian/RideShareClone
/location.py
1,870
3.90625
4
class Location: def __init__(self, row, column): """Initialize a location @type self: Location @type row: int @type column: int @rtype: None """ self._row = row self._col = column def __str__(self): """Return a string representation ...
19c30e51b1f7a3624428e192b4b34a50ec6d98a3
RodwelJunior09/Damas-Python-2.7
/run_game.py
5,976
3.75
4
import pygame from Objects.Ficha import Ficha from Objects.Tablero import Tablero from Objects.Pieces import player1_army, player2_army # Create the Structure for the Checkers Board(only the board, not the pieces). (See Image at the top) Done!! # Create a Function that creates all the pieces located in the starting po...
34aed835f7e05af4d6045deacb57ae7f67071539
umer7/Python-pandas
/new 1.py
317
3.53125
4
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') web_stats = {'Day':[1,2,3,4,5,6], 'Visitors':[43,34,65,56,29,76], 'Bounce Rate':[65,67,78,65,45,52]} df = pd.DataFrame(web_stats) print(df.Visitors) #print(df.tail())
3fe577b92d98a9f08958bb942b53afee084a5acd
felipefss/adventofcode
/2020/Day1/main.py
754
3.53125
4
# Part 1 with open('input.txt', 'r') as file: lines = file.readlines() years = [int(l.replace('\\n', '')) for l in lines] years.sort() def get_2_that_sum(year_list): size = len(year_list) for i in range(size - 1): for j in range(size - 1, 1, -1): if year_list[i] + year_list[j] == 202...
31735acf0e456e3c5c782593fc072dfc4552a777
felipefss/adventofcode
/2020/Day10/main.py
1,438
3.640625
4
def get_input(fname): data = [] with open(fname, 'r') as file: line = file.readline() while line: data.append(line.replace('\n', '')) line = file.readline() return data def part1(jolts): one_jolts = three_jolts = 0 for i in range(1, len(jolts)): di...
6db8fe3ab12d0993ee8032c5c118bd7399d4dce2
enverenver/myTestProject
/student.py
674
3.921875
4
class Student: def __init__(self, name, books_got=0, reader_type='student'): self.name = name self.books_got = books_got self.reader_type = reader_type def return_book_to_library(self, library, book): library.return_book_to_library(book, self.name) def return_book_to_teacher(...
f8d45e16621879e81b31baa95a68e65b91203b70
ZaneWarner/GoogleCompetitions
/CodeJam/2019/QualRound/B.py
283
3.734375
4
cases = int(input()) for case in range(1, cases+1): gridSize = int(input()) takenPath = input() myPath = "" for step in takenPath: if step == "S": myPath += "E" else: myPath += "S" print("Case #{}: {}".format(case, myPath))
699a6384d975ba47a0f38f0de10d700f7b8a6be9
ediziks/Predict-Future-Sales
/FinalProject/FinalProject.py
38,796
3.8125
4
#!/usr/bin/env python # coding: utf-8 # # Kaggle Competition Final Project # # # *1C Company* - Predict Future Sales # # **Motivation** # # *This challenge serves as final project for the "How to win a data science competition" Coursera course. In this competition you will work with a challenging time-series datase...
7e31942b56635ec1122e4ee36ae7127759ff1d29
H-B-P/WISHK
/Resources/PYTHON/repeater.py
593
4.28125
4
import sys #Imports sys, the library containing the argv function the_string=str(sys.argv[1]) #The string to repeat is the first argument given. target_number_of_repeats=int(sys.argv[2]) #The number of repeats is the second argument given. number_of_repeats=0 #Set this variable to zero, as there are no repeats at the s...
e8ed01bacf68dcdb7ef93b6568400b350c178544
shrestha-Prithivi/Graphics-lab
/graphics-lab/lab-2/DDA.py
547
3.65625
4
import turtle DDA = turtle.Turtle() def line(x1,y1,x2,y2): x = x1 y = y1 DDA.penup() DDA.goto(x,y) DDA.pendown() i = 0 dx = x2-x1 dy = y2-y1 if abs(dx) > abs(dy): steps = abs(dx) else: steps = abs(dy) x_incerement = dx/float(step...
22fb6967962195bdd0d0446611359ac1a6c1b677
flatplanet/Intro-To-TKinter-Youtube-Course
/title.py
961
3.71875
4
from tkinter import * root = Tk() root.title('Codemy.com - Change Titlebar Color') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x300") # remove title bar root.overrideredirect(True) def move_app(e): root.geometry(f'+{e.x_root}+{e.y_root}') def quitter(e): root.quit() #root.destroy() # Create Fake Titl...
fa364d2d9fa91c20a487a03b0ab5e3cc10e0b5c8
flatplanet/Intro-To-TKinter-Youtube-Course
/center_place.py
511
3.828125
4
from tkinter import * root = Tk() root.title('Codemy.com - Center A Thing With Place') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x500") button_1 = Button(root, text="Button 1", font=("Helvetica", 32)) button_2 = Button(root, text="Button 2", font=("Helvetica", 32)) button_1.grid(column=0, row=0) button_...
74057129dc6e090e129d287883829c3f4cf3b1a8
flatplanet/Intro-To-TKinter-Youtube-Course
/plots.py
418
3.53125
4
from tkinter import * from PIL import ImageTk,Image import numpy as np import matplotlib.pyplot as plt root = Tk() root.title('Codemy.com - Learn To Code!') root.iconbitmap('c:/gui/codemy.ico') root.geometry("400x200") def graph(): house_prices = np.random.normal(200000, 25000, 5000) plt.polar(house_prices) plt.s...
100b23dc4b9ed9cb0edb16f79a6c6012828b18bc
flatplanet/Intro-To-TKinter-Youtube-Course
/alpha.py
1,000
3.625
4
from tkinter import * import tkinter.ttk as ttk root = Tk() root.title('Codemy.com - Alpha Method') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x550") root.attributes('-alpha', 0.7) my_label = Label(root, text="Hello World!", font=("Helvetica", 20)) my_label.pack(pady=20) # Create Slide Function def slid...
16e94572cc075da4a6efe8fac2bf3bb82cb5d106
flatplanet/Intro-To-TKinter-Youtube-Course
/focus.py
656
3.546875
4
from tkinter import * root = Tk() root.title('Codemy.com - Tab Order') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x550") # Create some entry boxes red = Entry(root, bg="red", font=("Helvetica", 20)) white = Entry(root, bg="white", font=("Helvetica", 20)) blue = Entry(root, bg="blue", font=("Helvetica", 20...
c9e63e4caf62dd5304854d85de8473c36cd90853
flatplanet/Intro-To-TKinter-Youtube-Course
/fonts.py
635
3.859375
4
from tkinter import * from tkinter.font import Font root = Tk() root.title('Codemy.com - Custom Fonts') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x500") # Define Our Font bigFont = Font( family="Times", size=40, weight="bold", slant="roman", underline=0, overstrike=0) # Define Out Font mediumFont ...
80e33e5900486d5a1d29012ed6f9f199fe80a6d4
flatplanet/Intro-To-TKinter-Youtube-Course
/config.py
514
3.5
4
from tkinter import * root = Tk() root.title('Codemy.com') root.iconbitmap('c:/gui/codemy.ico') root.geometry("400x400") def something(): my_label.config(text="This is new text!!", font=("Helvetica", 8)) root.config(bg="blue") my_button.config(text="You've been configged!", state=DISABLED, pady=30) my_label =...
f316a68e724cca1135e78266e906e2b2063a7637
flatplanet/Intro-To-TKinter-Youtube-Course
/anim.py
1,067
3.796875
4
from tkinter import * root = Tk() root.title('Codemy.com - Simple Button Animation') root.iconbitmap('c:/gui/codemy.ico') root.geometry("400x300") #define some variables count = 0 size = 26 pos = 100 # Contract the button def contract(): global count, size, pos if count <= 10 and count > 0: size -= 2 # Configu...
21fd4fccc5fc5196d1e9e57cc104b43523e14c9f
flatplanet/Intro-To-TKinter-Youtube-Course
/flip.py
859
3.9375
4
from tkinter import * root = Tk() root.title('Codemy.com - Flip The Switch!') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x300") # Keep track of the button state on/off #global is_on is_on = True # Create Label my_label = Label(root, text="The Switch Is On!", fg="green", font=("Helvetica", 32)) m...
fce538f5364cab60503f391bc597928a2b6b07b4
flatplanet/Intro-To-TKinter-Youtube-Course
/listbox.py
1,890
3.578125
4
from tkinter import * root = Tk() root.title('Codemy.com') root.iconbitmap('c:/gui/codemy.ico') root.geometry("400x600") # Create frame and scrollbar my_frame = Frame(root) my_scrollbar = Scrollbar(my_frame, orient=VERTICAL) # Listbox! # SINGLE, BROWSE, MULTIPLE, EXTENDED my_listbox = Listbox(my_frame, width=50, ysc...
7ab00c2ef487935371700c4cda16888f28c5c786
flatplanet/Intro-To-TKinter-Youtube-Course
/bindtext.py
451
3.625
4
from tkinter import * root = Tk() root.title('Codemy.com - Bind Text!') root.iconbitmap('c:/gui/codemy.ico') root.geometry("500x500") def labeler(e): my_label.config(text=my_text.get(1.0, END + "-1c") + e.char) my_text = Text(root, width=50, height=20, font=("Helvetica", 12)) my_text.pack(pady=20) my_label = Labe...
fe5ce76c7668a352aaaee87214c88c30e934e957
surajjadli/Python-Programs
/ex7.py
179
3.953125
4
# sum of natural number # ask user for limit # print total limit = int(input("enter a number =>")) total = 0 i = 1 while i <= limit: total+=i i += 1 print(total)
cdeda8ee21b8749966fbe6cc9035509670a692aa
surajjadli/Python-Programs
/ex3.py
116
4.21875
4
# python program to take user name and print in reverser order name = input("enter your name ") print(name[::-1])
0ea791f6a430dd5bee1fb2fbc4c33fe263fa0889
m9i/myhackerrank
/leap_year.py
248
4.0625
4
def is_leap(year): leap = False if year >= 1900: if year%100==0: if year%400 ==0: leap=True if year%4==0: if (year/4)%2==0: leap=True return leap year = int(input()) print(is_leap(year))
73e4fbe2a31c14a95f19a427c48150661abbbba9
Meghali-Nandi/MACHINE-LEARNING-SCRIPTS-INITIAL-
/MACHINE LEARNING PROGRAMS/scripts/ml4.py
1,305
3.5625
4
#to determine how accurate the best fit line is! # using R- SQUARED THEORY from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('fivethirtyeight') #copy the 538.com style xs=np.array([1,2,3,4,5,6], dtype=np.float64)# describes how the bytes correspo...
055e91349cd2bad67aa56b205fa7cce3e16a52c1
polianaysato/Projects_JS_PY_C-_Java
/Pokemon/pokemon_starting/pokemon.py
7,963
3.984375
4
import random class Pokemon: def __init__(self, name, type_, level = 5): """ Parameters: string name, string type_ and integer level Description: constructor method of the Pokemon Class. The level parameter if not passed, it'll be set with the default value of 5. Both m...
d969f995611b9702a1f0ac04913aa29db657d5c0
ankitboghra/competitive-solutions
/Balanced Brackets.py
543
3.71875
4
#!/bin/python3 import sys left="{([" right="})]" def isBalanced(s): stack=[] for c in s: if c in left: stack.append(c) elif c in right: if not stack: return "NO" if right.index(c)!=left.index(stack.pop()): return "NO" if n...
2f4c023e7dc621c73c6aeee08cef0ea7fc663be8
Jusrealm9576/Python-Codes
/StudentManagement.py
1,281
3.859375
4
student_records = {} def printmenu(): print('''\n\n Student Management: 1. Add Record 2. View Record 3. Exit \n\n''') def menu(): choice = int(input("Enter your choice : ")) if choice==1: addrec() elif choice==2: viewrec() elif choice...
31ce2fd017376aa7ee6646a8abffbf949e66955f
Jusrealm9576/Python-Codes
/Menu2.py
1,675
4.03125
4
def question(): print("\n\t 1.Check wether string is pallindrome or not\n\ 2. Calculate total characters of string\n\ 3. Calculate total vowels in string\n\ 4. Calculate total spaces in string\n\ 5. Display string in reverse order\n\ 6. Exit\n") def menu(): a = int(input("Enter number [1-6]: ")) if a ==...
c1bdb723ad5d8e2413f5cbcd4f5302b5401717c2
samir711/PythonMasterClasses
/BooleanLoginDemo.py
291
3.53125
4
username = "user" password = "admin123" # if username == "admin" and password == "admin123": # print("You are valid User") # else: # print("Invalid User") if username == "admin" or password == "admin123": print("You are valid User") else: print("Invalid User")
187265438840c522246d6bf84af8a84e6b7a5a16
guoxiaolihd/jianshu_spider_flask
/datetimedemo.py
472
3.96875
4
from datetime import datetime def date_to_week(str_date): time_date = datetime.strptime(str_date,'%Y-%m-%d %H:%M:%S') week_day_dict = {0: '0周一', 1: '1周二', 2: '2周三', 3: '3周四', 4: '4周五', 5: '5周六', 6: '6周日'} print(time_date) print(type(time_date)) return week_day_dict[time_date.w...
1756b3874306fd65793fe19aa1d09087df2b23bb
edithli/Just-for-Fun
/python/PP4-preview/make_db_file.py
880
3.765625
4
#!/usr/bin/python3 ''' write db into file using silly ways re-typing examples ''' dbfilename = 'people-file' ENDDB = 'enddb.' ENDREC = 'endrec.' RECSEP = '=>' def storeFile(db, dbfilename=dbfilename): dbfile = open(dbfilename, 'w') for key in db: print(key, file=dbfile) for (name, value) in db...
579041daf230f5b7d5fde172f73c2104067e055e
chenx-eric/Python_Learning
/练习实例001.py
404
3.703125
4
# Python 练习实例001 # 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? num = [1, 2, 3, 4] for i in range(len(num)): a = num[i] for j in range(len(num)): b = num[j] for k in range(len(num)): c = num[k] if (a!=b and a!=c and b!=c): print('{}{}{}'.format(a, b, c))
c9205163210b849d7de98f13ccf8e4e6e5432343
ashminbhandari/problem-solving
/search-suggestions.py
1,214
3.8125
4
#create a new TrieNode class class TrieNode: def __init__(self): self.children = OrderedDict() self.words = [] #trie class with ability to search as well as insert class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for le...
597a35acd10f233b69b3409d4c6689dd1688ce25
ThomasLee94/pythonic
/list_comp.py
673
3.96875
4
# List comprehension str[start:end:step] trash = "trash" trash[::-1] => "hsart" # create list nums in range of 0-100 list_of_nums = [number for number in range(100)] # create tuple nums in range of 0-100 tuple_of_nums = (number for number in range(100)) # create a list with values 1-10 squared squares = [x ** 2 for...
aa89fa84609f1caca03eac629fa9c7d891f2a804
frostcutter778/Python-Code
/pandas/dataframe_data_filter.py
406
3.78125
4
### Importing important libries import numpy as np import pandas as pd ### Checking if my dataframe has the values of my list # dataframe created df = pd.DataFrame([1,2,3,4,5,6],columns = ['Filter']) #list created list2 = [1,4] #filtering the dataframe index ind=[df.index[df['Filter']==i].tolist() for i in list2] f...
f1d844cf58887f51ef4011cfeae0543bac71cac6
Andrewyzhang/freesurfer
/dmri_violinPlots.py
5,991
3.703125
4
#!/usr/bin/env python # Andrew Zhang # Professor Siless # July 2019 # plots.py # This program takes in a directory of subjects, a text csv file that organizes the subjects into # groups, and the name of a structure that the user wants data for. The program first organizes # the subjects into the numbered groups. For ...
8e6a333789c4c9ff39d302a7bb94ea0a5114fde3
simayhosmeyve/Machine_Learning
/Classification/knn.py
955
3.59375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd datas = pd.read_csv("values.csv") print(datas) x = datas.iloc[:,1:4].values #bağımsız değişkenler y = datas.iloc[:,4:].values #bağımlı değişken #print(x) #print(y) from sklearn.model_selection import train_test_split x_train, x_test,...
e99eef6dc73320bf7bc6ace8e3803a69c37751a5
ishal17/NLP_intro
/Decryptor/encryptor.py
1,327
3.96875
4
import random def manuallySetkey(): print('input key:') new_key = input() print('key updated: ', new_key) return new_key def setRandomKey(key): l = list(key) random.shuffle(l) key = ''.join(l) print('random key is: ', key) return key def encryptText(key): print('') print(...
80854a2ff8354d005c1b6035d1ed22532f42fd95
ronan583/QipaiGame-egret
/tools/zipgamerespak.py
3,224
3.671875
4
#coding=utf-8 #甄码农python代码 #使用zipfile做目录压缩,解压缩功能 import os,os.path import zipfile def zip_dir(dirname,zipfilename): filelist = [] if os.path.isfile(dirname): filelist.append(dirname) else : for root, dirs, files in os.walk(dirname): for name in files: filelist.append(os.path.join(root, name)...
396156698d60b0ff265e743fb37701ed09ea3b5b
platinum2015/python2015
/cas/python_module/v03_nested_loops.py
125
3.734375
4
fruits = ["apple", "banana", "melon"] for i in range(2, 6, 2): for f in fruits: print str(i) + " " + f + "s"
20b534a5f01faec753f8dbefed33be1ca76e9959
platinum2015/python2015
/cas/python_module/p05_alphabet_trainer.py
1,271
3.609375
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import random print("Exercise: Alphabet trainer mini project") alphabet = { 'A':'Alpha', 'B':'Bravo', 'C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', 'H':'Hotel', ...
d770c7acc4d3f42b7aeaf3b1f9856c89b1723b6e
platinum2015/python2015
/cas/python_module/v07_derivation.py
459
4.03125
4
import math def df(f, x , h): '''Computes the numerical approximation of the derivative of f at point x: f\'(x), using a small increment h around the value x''' return (f(x+h) - f(x-h)) / (2.0*h) f = math.sin for x in [0.0, 0.5*math.pi, math.pi]: #take some values in [0, pi] dx = df(f, x, ...
e36cf8cc4dd221c99604e47c41b14666d08ea001
platinum2015/python2015
/cas/python_module/v07_return.py
252
3.65625
4
def function(a): if a: return else: return (a, not a) x = function(True) y = function(False) z1, z2 = function(False) print "x: ", x, type(x) print "y: ", y, type(y) print "z1, z2: ", z1, type(z1), z2, type(z2)
56a6965014a8d529400257f90556692bb619861d
platinum2015/python2015
/cas/python_module/v07_nested_functions_2.py
440
4.1875
4
def derivative(my_function): '''Returns a function that computes the numerical derivative of the given function my_function''' def df(x, h=0.0001): return ((my_function(x+h) - my_function(x-h)) / (2*h)) return df def f(x): '''The mathematical function f(x) = x^3''' return x*...
c8874280aed111f9ddfdb8924c1761df091e6d92
platinum2015/python2015
/cas/python_module/v03_game_of_life_simple.py
1,999
3.703125
4
import os import copy import random import colorama #https://pypi.python.org/pypi/colorama #definition of grid size rows = 23 cols = 79 #initializations, e.g. board with random zeros and ones random.seed() colorama.init() generation = 0 empty = False board = [[int(random.choice('01')) for x in range...
97b8eb38dab2dd4fd7c5a38f71b4371cd419ff12
platinum2015/python2015
/cas/python_module/v07_braking_distance_revisited.py
370
3.765625
4
def get_braking_distance(v0,mu): ''' Calculates braking distance [m] with mu and v0 [km/h] ''' g = 9.81 # gravitational acceleration return 0.5*v0**2 / (mu*g) velocity = 100 #km/h friction = 0.2 print "The braking distance for v0=",velocity, print "and friction mu=",friction, print ...
0b7360bdf8002a8b0c5542ea2cfa08784855be7b
platinum2015/python2015
/cas/python_module/Day1_SampleSolutions/p02_braking_distance_SOLUTION.py
1,095
4.375
4
# Compute the distance it takes to stop a car # # A car driver, driving at velocity v0, suddenly puts on the brake. What # braking distance d is needed to stop the car? One can derive, from basic # physics, that # d=0.5*v_0^2 / mu * g # # Develop a program for computing d using the above formula when the ini...
546daedd507ef60eb00fcf5cad3bc1e8156af433
platinum2015/python2015
/cas/python_module/v04_shared_reference.py
417
3.71875
4
# List of restaurants my_restaurants = ['Mensa', 'Royal Mangal City', 'Migros', 'Tibits'] # Your like Bloom and not Tibits your_restaurants = my_restaurants your_restaurants[-1] = 'Bloom' # Print our restaurants print "These are MY favorite restaurants" for rest in my_restaurants: print "\t"+rest print "The...
ecbfcc58a30b07d0c5e4cecaaed9a90716c9bfd9
platinum2015/python2015
/cas/python_module/p09_numpy.py
640
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 9 15:34:49 2015 @author: programming """ import numpy as np x = np.random.normal(5, 2.5, size=10) print x print "Calculate the mean (should be close to 5)" print x.mean() print " Calculate the standard deviation (should be close to 2.5)" print x.std() print "Find the in...
7ea9dbb97530595e97fbc1930b8e850647428e10
elva02347/MTA-python
/day2-5.py
106
3.828125
4
dict1 = {'a':'apple','b':'banana','c':'cat','d':'dog'} for k,v in dict1.items(): print(k,'=>',v)
533a8f29becf71ed8fe5571d98c832a04efc7c32
andrewparker11/Unit-1
/change.py
392
4.03125
4
#Andrew Parker #9/8/17 #change.py - Tells how many coins you need to make up a given change cents = int(input('How many cents? ')) quarters = (cents//25) dimes = ((cents-(quarters*25))//10) nickels = ((cents-((quarters*25)+(dimes*10))//5)) pennies = (cents-((quarters*25)+(dimes*10)+(nickels*5))) print('You have', qua...
af4048f95ac2fa670dddc64719b6525c60955c17
lldaniel23ll/python
/Prueba4.py
152
3.8125
4
a=int(input("Digite A ")) b=int(input("Digite B ")) #esto cambiara los valores entre si a,b = b,a print(f"El valor de A es {a} y el valor de B es {b}")
f0408ee8513a9f7b3ae056e4ea40aeb86d43cc26
lldaniel23ll/python
/Prueba5.py
172
3.84375
4
#Calcular el area y longitud de una circunferencia r=float(input("Digite el Radio ")) area=3.1416*r**2 long=2*3.1416*r print(f"el area es {area}\nla longitud es {long}")
264cf3c5c543a3fdbe341cf89276f23f1a2da261
Negiz/database_from_excel_with_python
/excel_data_to_dict.py
2,406
3.921875
4
# -*- coding: utf-8 -*- # like the name says this code creates a dictionary from excel file # this module needs this openpyxl package however from openpyxl import load_workbook # I created two methods since one might need only a dictionary # workbook's sheet names are useful when trying to import the data to a datab...
71641ed6f59775a3b6642c85a7af6fbbef4d3381
kmader/superintendent
/superintendent/display.py
2,899
3.859375
4
"""Helper functions for displaying types of data.""" import operator import IPython.display import numpy as np import pandas as pd from matplotlib import pyplot as plt def get_values(data, idxs): """ Helper function to index numpy arrays and pandas objects similarly. Parameters ---------- data ...
f28434c4b64223440ba4454249a7782b85a9909c
Rafesz/URI_solutions_py
/1156.py
444
3.8125
4
# Escreva um algoritmo para calcular e escrever o valor de S, sendo S dado pela fórmula: # S = 1 + 3/2 + 5/4 + 7/8 + ... + 39/? # Entrada # Não há nenhuma entrada neste problema. # Saída # A saída contém um valor correspondente ao valor de S. # O valor deve ser impresso com dois dígitos após o ponto decimal. ...
fa7c7017c4ae728f83609351764d1d18ca792d16
Rafesz/URI_solutions_py
/1181.py
1,517
4
4
# Neste problema você deve ler um número, indicando uma linha da matriz na qual uma operação deve ser realizada, um caractere maiúsculo, indicando a operação que será realizada, e todos os elementos de uma matriz M[12][12]. Em seguida, calcule e mostre a soma ou a média dos elementos que estão na área verde da matriz, ...
4e8e207e6f60ee97fe4bfb6343fc35f044e285ec
Rafesz/URI_solutions_py
/1142.py
414
3.90625
4
# Escreva um programa que leia um valor inteiro N. Este N é a quantidade de linhas de saída que serão apresentadas na execução do programa. # Entrada # O arquivo de entrada contém um número inteiro positivo N. # Saída # Imprima a saída conforme o exemplo fornecido. i = 0 n = int(input()) x = 1 while...
b4b805e8104042ca11018754d4cf2cf9d2dffdaf
Rafesz/URI_solutions_py
/1589.py
963
3.59375
4
# Você tem em mãos dois cabos circulares de energia. O primeiro cabo tem raio R1 e o segundo raio R2. Você precisa comprar um conduite circular (veja a imagem abaixo que ilustra um conduite) de maneira a passar os dois cabos por dentro dele: # Qual o menor raio do conduite que você deve comprar? Em outras palavras, ...
0b096bb53d3e363abfec71d0ffba73a33f1922e8
Rafesz/URI_solutions_py
/1155.py
414
3.6875
4
# Escreva um algoritmo para calcular e escrever o valor de S, sendo S dado pela fórmula: # S = 1 + 1/2 + 1/3 + … + 1/100 # Entrada # Não há nenhuma entrada neste problema. # Saída # A saída contém um valor correspondente ao valor de S. # O valor deve ser impresso com dois dígitos após o ponto decimal. i = ...
c021b6747d6a32fba1a85c77e7f285339385b361
Rafesz/URI_solutions_py
/1144.py
573
3.84375
4
# Escreva um programa que leia um valor inteiro N. N * 2 linhas de saída serão apresentadas na execução do programa, seguindo a lógica do exemplo abaixo. Para valores com mais de 6 dígitos, todos os dígitos devem ser apresentados. # Entrada # O arquivo de entrada contém um número inteiro positivo N (1 < N < 1000). ...
75b1737a792c2f8241712f04e11d00e098430c4d
Rafesz/URI_solutions_py
/1050.py
922
4.0625
4
# Leia um número inteiro que representa um código de DDD para discagem interurbana. Em seguida, informe à qual cidade o DDD pertence, considerando a tabela abaixo: # Se a entrada for qualquer outro DDD que não esteja presente na tabela acima, o programa deverá informar: # DDD nao cadastrado # Entrada # A entrad...
a49b0071e34cbae31101b328165e6e8e9adcd434
Rafesz/URI_solutions_py
/1172.py
651
3.75
4
# Faça um programa que leia um vetor X[10]. Substitua a seguir, todos os valores nulos e negativos do vetor X por 1. Em seguida mostre o vetor X. # Entrada # A entrada contém 10 valores inteiros, podendo ser positivos ou negativos. # Saída # Para cada posição do vetor, escreva "X[i] = x", onde i é a posição do ...
673205011180f13b5d5d0d79c9437d2401b43fe7
Rafesz/URI_solutions_py
/1094.py
1,900
3.609375
4
# Maria acabou de iniciar seu curso de graduação na faculdade de medicina e precisa de sua ajuda para organizar os experimentos de um laboratório o qual ela é responsável. Ela quer saber no final do ano, quantas cobaias foram utilizadas no laboratório e o percentual de cada tipo de cobaia utilizada. # Este laboratór...
fd281bb8aab5c28f8731be5c9362df10b359b26e
Javran/leetcode
/find-and-replace-in-string/solution.py
2,273
3.640625
4
#!/usr/bin/env python3 # a Plan is just the tuple (index, src, tgt) # for indicating a "find-and-replace" plan class Plan: def __init__(self, index, src, tgt): self.index = index self.src = src self.tgt = tgt def __str__(self): return "({}, {}, {})".format(self.index, self.src,...
a41cb6972817f9a5ea2f751dfc72341a3b6bd8c4
baranmcl/HackerRank_Solutions
/Algorithms/Warmup/A_Very_big_sum/A_very_big_sum.py
167
3.671875
4
def bigsum(n): return sum(n) if __name__ == '__main__': num = int(input()) numbers = [int(i) for i in input().strip().split()] print(bigsum(numbers))
fe811c03eb3e99559347179c5aa6736a48167062
baranmcl/HackerRank_Solutions
/Algorithms/Strings/Make_it_Anagram/Make_it_Anagram.py
775
3.75
4
def anagram(x, y): delcount = 0 xletters = {} yletters = {} for letter in x: if letter not in xletters: xletters[letter] = 1 else: xletters[letter] +=1 for letter in y: if letter not in yletters: yletters[letter] = 1 else: ...
2dba41334577686f2b35201bf2400bda6d7b87b0
baranmcl/HackerRank_Solutions
/Algorithms/Strings/Funny_String/Funny_String.py
609
3.6875
4
def funny(x): alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] backwards = x[::-1] for i in range(len(x)-1): answer = abs(alphabet.index(str(x[i])) - alphabet.index(str(x[i+1]))) backwards_answer = a...