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
d79119bf1d78ac23864072cfbeebb57f4e930682
alecha98/lab10
/1.py
91
3.75
4
A = set('bqlpzlkwehrlulsdhfliuywemrlkjhsdlfjhlzxcovt') B = set('zmxcvnboaiyerjhbziuxdytvasenbriutsdvinjhgik') for x in A: if (x not in B)==True: print (x)
cb6f797dde9f6f10e490b063fb2256e0691fec66
jpfairbanks/dataflowstreams
/variance.py
4,932
3.703125
4
import math import collections import numpy as np import numpy.random as rand import scipy import scipy.stats as stats import matplotlib.pyplot as plt class variance_state(object): """This object encapsulates the data necessary to maintain a streaming variance estimator. This includes the sum, variance, count...
b4b42c5f51f6d765b0468dd70f6b7fa2ff8d2d41
momentum-cohort-2018-10/w2d1-currency-converter-stevelknievel
/currency_converter.py
357
4
4
def convert(rates, value, current, to): if current == to: return value for conversion in rates: # rates=("USD", "EUR", 0.74) if current == conversion[0] and to == conversion[1]: return value * conversion[2] if current == conversion[1] and to == conversion[0]: ...
571fae45eb72ca03e44df56c1c9d6b49f378a070
swkane/katas-fns-loops
/main.py
638
4.0625
4
def add(x, y): return x + y print(add(2, 4)) def multiply(x, y): result = 0 for i in range(x): result = add(result, y) return result print(multiply(6, 8)) def power(x, n): result = 1 for i in range(n): result = multiply(result, x) return result print(power(3, 4)) ...
9485759ef1b43b19642b35039ec0e5a0e5408f36
raylyrainetwstd/MyRepo
/M07_Code_Fixed.py
2,458
4.1875
4
#this function takes an input from a user in response to a question #if the user input is not a number, is_num doesn't accept the user input def is_num(question): while True: try: x = int(input(question)) break except ValueError: print("That is not a number") ...
91cd8ab16e42d87249023a65929e46bc756e857a
raylyrainetwstd/MyRepo
/SDEV120_M02_Simple_Math.py
452
4.1875
4
#get two numbers from user #add, subtract, multiply, and divide the two numbers together and save the values to variables #print the results on one line num1 = int(input("Please type a number: ")) num2 = int(input("Please type another number: ")) addition = str((num1 + num2)) subtraction = str((num1 - num2)) multiplic...
c943548f6d510df7aa377e98138d746a6a1c4257
raylyrainetwstd/MyRepo
/if.py
191
4.125
4
var1 = "no" if var1 == "yes": print("The variable is 'yes'") elif var1 == "YES": print("THE VARIABLE IS 'YES'") else: print("No other condition met") print("The program is done.")
c1aec2cea45a24343cd256ce013cce9d5b19c1f6
NadalChi/LeetCode
/Algorithms/python/0103. Binary Tree Zigzag Level Order Traversal/103. Binary_Tree_Zigzag_Level_Order_Traversal.py
1,189
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root): temp = [] roots = [] roots.append(root) ans = [] if root == Non...
812ee3c9b1c5a27cbae44f8dc4420fc9afba0bb9
NadalChi/LeetCode
/Algorithms/python/0107. Binary Tree Level Order Traversal II/Binary_Tree_Level_Order_Traversal II.py
542
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] nodes = [root] ...
f53b640eec6b34c3543467cfc2ee816566fc53e7
Isaac-Kwon/pyqupid
/qupid/Tools.py
1,403
3.734375
4
import numpy as np from .Grapher import PrintTFGrid def ShrinkTFArray(array): """ 임의의 ndarray 를 받아 False 만으로 이루어진 외곽의 행 또는 열을 제거하여 압축할 수 있는 함수. Parameters ---------- array : numpy.ndarray 출력할 ```True``` 와 ```False``` 로 이루어진 **2차원** 행렬 Returns ------- farray : numpy.ndarray...
df55e91a7e96de2db576b66d6969e8232693a6eb
RiccardoBonini/ProgettoAI
/Main.py
3,425
3.578125
4
import numpy as np import mnist_reader import KernelVotedPerceptron as kvp from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report import matplotlib.pyplot as plt #we load the complete dataset X1, y1 = mnist_reader.load_mnist('data/fashion', kind='train') X2, y2 = mnist_...
0372b9af917ad962bda20194619c7a90f12c47b4
minahkeem/random_practice
/CTCI/8_2.py
2,085
3.796875
4
#8.2 Robot in a Grid def find_path(arr): path = [(0,0)] helper(arr, path, 0, 0) reverse_list(path) return path def helper(arr, path, x, y): if arr[x][y] == 1: if x == len(arr)-1 and y == len(arr[0])-1: path.append((x,y)) return 1 r, d = 0, 0 ...
4e4f9aa9a5f2a077153880e4df806506917acc88
minahkeem/random_practice
/CTCI/find_pair.py
783
3.703125
4
def find_pair(int_list, num): l = 0 r = len(int_list)-1 max_sum = (int_list[r]+int_list[l], l, r) while r > l: print(max_sum[0]) if max_sum[0] > num: r -= 1 elif max_sum[0] < num: l += 1 else: break if r > l: ...
fc0a7ea36b4ca9959ca0e456449d9eaa7edbd704
JevonWei/scripts
/factorial-2.py
215
4.09375
4
def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) number = int(input("please input a number: ")) result = factorial(number) print("%d的阶乘是:%d" % (number,result))
caef70a04c0e57a35f29cd0605c042769b66e501
SkyScraperGames/ciraui
/src/assets/lessons/python/5/code.py
369
3.5625
4
from cira.ciragame import * class MyGame(CiraGame): # called when each frame needs to be drawn def draw(self): cira.display.clearScreen(0, 0, 0) # Draw your character by placing pixels # use the cira.display.putPixel(x, y, r, g, b) function from lesson 4 # each pixel needs to be...
19305901b6d70c7a6c8410c92d6bf8be98427e65
cuichacha/MIT-6.00.1x
/Week 1: Python Basics/2. Core Elements of Programs/Exercise-vara varb
280
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 22 09:37:58 2019 @author: Will """ if type(varA)==str or type(varB)==str: print ("string involved") elif varA>varB: print ("bigger") elif varA==varB: print ("equal") else: print ("smaller")
c19aec51c11b8f95adf776e0c13362e6ae319c80
cuichacha/MIT-6.00.1x
/Week 2: Simple Programs/4. Functions/Towers of Hanoi-4.py
430
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 14 16:03:45 2019 @author: Will """ def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' testValue = min(a, b) # Keep looping until testValue divides both...
3042a58e9d3deadaad9caa2291f2a672798b482d
cuichacha/MIT-6.00.1x
/Week 2: Simple Programs/4. Functions/Recursion on non-numerics-1.py
621
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 15 20:54:15 2019 @author: Will """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' if aStr=="": return False if char==aS...
369c812ba11e4fa179c51fe7531313f588fba177
sowjanya87/EasyData
/missing_data.py
1,785
3.84375
4
# 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('Data.csv') X = dataset.iloc[:, :-1].values Y= dataset.iloc[:, 3].values # Taking care of missing data dataset=pd.read_csv('Data.csv') from sklearn....
c168badb4cd52b20f1f318dc659350d4d4fae361
taoroalin/catan_py
/test.py
5,221
3.53125
4
import unittest import manager import board import numpy as np class PlayerTest(unittest.TestCase): def setUp(self): self.player = board.Player(None) self.bank_statement = {"Wood": 1, "Brick": 1, "Wheat": 1, "Rock": 1, "Sheep": 1} self.blank_bank_statement = {...
59a1f07ba4755c538e52e136ec81e9bc79a2b960
kapilnegi67/PythonSeleniumDemo
/src/selenium_with_python_demo.py
450
3.53125
4
from selenium import webdriver driver = webdriver.Chrome(executable_path=r"/Users/kapilnegi/Desktop/chromedriver") driver.get("https://demoqa.com/") element = driver.find_element_by_link_text("Selectable") element.click() select_list = driver.find_element_by_id("selectable") select_list.find_element_by_xpath("//li[t...
6a04d4db960771bc105e85df7c23b33202842c35
chinu1996/pythonPrac
/learning/class_variables.py
902
3.78125
4
class Employee: raise_amount = 1.05 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.fullname = self.first + ' ' + self.last def promotion(self): new_pay = (self.pay * self.raise_amount) self.pay = new_pay ...
96a7c9c0f28c2bd640a46ba1cac46d6ff3ee3bde
chinu1996/pythonPrac
/Get_requests.py
268
3.546875
4
# Import package import requests # Specify the url: url url="http://www.datacamp.com/teach/documentation" # Packages the request, send the request and catch the response: r r=requests.get(url) # Extract the response: text text=r.text # Print the html print(text)
dbcee04ae65e39535bd826d323cd249b00bf2d5c
chinu1996/pythonPrac
/DSandAlgo/Trees/disk_space.py
273
3.625
4
def disk_space(T, p): """Return total disl space for subtree T rooted at p""" subtotal = p.element().space() #space used at postion p for c in T.children(p): subtotal+= disk_space(T, c) #add child's space to subtotal return subtotal
3a4a10aee0f2cbfd671e0ecd39c5e336222df2b1
chinu1996/pythonPrac
/DSandAlgo/LinkedList/MaintainingAccessFrequency.py
3,550
3.640625
4
from .DoublyPositionList import PositionalList class FavoritesList: """List of elements ordered from most frequently accessed to least""" # --------------NESTED ITEM CLASS---------- class _item: __slots__ = '_value', '_count' def __init__(self, e): self._value = e ...
1db6aaac34a4b193d480095f5ecad953b066c813
YuvrajRajpoot-Dev/Hangman-Game
/hangman.py
2,710
3.90625
4
import random def hangman(): word = random.choice(['notebook','classroom','system','network','python','javascript','banana','jackfruit','friends','wineglass','yellow','green','square','cube','save','safe']) guess_word_list = '' missed = 10 while len(word) > 0: main = '' for letter in w...
7c96d230f93a618a5effdf4e35eab119895308a3
EveYu0130/Computer-Networks
/A1/server.py
2,010
3.53125
4
from socket import * import sys def UDP_Transaction(serverUDPSocket): # receives the string and sends the reversed string back to the client msg, client_address = serverUDPSocket.recvfrom(2048) reversed_msg = msg[::-1] serverUDPSocket.sendto(reversed_msg.encode(), client_address) def TCP_Negotiation(r...
efedbfa16fe07959f1cbbbb6c8c43d5151e5ba34
CaptainTralfaz/Shallow_Seas
/src/components/cargo.py
6,276
3.625
4
from enum import Enum class Cargo: def __init__(self, max_volume, max_weight, manifest): """ Holds maximum weight and volume of a container, and a list of Items currently held TODO: make over-weight effect ship's momentum value TODO: make over-weight effect targeted features (highe...
26b702480b13fa26d33ec0bd3573702bbaf31d61
sreenathmmenon/DSA
/Two-Pointers/MiddleOfLinkedList.py
1,116
4.09375
4
### Given the head of a singly Linked List. Return the middle node of the linked list ### If there are 2 middle nodes, return the 2nd middle node # head = [1,2,3,4,5] ## Note: In Linked List, we usually use the head node(first node) to represent whole list ### Answer ## Use 2 pointers - fast and slow. ## Fast moves w...
79a204a243f38c9c693b6a7b9660077ca0c2d003
TrinTragula/ClumsyPygeon
/src/provahash.py
313
3.59375
4
board = "rnbqkbnr" \ "pppppppp" \ "00000000" \ "00000000" \ "00000000" \ "00000000" \ "PPPPPPPP" \ "RNBQKBNR" table = {} print board+"00"+"bianco" key = hash(board+"00"+"bianco") table[key] = 12 if hash(board+"00"+"banco") not in table: print "Ok"
7b47b637f5f2ab8c145344bbf6bb03d88eecb846
Gildardo19/Ice_Cream_project
/main.py
31,546
3.921875
4
"""This is my integration project.""" __author__ = "Gildardo Miguel" """This program is used to make a transaction of ice cream through the system either for a large number of people or individual buyers. While giving an opportunity for the buyer to win a discount when a user buys in large.""" # Jairo help...
12e586220eea9db292ec3cfbdc384a043780b48a
AmmarRashed/EmoTagger
/Trie.py
886
3.875
4
class Node(object): def __init__(self, char: str): self.char = char self.children = list() self.tag = None self.counter = 1 # number of words having this character def add(root, emotic: str, tag: str): node = root for char in emotic: in_child = False # is t...
55fb287cc6788e0a5cc054410c18054f67675b7a
Satyam2000/CS384_1801EE48
/Projects/P2 Notepad_GUI/p2_main.py
22,639
3.921875
4
#A Python project to Make Notepad using Tkinter ....... # Group members:- #Satyam Kumar (1801EE48) #Kishan Kumar singh (1801EE22). import pathlib import datetime import tkinter as tk from tkinter import ttk from tkinter.scrolledtext import ScrolledText from tkinter import Event, font a...
f1f4ca1185dda31236ba9bd5ceded47043312d59
enireves/converter
/andbis.py
462
4.25
4
weather = input("What's the weather like? ") temperature = input("What temperature is it? ") if weather == "rainy" and temperature == "cold" : print("Take an umbrella and a warm jacket.") elif temperature == "warm": print("Take an umbrella and a shirt.") elif weather == "sunny" and temperature == "cold": pr...
d8c46a5579c206e35a7c1f7963dda2643504b664
enireves/converter
/ittt.py
187
3.84375
4
password = "secret" user_input = input("Enter the password: ") if password == user_input: print("You are now logged in.") if password != user_input: print("Wrong password.")
067413cb155c291b31def5c0b5c4a8507ea81163
enireves/converter
/guess.py
224
3.796875
4
secret_number = str(5) guess = input("Guess my secret number. It's between 1 and 10: ") if secret_number == str(guess): print("Congrats! You found the right one.") else: print("You lose!") print("Try to play again!")
216aefe64aeb383e4e0da112e08540f43fb6eca6
ando-huang/DeepLearning
/ConvolutionalNN/convolutional_reduction.py
749
3.71875
4
def printMatrix(matrix): for i in range(len(matrix)): print(matrix[i]) def convolute(matrix): rows = len(matrix) cols = len(matrix[0]) output = [[0 for col in range(cols-1)] for row in range(rows-1)] convolute = [[2, 0], [0, 1]] for i in range(len(output)): for j in range(len(ou...
1ab2d88f09aedee3bcb579b977f6a1b36679308e
Vladimirescu/RL_stocks
/Environment.py
4,249
3.78125
4
import numpy as np from itertools import product class Environment: """ Sock prices environment n_step = number of days for which we know the stock values n_stock = number of different stocks cur_step = current day data = numpy array with dimension (n_step, n_stock) containing all stock prices...
88fbf04122f3bc56b66cdb94a1cd753c01891010
Mickho/function
/function.py
1,135
4.09375
4
# function 函式/功能 #用來收納程式 #是個功能 def wash(dry): print('wash') print('Add wash') print('route') if dry: print('烘衣') wash(True) #use function dry=True wash(False) # dry=False def say_hi(): print('hi') say_hi() def add(x, y): print(x + y) add(3, 4) add(123, 333) def add(x=1, y=2): #參數可以有預設值 可以直接印 print(x + ...
f12b661134198995402bfdfd54a3df7c0e327f53
100ballovby/8v_3ch
/2601/main.py
930
4.09375
4
''' while логическое_выражение: действие 1 ... действие n ''' # просим ввести в переменную число с клавиатуры n = input('Введите число: ') # пока в переменной n не будет целого числа (int) while type(n) != int: # пытаемся привести число n к целому виду try: n = int(n) # если не получает...
24e336af62d265752b65a5861dd9e74e3692c91c
derysudrajat/gui-lab
/Pertemuan1/TugasPrak1.py
249
3.875
4
userInput = float(input("Masukan Nilai: ")) print("Nilai Kamu: ") if userInput >= 80 : print("A") elif 80 > userInput >= 70: print("B") elif 70 > userInput >= 60: print("C") elif 60 > userInput >= 40: print("D") elif userInput < 40: print("E")
5f045bf209499c204da78e62ff7531bb2cda0665
rlwest/Learning-Models
/simple_production_v1.py
2,149
3.515625
4
#################### ham cheese production model ################### # this is the simplest type of act-r model # it uses only the production system and one buffer # the buffer represents the focus of thought # we call it the focus buffer but it is often called the goal buffer # productions fire if they match the focu...
bcd396ad5c2ab27d1f11a224cba744b2cff2846f
amanchauhan98/mini-project
/Mini_project.py
1,524
3.9375
4
import time print("|---------------------------------------------|") print(" MINI PROJECT OF GAME AND OTHER COMPONENTS ") print("|---------------------------------------------|") print(" developed by Aman chauhan") time.sleep(2) # print("Enter your name please!") name = str(input("En...
21b7ef1229a48fda1e79c786ed602c56704809a7
Elza-MerilGucic/HW8
/HW8.2/main.py
175
3.8125
4
guess = int(input("Guess the secret number: ")) secret = 5 if secret == guess: print("Congratulations, you guess the secret number!") else: print("Please try again")
083a2d404922c25ca29310ead58938ebcf613db7
quangvinh86/python-projecteuler
/PE-010/summation_of_primes.py
949
4.125
4
""" Solution to Project Euler problem 10 @author: vinh.nguyenquang @email: quangvinh19862003@gmail.com """ import math UPPER_LIMIT = 2000000 def is_prime(number): if number <= 1: return False elif number <= 3: return True elif not number % 2: return False max_range = int(ma...
d43309c31dc82e6b5c94c61d868c90392ca38403
quangvinh86/python-projecteuler
/PE-019/sundays_counting.py
545
4.03125
4
""" Solution to Project Euler problem 19 @author: vinh.nguyenquang @email: quangvinh19862003@gmail.com """ import datetime def count_sundays(): return sum(1 for y in range(1901, 2001) for m in range(1, 13) if datetime.date(y, m, 1).weekday() == 6) if __name__ == "__main__": i...
8a3b93934edb8bb99c7358f3da8e8e9eb29c1988
Lucaseduedu/trabalhos404
/exer2.py
484
3.859375
4
def crescente(a,b,c): if a > b and a > c: if b > c: return c,b,a else: return b,c,a elif b > a and b > c: if a > c: return c,a,b else: return a,c,b elif c > a and c > b: if a > b: return b,a,c else: ...
9318b3753f67a7b84e1ecce2bc8828ae23615742
Lucaseduedu/trabalhos404
/exer11.py
264
3.640625
4
def votar(idade): if (2017 - idade) > 18 : return "Voce pode votar" elif (2017 - idade) < 18: return "Nao pode votar" try: idade = int(input("Digite sua idade: ")) print(par(x)) except: print("Digite sua idade corretamente")
f5e328337f980bb0d0a251fbf2088af0ca868df1
bjb40/task_tracker
/tracker.py
3,424
3.671875
4
""" This is a simple task-tracker that saves data into a pre-specified csv location. """ # import dependencies from datetime import date, timedelta as td import datetime import time as now import pandas import csv #Define Timer Object class Timer(object): """A simple timer class""" def __init__(self): ...
36f2b4deae67bab8203022ddddfff3c6f3b8f3e3
indrajithi/code-lab
/pyLab/varlen.py
210
3.5625
4
def sumall(*args): r_sum, i = 0,0 n = len(args) while(n): r_sum = r_sum + args[i] print i i += 1 n -= 1 print r_sum if __name__ == '__main__': sumall(1,2,3,4,5)
36584a8aa0298b83b6b9d6d83b3d29c93ab86b05
indrajithi/code-lab
/pyLab/prg.py
187
4.09375
4
x = int(raw_input("please enter an integer:")) if x < 0: x = 0 print "negetive number changed to zero:" elif x == 0: print 'Zero' else: print 'x greter than zero: ', x
1d0015f274d848ab69a9c50597b63cfbd41bb68a
indrajithi/code-lab
/pyLab/prg2.py
277
3.734375
4
from sys import argv script , filename = argv txt = open(filename) print "here is your file %s: " % filename print txt.read() #print "type another filename:" #file_nw = raw_input("> ") #txt_nw = open(file_nw) #print txt_nw.read() print "--------------" print txt.read()
cc7bf998dc1b446c9bbe4b5f1455c5e62b7c8276
FrankCardillo/practice
/2016/codewars/python_practice/digital_root.py
577
4.21875
4
# A digital root is the recursive sum of all the digits in a number. # Given n, take the sum of the digits of n. # If that value has two digits, continue reducing in this way until a single-digit number is produced. # This is only applicable to the natural numbers. def digital_root(n): total = 0 stringified = ...
45002426aa431a2796f6dce4e2805e25a9a4d387
KSneijders/AoE2ScenarioParser
/AoE2ScenarioParser/objects/support/trigger_select.py
1,598
3.640625
4
from typing import Type from AoE2ScenarioParser.objects.data_objects.trigger import Trigger class TriggerSelect: """ Object used to select a trigger in many trigger related functions. For ease of use, the alias `TS` can be called. You can also use those in combination with the class methods (factory meth...
f955286894d5ee99a575169bd2bb89a9e3e32f9e
linkenpeng/python
/src/exception/10.3浮点转换异常.py
1,220
3.765625
4
''' - BaseException |- KeyboardInterrupt |- SystemExit |- Exception |- (all other current built-in exceptions) 所有当前内建异常 ''' def safe_float(obj): try: retval = float(obj) except ValueError: retval = 'could not convert non-number to float' except TypeError: retval =...
5edf5a0c72313b138d19cc897c4fc5300f830f19
fearlessfreap24/codingbatsolutions
/List-2/sum67.py
943
3.9375
4
def sum67(nums): if 6 not in nums: return sum(nums) else: ret = 0 flag = False for num in nums: if num == 6: flag = True continue elif num == 7 and flag: flag = False continue if ...
3bf5ade42b130da096065f8dd3b16288398946f4
fearlessfreap24/codingbatsolutions
/List-1/max_end3.py
422
4.03125
4
def max_end3(nums): if nums[0] >= nums[-1]: return [nums[0],nums[0],nums[0]] if nums[0] < nums[-1]: return [nums[-1],nums[-1],nums[-1]] if __name__ == "__main__": print("{} :{}".format([1,2,3],max_end3([1, 2, 3]))) print("{} : {}".format([11,5,9],max_end3([11, 5, 9]))) print("{} :...
64d160e63a22e09b5004d5639a2dc97cffb4d2b3
fearlessfreap24/codingbatsolutions
/Warmup-2/string_bits.py
262
3.859375
4
def string_bits(str): newstr = "" for i in range(len(str)): if i%2 == 0: newstr += str[i] return newstr if __name__ == "__main__": print(string_bits('Hello')) print(string_bits('Hi')) print(string_bits('Heeololeo'))
b7fab26d44f16a123f15142f6aac5cd697abcf58
fearlessfreap24/codingbatsolutions
/Logic-2/make_chocolate.py
572
4.125
4
def make_chocolate(small, big, goal): # not enough bricks if big * 5 + small < goal: return -1 # not enough small bricks goalmod = goal % 5 if goalmod > small: return -1 # enough small bricks if big < goal // 5: return goal - (big * 5) if big >= goal // 5: ...
151e2845cdd09fa9a8f7668a6d93d9a732e4c64f
abhisheksingh102/Python_Programs
/ReadLine.py
179
3.96875
4
# Q. Write a Python Program to read first n lines of a file. f=open('abc.txt','r') n=int(input("Enter the number of line\n")) for i in range(n): print(f.readline()) f.close()
57c0533a02365f3ccddca0ff6964a5ed118add1d
thebertster/aoc_2020
/day_02.py
712
3.515625
4
from lib.aoclib import AOCLib puzzle = (2020, 2) # Initialise the helper library aoc = AOCLib(puzzle[0]) puzzle_input = aoc.get_puzzle_input(puzzle[1], AOCLib.lines_to_list) valid_passwords_1 = 0 valid_passwords_2 = 0 for entry in puzzle_input: split_1 = entry.split(': ') password = split_1[1] split_2...
f775d5fdc6c09aa3735be36062241fafc680610e
thebertster/aoc_2020
/day_03.py
931
3.546875
4
from lib.aoclib import AOCLib def count_the_trees(forest, vector): height = len(forest) width = len(forest[0]) position = (0, 0) number_of_trees = 0 while True: position = (position[0] + vector[0], position[1] + vector[1]) if position[1] >= height: return number_of_tr...
0b7871368541a36ea8e3776166d7c1a4fd314f93
thebertster/aoc_2020
/day_18.py
3,561
3.828125
4
from lib.aoclib import AOCLib def evaluate_expression(expression, precedence): # Converts each problem into a Reverse Polish stack! # # e.g. for "normal" operator precedence, converts: # ((1 + (2 * 3 + (4 - 1 + (8 * (6 - 1) + 5 + 2)) ^ 2)) + 5) # # to: # # 1 2 3 * 4 1 - 8 6 1 - * 5 + 2...
40baa8a6b07485dce06ea8be9c39d5ba2a423cc5
flamever2015/Starbucks_Capstone
/build_model.py
1,063
3.53125
4
def evaluate_model_performance(clf, X_train, y_train, class_name): """ Prints a model's accuracy and F1-score INPUT: clf: Model object X_train: Training data matrix y_train: Expected model out...
60a9f21b8df81f1d193bb6c4f67ccee0170a4b9c
tslmy/ICWSM2019
/_tools.py
1,808
3.96875
4
#!/usr/bin/env python import numpy as np import numpy.linalg as la def orthogonalize(U, eps=1e-15): """ credit: <https://gist.github.com/anmolkabra/b95b8e7fb7a6ff12ba5d120b6d9d1937> Orthogonalizes the matrix U (d x n) using Gram-Schmidt Orthogonalization. If the columns of U are linearly dependent with...
b337e425f2ce7a6755626b0f8fb295630ffb3b0f
Paul199199/THU-transfer-data
/Ex02.py
598
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 18 19:14:11 2021 @author: user """ data = [ 10,20,30,40,50] data2 = [] for i in data: data2.append(i) data.append('A') print(data) print(data2) import copy number = [1,2,3,4,5] newnum = copy.copy(number) number[0] = 99 print(newn...
f7107f6f7b5d2d36ff54560c229c2625061b8269
Paul199199/THU-transfer-data
/報表建立.py
741
3.578125
4
def personal(name,dep,*score): print('Student:',name) print('Depatment:',dep) total = sum(score) if len(score) ==0: print('Student:{},Depatment:{}'.format(0,0)) else: print('total score:{},Balance:{}'.format(total,total/len(score))) personal('Paul','English',85,95,70) personal('...
46c222edc1342a2776a5b836bd56683f0e9caf42
Paul199199/THU-transfer-data
/while迴圈.py
362
3.953125
4
#while迴圈 # i = 1 # while i<10 : # print(i) # i+=1 # print('SystemExit') #猜數字 # import random # ans = random.randint(1,100) # guess = 0 # while ans != guess : # guess = int(input("Type a number between 1-100:")) # if guess > ans: # print('small') # if guess < ans: # pri...
c22710e31de002e72d5e1036d0e19c095f3e0c62
000alen/RE
/RE/RegularExpression/Expression.py
5,847
3.953125
4
from typing import List, Tuple, Iterator from RE.FiniteStateMachine import FiniteStateMachine __all__ = ( "Expression" ) # TODO: Use abc.ABCMeta and @abstractmethod class Expression: """Baseclass for Regular Expressions. Examples: >>> from RE.RegularExpression.Expression import Expression ...
d48a50bc312ecf6a1ecca31c51004c922eacbf1b
akjayant/Data-Structures-Algorithms-and-OOPS-in-Python
/singleton.py
666
3.921875
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 23 14:48:06 2017 @author: Ashish Kumar Jayant """ class Singleton(object): _instance = None age = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__( ...
9a2a8efbab600dc925050e1cf6dc0843d1bbd145
missglory/algorithms
/algorithmic_toolbox/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.py
512
3.640625
4
# Uses python3 import sys arr = [0] * (int)(1e5 + 2) arr[:3] = [0,1,1] def get_fibonacci_huge_naive(n, m): if n <= 3: return arr[n] for i in range(3, min(n + 1, 10 * m + 1)): # previous, current = current, previous + current arr[i] = arr[i-1] + arr[i -2 ] arr[i] %= m ret...
bec25453c1cd382fd14d2a288687b285afd82656
felit/art-of-computer-programming
/chapter03/section3_1/algorithm_k.py
1,902
3.515625
4
# -*- coding:utf8 -*- def k1(x): y = x / (10 ** 9) for i in range(0, y + 1): x = k2(x) # print 'num = %010d' % x print '\'%010d' % x # print 'y = %s' % i return x def k2(x): z = x / (10 ** 8) % 10 if z <= 0: x = k3(x) # print x if z <= 1: ...
7c33df4cb6c26b6e82fc78cdb20ca25e8a3cb7d3
patnir41/Facebook-Chat-Analysis
/chat_analysis.py
2,378
3.65625
4
import string DATA_FILENAME = "message_logs.txt" def add_one_to_count(counts, counted, month): if counted not in counts: counts[counted] = {} inner_counts = counts[counted] if month not in inner_counts: inner_counts[month] = 0 inner_counts[month] += 1 return counts def get_count...
2b88bad5e7887da6f38965e23e5649d270ca46f0
Dicmark/polotic_web_fullstack_con_python_javascript
/estructuras_de_control_y_toma_de_decisiones/script.py
851
4.0625
4
#Listas nombre =["harry", "ron","hermione"] print(nombre) #Para acceder a un elemento se hace de la siguiente manera print(nombre[2]) #Para agregar elementos nombre.append("draco") print(nombre) #Para ordenarlas nombre.sort print(nombre) #Sets conjunto = set()#Se crea el conjunto vacio #Para agregar un elemento al ...
7d168d5314a56ca21428b71dada7eeab05f191f9
CodeNameRobin/MadLibLoop
/MadLibLoops.py
833
3.5625
4
import random user_state = str(input("State something and then an amount of that!\n" "Example: bannanas 12\n" "Type QUIT 0 to quit!\n" ">")) user = user_state.split() if user[0] == '0': print("Goodbye!") quit() else: pass ...
42333d3227e6f139bf6a5cf5174bb05136c9be8a
ketkat001/Programmers-coding
/Level_2/전화번호목록.py
274
3.734375
4
def solution(phone_book): phone_book.sort() for i in range(len(phone_book)-1): for j in range(i+1, len(phone_book)): if phone_book[j].startswith(phone_book[i]): return False return True print(solution(["123", "456", "789"]))
e83ca40def84917f2b19dc6c7f1e77cadc08b065
ketkat001/Programmers-coding
/Level_2/거리두기확인하기.py
1,261
3.578125
4
def checking(people, place): for p in range(len(people) - 1): for q in range(p + 1, len(people)): if abs(people[p][0] - people[q][0]) + abs(people[p][1] - people[q][1]) <= 2: p1, p2 = people[p], people[q] if p1[0] == p2[0] and place[p1[0]][(p1[1]+p2[1])//2] != 'X'...
d6db922fa316fb84e86e2f99a64c0b2376ee3133
ketkat001/Programmers-coding
/Level_2/최댓값과최솟값.py
205
3.609375
4
def solution(s): answer = '' s = list(map(int, s.split(' '))) max_num, min_num = max(s), min(s) answer = str(min_num) + ' ' + str(max_num) return answer print(solution('-1 -2 -3 -4'))
71b2ff455314982c6071e1e3dc545b00884d97d8
ketkat001/Programmers-coding
/Level_3/이중우선순위큐.py
753
3.53125
4
import heapq def solution(operations): queue = [] max_queue = [] for operation in operations: if operation[0] == 'I': heapq.heappush(queue, int(operation[2:])) heapq.heappush(max_queue, -int(operation[2:])) else: if len(queue) == 0: conti...
6c03b1e62f5c2006e3dce37a7d44b1f4ccb63625
joseruben123/EstructuraDatos
/S15-TAREA_4-Ejercicios_Clases/pila.py
1,114
3.90625
4
class Pila: def __init__(self, tamanio=1): self.lista=[] self.size=tamanio self.top=0 def push(self, dato): if self.top < self.size: self.lista += self.lista+[dato] self.top+=1 else: print("La lista esta llena") ...
58724808401d4280a852997f06a00f4480d75aeb
Maidou0922/Maidou
/阶乘.py
421
4.15625
4
b=int(input("pls input number:")) def fact(a): result=1 if a < 0: return("Error") # should be Error elif a == 0 or a==1: return(str(a)) while a > 1: tmp=a*(a-1) result=result*tmp a -=2 return result #return after loop print(fact(b))...
73f05af982732d91004c84a6686e2116e2e1b705
rinkeshsante/ExperimentsBackup
/Python learning-mosh/Python Files/learn_02.py
1,123
4.15625
4
# from the python mega course # to run the entire code remove first ''' pair from code # create text file named test.txt containg multiple lines # file handling opening t& reading the file ''' file = open("test.txt", "r") content = file.readlines() # file.read() for all content reading # file.seek(0) to readjustng th...
a68e5eb7240d51bd2f82fe82c5e47dc461c009ff
cvankerkhove/UNO-Game
/a5_uno.py
11,476
4.0625
4
# a5_uno.py # Chris VanKerkhove cjv47; Omar Rasheed oyr2 # None # 5/9/2018 # skeleton by: # Anthony Poon (ATP65) # Victoria Litvinova (VL242) - simple edits # Lillian Lee (LJL2) - simple edits # April 27, 2018 """ This module contains an implementation of an Uno-like game using standard 52-card playing ca...
f3e4a992c8d98c6c11003855af340a10dafcc1d4
wfsfgedtwwwarfsge/python_programming
/default/default_simple_error.py
547
3.984375
4
def greet(name, msg="Good morning!"): """ This function greets to the person with the provided message. If the message is not provided, it defaults to "Good morning!" """ print("Hello", name + ', ' + msg) greet("Hrishikesh") greet("Shalini", "How do you do?") def greet(msg = "Go...
a002a824207f2f72ffe66f9e213a03201635e7d2
StarlitGhost/ananas
/ananas/default/roll.py
10,291
3.828125
4
import random, string, itertools, traceback from more_itertools import peekable from ananas import PineappleBot, reply, html_strip_tags def peek(gen): return gen.peek() # DICE PARSING # Formats we want to accept: # @roll [#]d#[±#] # @roll #d#d#[±#] # @roll #d#k#[±#] # @roll #x[above] # We also want to accept any ...
e4c11407f315d7ee14c92362ce290ac3665076cc
shanshanya123/test
/string.py
588
4.15625
4
str1="hello world " str2="python hello world " print("str1[0]:",str1[0]) print("str2[0:5]:",str2[0:5]) l=str1.__len__() print("更新字符串:",str1+str2) str3=str1+str2 print(str3) print(str3.find(str2)) print(str3.count('h')) print(str1.capitalize()) print(str1.center(50,'+')) str = "字符串函数"; str_utf8 = str.enco...
17441f294045dce52c852eb4f2ddac632008da91
hugoleonardodev/learning
/python/desafio-010-python.py
211
3.921875
4
#Desafio 010 Python Prof Guanabara #input quanto dinheiro em reais converter para dollar 1=5.65 R$ reais dr=float(input('How much you have in Reais R$:')) dl=float(dr//5.65) print('You can buy $',dl,'Dollars!')
453b82388354e62b2d7e2dedd99d7a5e537d20bf
hugoleonardodev/learning
/python/desafio-008.py
234
4.0625
4
#Desafio 008 Python Prof Guanabara #Create a code where input is a number in meters and return its value in cm and mm n=float(input('Type a number in meters: ')) print(n,'meters are ', n*100, 'centimeters and ', n*1000, 'milimeters')
13c20d216e5ce3f981849248407162e23c6982bf
hugoleonardodev/learning
/python/desafio-011-python.py
292
3.890625
4
#Desafio 011 Python Prof Guanabara #culculate the area of a wall in (m²) and how much paint will need if #each paint liter (L) can paint 2m² of wall h=float(input('Height of the wall in m:')) l=float(input('Length of the wall in m:')) a=(h*l) q=(a//2) print('You will need',q,'L of paint')
09304be381069205c20d79d0dae91d051d06e81c
ppolle/password-locker
/account.py
1,496
3.90625
4
import string import random class Account: ''' Class that generates new instances of accounts/credentials ''' account_list = [] def __init__(self,account_name,email,user_name,number,password): ''' __init__ method that helps us define properties for our objects. ''' self.account_name = account_name se...
757e2d80adfd115322aa1780ddcdea1295311b62
SaiSatwik2226/GFG_30
/5.py
2,188
4.0625
4
""" 1. Spiral Matrix Medium Accuracy: 100.0% Submissions: 231 Points: 4 Given a matrix of size N x M. You have to find the Kth element which will obtain while traversing the matrix spirally starting from the top-left corner of the matrix. Example 1: Input: N = 3, M = 3, K = 4 A[] = {{1, 2, 3}, {4, 5, 6}, ...
a4beb9881f1150c8d43591a1a0bb3d07db85f69b
lahorton/markov-twitter
/LC-markov.py
3,082
3.75
4
"""Generate Markov text from text files.""" from random import choice import sys import twitter import os import string api = twitter.Api(consumer_key=os.environ['TWITTER_CONSUMER_KEY'], consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'], access_token_key=os.environ['TWITTER_ACC...
52a501b0f3dd5482bfc1c9ffc58b3b254b9e50b0
anxmesh/Python-Projects
/Snake Game/With High Score tracking/scoreboard.py
1,239
3.9375
4
# importing the required libraries import turtle as tt # Constants ALIGNMENT = "center" FONT = ("Courier", 24, "normal") # DEfining the Scoreboard class class Scoreboard(tt.Turtle): def __init__(self): super().__init__() self.score = 0 with open("data.txt", mode="r") as data: ...
dbde6e00bdb831ab7d0a117049805243ffa11c1a
anxmesh/Python-Projects
/Quiz Game/quiz_brain.py
933
3.625
4
class QuizBrain: def __init__(self, q_list): self.question_number = 0 self.question_list = q_list self.score = 0 def next_question(self): current_question = self.question_list[self.question_number] self.question_number += 1 user_answer = input(f"Q.{self.question_...
918be7eef84086c5553b6c018757e9f653c2a076
samanyougarg/Linear-Regression
/regression.py
844
3.84375
4
import pandas as pd from sklearn import linear_model import matplotlib.pyplot as plt # read data using pandas # read_fwf - pandas dataframe object dataframe = pd.read_fwf('brain_body.txt') # parse and read both measurements into two seperate variables # brain weight x_values = dataframe[["Brain"]] # body weight y_va...
c6690b93a412d97aae69eec46305724bbc944b01
andbra16/CNC
/F14/ai/Queens.py
425
3.703125
4
def setup(n): board = [] for i in range(n): board.append(["X"] * n) return board def printBoard(board): for row in range(len(board)): for column in range(len(board)): print board[column] print def addQueens(board,x,y): board[x][y] = "Q" def checkRow(board,x,y): for i in range(len(board)): print boar...
d8e793e33c0c7e34e9a663113b968f6619828913
Khushisomani/codes
/27317661.py
163
3.65625
4
# cook your dish here for _ in range(int(input())): a=int(input()) x=200 for i in range(a): print(x,end=" ") x=x+1 print()
f84c6810754b8fe8753379796d44145a44336b1f
Khushisomani/codes
/34665659.py
194
3.765625
4
# cook your dish here for _ in range(int(input())): t=int(input()) if t%2==0: while(t%2==0): t=t//2 count=t//2 else: count=t//2 print(count)
f2a9967a28d1e6fde251ba66a2039274e842e3b0
Khushisomani/codes
/sorted list to bst.py
815
3.796875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # ...
2dd4c16eeadb05beb1f1cc0e44e7c09a2bc3f798
Khushisomani/codes
/29099417.py
125
3.5
4
# cook your dish here import math for _ in range(int(input())): a,b=map(int,input().split()) print((2*math.gcd(a,b)))