blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
429beea2768da60ef01d612ee1f2a6226004f648
izham-sugita/python-attendance
/listallfiles.py
1,046
3.65625
4
#--detect new file and print the name import glob import os def listallsorted(all_files,target): temp = glob.glob(target) temp.sort(key=os.path.getmtime) for i in temp: all_files.append(i) return def latestfile(all_files, filename): filename = max(all_files, key=os.path.getctime) ret...
39b48704923a5d2f6f9f9cccf607638953add7e4
thefactmachine/nltk
/data_camp/chapter_3/chapter_three.py
3,805
3.53125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Aug 20 11:18:43 2017 @author: markhatcher """ # For loop with two variables names = ( "John", "Sal", "Bill" ) ids = ( 123, 321, 231 ) lst_tup = zip(names, ids) # this gives a list of tuples # [('John', 123), ('Sal', 321), ('Bill', 231)] for x, y i...
2bf558d3c7d3569f7aba5867fd5e506d8b91fc93
haoingg/TIL
/conditionLab3.py
176
3.515625
4
import random grade=random.randint(1,6) if ( grade >=1 and grade <4): print(grade,"학년은 저학년입니다.") else: print(grade,"학년은 고학년입니다.")
c733b3717cbc3b24684b8e7cead25bdc86a999a7
snaily16/ud120-projects
/datasets_questions/explore_enron_data.py
2,076
3.5625
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that pers...
f3a4a185e7f367057a144217db90b99e742594f8
szepema/ML_in_practice
/2/linear_reg.py
2,447
4
4
# Original code: https://arato.inf.unideb.hu/ispany.marton/MachineLearning/2021%20fall/basic_linear_regression.py import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # Default parameters n = 1000 # sample size b = 3 # i...
56ef4bda6eaa1776060f91378a84430ad61fff15
RanjanShrivastva/PythonSeleniumAutomation
/PythonPrograms/PythonPrograms/Inheritence/P12_Use OfSuperFunction.py
630
4.3125
4
""" Lecture: 310 parent class members are default available to child class and we can access from child class using child reference But if constructors, variable, methods are same in both parent and child class then super function is used to access or call parent class method, constructor and variables """ class P: ...
7fff2d9b545696cbcd07eb2bb36684708f84e46b
RanjanShrivastva/PythonSeleniumAutomation
/PythonPrograms/PythonPrograms/GeneralProgram/OccureneceOfCharExample.py
215
3.71875
4
user_ip = str(input("provide string to find char occurrence: ")) dict ={} for ch in user_ip: dict[ch] = dict.get(ch, 0)+1 for key, val in sorted(dict.items()): print('{} occurred {} times'.format(key, val))
4b32d218db3e3baa345d0056f4efa6c8b5f618b7
RanjanShrivastva/PythonSeleniumAutomation
/PythonPrograms/PythonPrograms/Inheritence/P13_Access_Particular_Method_Of_super_class.py
636
4.0625
4
class A: def m1(self): print("I am A class m1 method") class B(A): def m1(self): print("I am B class m1 method") class C(B): def m1(self): print("I am C class m1 method") class D(C): def m1(self): print("I am D class m1 method") class E(D): def m1(self): ...
9e586ac1b12f62167d3b129c4ead6370d602ea02
RanjanShrivastva/PythonSeleniumAutomation
/PythonPrograms/PythonPrograms/Inheritence/P05_SingleInheritance.py
234
3.84375
4
""" Single Inheritance = single parent and single child """ class Animal: def m1(self): print("I am parent class") class Dog(Animal): def m2(self): print("I am child class") dog = Dog() dog.m1() dog.m2()
5999533fccf5cd8b0fb84b179b97eb715d4c9c11
RanjanShrivastva/PythonSeleniumAutomation
/PythonPrograms/PythonPrograms/Inheritence/P04_UseOf_IS-A_and_HAS-A_Inheritance.py
1,115
3.828125
4
class Car: def __init__(self, cname, cmodel, ccolor): self.cname = cname self.cmodel = cmodel self.ccolor = ccolor def car_info(self): print("Car name: {} \t\n Car model is: {} \t\n Car color is: {}".format(self.cname, self.cmodel, self.ccolor)) class Person: def __init__(...
11979f7ce1278533fec2a60731c4f4e54fc4a3c7
iskrich/ticket_scrapper
/ts/ticket.py
375
3.6875
4
class Ticket(object): """Object for storing price, time""" def __init__(self, price, start_time, end_time): """ :param price: Price for ticket in EUR :param start_time: start time of route :param end_time: end time of route """ self.price = price self.st...
8b314d794110ad0aa4219e670d3f8224b6286acd
francisconeves97/pri
/1/2-1_1-3.py
350
3.6875
4
# 2.1 - 1.3 import nltk text = '' with open('text.txt') as f: text = f.read() text_array = nltk.word_tokenize(text) word_dict = {} for word in text_array: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 for word in word_dict: print('Word: {}, Occurences: {}'.fo...
5188c03f1a330e4fa788184decdadb00440f68f8
francisconeves97/pri
/2/ex2.py
1,448
3.53125
4
import math from ex1 import file_inverted_index num_docs, inverted_index = file_inverted_index('lusiadas.txt') def term_statistics(term): doc_occurrences, _ = inverted_index[term] doc_occurrences_count = len(doc_occurrences) df = doc_occurrences_count / num_docs max_occ = 0 min_occ = 9999 for doc in...
0473558243b120bc8f8d991b2ef3605b8c2e8fdc
kendricktan/pybp
/main.py
2,830
3.625
4
import sys from pybp.pederson import PedersonCommitment from pybp.rangeproof import RangeProof if len(sys.argv) is not 3: print('python main.py <value to prove> <within 2**x range>') exit(1) value = int(sys.argv[1]) bitlength = int(sys.argv[2]) # Now simulating: the serialized proof passed to the validator...
f51976d5bd024fddd1c09d030953400eb4511a4b
zhou-1/COVISS-Lab-Research
/OpenCV/Python/Gui Features/DrawFunctions/Second.py
899
3.828125
4
import numpy as np import cv2 as cv # Create a black image img = np.zeros((512, 512, 3), np.uint8) # Draw a diagonal blue line with thickness of 5 px # in the middle cv.line(img, (0, 255), (511, 255), (255, 0, 0), 5) # Draw a green rectangle at the top-right corner of image. cv.rectangle(img, (180, 0), (330, 150), (...
f1e63962143c2f371cdd1dc2ec19045cc77d53c1
sajanrav/scripts
/generate_nps_score.py
2,843
3.78125
4
''' Script to generate NPS score. In case the function generate_nps_score() is to be used as a separate module, please remove the main() function. The input file should have two columns: 1. id 2. nps score Definitions: 1. A valid nps score is an integer in the range 0 - 10 2. Promo...
6347e962a1e8276ab4e0e0a96be92afd9d77dfe5
yu-11-22/pandas
/pandas-filter.py
471
3.890625
4
# 載入 pandas 模組 import pandas as pd data=pd.Series([30,15,20]) condition=data>18 filtereData=data[condition] print(filtereData) data=pd.Series(["您好","Python","Pandas"]) condition=data.str.contains("P") filtereData=data[condition] print(filtereData) # 篩選練習 - DataFrame data=pd.DataFrame({ "name":["Amy","Bob","Charle...
f40b3f9ffc511c4c0186024b5d6b7a0464526fdc
lkkouam/Python-Challenge
/PyPoll/main.py
3,491
3.59375
4
# Part 1 import os import csv import collections print ("Election Results") print ("------------------------") # List of file fileNumbers = ['1', '2'] # Loop through files for numToCheck in fileNumbers: # Grab election data CSV electionDataCSV = os.path.join('Resources', 'election_data_' + numToCheck + '.csv...
b79044acba76d799af35342e908a5c32f2523e4b
Romero027/effective-python
/item_6_unpacking.py
740
4.65625
5
# Unpacking allows for assigning multiple values in a single statement item = ('apple', 'banana') a, b = item print(a, 'and', b) # Unpacking can even be used to swap values in place # Python will create an implicit temp value for you x = 1 y = 2 x, y = y, x print('x =', x, 'and y =', y) # It is also useful in for ...
869a42530cfb0d10f6b903c04cbb0272f4ea433d
starkhv/tdd_kata
/day11/test_string_calculator.py
1,104
3.84375
4
import unittest import random from string_calculator import add class TestStringCalculator(unittest.TestCase): def test_add_empty_string_returns_zero_int(self): self.assertEqual(0, add('')) def test_add_single_number_string_returns_same_number_int(self): self.assertEqual(1, add('1')) def ...
b325fa75b2cc11dd0f8adcd0f19c8a0444511401
starkhv/tdd_kata
/day18/string_calculator.py
2,052
4.4375
4
# built-in modules import re def add(numbers_string): """ Add numbers in given string and return sum """ # if numbers_string is not empty if len(numbers_string) > 0: # regex to detect delimiter declaration in numbers_string dd_regex = re.compile(r'//(?P<delimiter>.*)\n(?P<numbers_string>.*)...
c3778e31e64520da31fda81d012884afb913b7df
starkhv/tdd_kata
/day5/string_calculator.py
1,509
4.15625
4
import re def add(numbers_string): if len(numbers_string)>0: # delimiter declaration regex dd_regex = re.compile(r'//(?P<delimiter>.*)\n(?P<numbers_string>.*)') # check if given string matches delimiter declaration regex dd_match = re.match(dd_regex, numbers_string) if dd_ma...
305503b26f584381c96380d148f60c9ca6b3f01a
Siffersari/StackOverflow-lite
/app/tests/v1/test_answers.py
8,995
3.59375
4
import unittest import json from ... import create_app class TestAnswers(unittest.TestCase): """ Contains test cases for the questions """ def setUp(self): """ Initiates the app and varibles to be used when the tests run """ self.app = create_app() self.client...
12eb951e533f5672c7d0d73211f2fb73a8de5eff
tnameera/codepath_intermediate
/week1/multiplwa3and5.py
247
3.890625
4
def multiple(n): sum = 0 for i in range(1,n,1): if (i % 3 == 0): #print(i) sum = sum + i elif( i % 5 == 0): #print(i) sum = sum + i return(sum) print(multiple(1000))
9da760aade3e6b45b0fcba97035cde5e800d732d
tnameera/codepath_intermediate
/week2/tempCodeRunnerFile.py
1,713
3.8125
4
""" Problem 1 - Find a pair with given sum Given an array of size n and a number x, determine the first two elements in the array, if any, whose sum is exactly x. """ def twoSum(nums, target): """ time complex:O(N) for i in range(len(nums)): nums[i] in pairmaps: is O(1) Space complexity: O(N) for pairm...
68fc66a9c71c72ed7a49e40b7cbeef5a53a85aaf
sampathweb/card_games
/__init__.py
1,600
3.796875
4
""" Card Games package: This package acts as the container for various card games. BlackJack: You will be the Player and system acts as the Dealer. ========= The Objective of the game is to get to 21 or close to it without exceeding 21. You are playing solely against the dealer or also called the House. You can draw ...
2d00f03581f672c51cd6bc2bef621bd8db902988
bounty030/Coursera
/Python_for_Everybody_Specialization_UMich/PythonUsingDatabases/week5_DatabasesAndVisualization.py
348
3.5625
4
#Week 5 - Databases and Visualization #--------16.1 - Geocoding #multi-step data analysis #1. Gathering data #2. Cleaning data #3. Analyzing data #4. Visualizing data #-------16.2 - Geocoding Visualization a = 1 b = "1" try: print("positive") c = a+b print("positive") d=a+1 print("positive") e...
5b37a4471322a633d7ad60d4606ad9a5f6aaca7a
bounty030/Coursera
/Crafting_Quality_Code_UniToronto/week5_functions/assignment/a2.py
6,001
4.15625
4
# Do not import any modules. If you do, the tester may reject your submission. # Constants for the contents of the maze. # The visual representation of a wall. WALL = '#' # The visual representation of a hallway. HALL = '.' # The visual representation of a brussels sprout. SPROUT = '@' # Constants for the directio...
14c9bd3b5a5d27a265835e405f0a5132d18adc48
bounty030/Coursera
/Data_Science_Specialization_IBM/Applied_Data_Science_Specialization_IBM/Data_Analysis_with_Python/week3_exploratory_data_analysis/week3_dataAnalysis.py
1,979
3.703125
4
import pandas as pd import matplotlib as plt from matplotlib import pyplot import numpy as np import seaborn as sns from scipy import stats path2 = '/home/tbfk/Documents/VSC/Coursera/Data_Analysis_with_Python/' fn = 'automobileEDA.csv' df = pd.read_csv(path2 + fn) print(df.head(10)) print(df[['bore', 'stroke', 'comp...
c9420b6904e96493cff62ebba9bd41f020dc8cd7
bounty030/Coursera
/Python_for_Everybody_Specialization_UMich/PythonForEverybody/week5_assignment3.2.py
818
4.09375
4
#Exercise 3.2: Rewrite your pay program using try and except so # that yourprogram handles non-numeric input gracefully by # printing a messageand exiting the program. The following # shows two executions of the program: # Enter Hours: 20 # Enter Rate: nine # Error, please enter numeric input # Enter Hours: forty ...
e2a1534ed1822c51b7b88a60b45be3a93a01d469
bounty030/Coursera
/Crafting_Quality_Code_UniToronto/week5_functions/assignment/test_a2.py
6,442
4.0625
4
import unittest import a2 class TestRat(unittest.TestCase): """ Test class for class Rat. """ rat1 = a2.Rat("Tim", 1, 2) rat2 = a2.Rat("Claudia", 3, 4) def test_rat_init(self): """ Test the initialization of two rats. """ self.assertEqual(self.rat1.name, "Ti...
f9125cfc326b3031acc810fae483df3df3b63e8e
bounty030/Coursera
/Python_for_Everybody_Specialization_UMich/PythonAccessWebData/week6_chapter13_assignmentGeoJSON.py
3,266
4.5
4
#week 6 - Assignment #Calling a JSON API #In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. # The program will prompt for a location, contact a web service and retrieve JSON for the web service and # parse that data, and retrieve the first place_id from the ...
67545b7da6cb8c7e0c6e3a79c5261fa331ce1ec2
bounty030/Coursera
/Python_for_Everybody_Specialization_UMich/PythonAccessWebData/week2_chapter11_assignment.py
2,408
4.28125
4
#week 2 - chapter 11 - assignment # Finding Numbers in a Haystack #In this assignment you will read through and parse a file # with text and numbers. You will extract all the numbers # in the file and compute the sum of the numbers. #Data Files #We provide two files for this assignment. One is a sample # file wh...
7a7fd4525046219418bcaf44d9bfa189d30ee72b
bounty030/Coursera
/Python_for_Everybody_Specialization_UMich/PythonForEverybody/week5_conditionalStatements.py
1,071
4.34375
4
#3.1 Conditional Statements #if statements has a condition, if it is true, the indented next # lines will be executed, if it is false the next indented # lines will be skipped. Indenting by 4 spaces, indenting matters! # make sure to turn tabs into spaces, otherwise python will complain!!! #comparison operators: ...
7d3cb9ea1442bab305f27468eb2a9914c71c4f2a
gopalreddy-developer/-python-boot-camp
/day 12.py
450
3.71875
4
# creating file and writing text into it with open("30 days 30 hours.txt","w") as f: f.write("i have completed 10 days successfully\n") print("process completed") # opening file and adding text to it f = open("30 days 30 hours.txt","a") f.write("gopal reddy\n") print("adding completed") f....
41ac355babfede59ddbcb160e4ef1c9cb4f79f3f
gopalreddy-developer/-python-boot-camp
/day 7.py
639
4.15625
4
# 1.creating a function and retuing calc def calc(x,y): add = x+y sub = x-y mul = x*y div = x/y print("the sum is",add) print("the diference is:",sub) print("the multiplication is",mul) print("the division is ",div) x = int(input("enter first value")) y = int(input("ente...
6c370625848a7e589b69e7555c741710e5320615
Linet17/PythonRepo1
/functions.py
1,900
4.3125
4
# # functions are a group of related statements that perfom a specific task # # uses keyword def # # syntax -> def functionName(): # # statements # # exapmle 1 # def helloWorld(): # print("Hello world") # # # helloWorld() # to use a function,you need to call it # # # # example 2 # def add_two_numbers(): # pass...
3fb9807253e6aadac94ec84602372aee2c6e395d
popovbodya/projects
/python/PyhonEdu/Strings.py
2,784
4.0625
4
# Изучение Strings # Combining two strings using the + symbol is called concatenation. hello = "Hello" world = 'World' hello_world = hello + " " + world # Python supports a string-by-number multiplication (but not the other # way around!). hello = "hello" ten_of_hellos = hello * 10 ...
4567c41d8d22731322d7d603e465262e1a1f38d8
apollopower/interview-prep
/python/python_questions/deepest_node.py
651
3.96875
4
# Given the root of a binary tree, return its deepest node class TreeNode(): def __init__(self, val): self.val = val self.left = None self.right = None def add_node(root, val): if root is None: return TreeNode(val) elif val < root.val: root.left = add_node(root.lef...
061d9fea4121d39b9d469ae34dda5eed8a431a5d
apollopower/interview-prep
/python/python_questions/graph_coloring.py
680
3.984375
4
# Write a function to color all nodes in an undirected graph. No two # neighbor nodes should have the same color class GraphNode: def __init__(self, val): self.val = val self.neighbors = set() self.color = None def color_graph(graph_node, colors): graph_queue = [] graph_queue.append(graph_node) ...
fffc3035e73e3209978973ff7a5e9f1ef8961c5b
apollopower/interview-prep
/python/python_questions/palindrome_permutation.py
681
4.1875
4
# Write a function that checks if a given string is a # permutation of a palindrome. # Do this in O(n) time # ANSWER # By using an "unordered set", we can keep track of letter pairs. # Palindromes will always have letters paired, with sometimes the # exeption of one letter. # Space time complexity: # Time => O(...
b38e14562b5fce139691aea37417420a94b78c7c
apollopower/interview-prep
/interview_questions/stock_prices/solution.py
939
3.890625
4
# Write an efficient function that takes stock_prices and returns the # best profit I could have made from one purchase and one sale of one # share of stock yesterday. # stock_prices = [10, 7, 5, 8, 11, 9] # get_max_profit(stock_prices) # Returns 6 (buying for $5 and selling for $11) # SOLUTION def get_max_profit(s...
c7f00b8d713785345579872053aa9ca370f861b2
apollopower/interview-prep
/interview_questions/top_scores/solution.py
766
3.859375
4
# Write a function that takes: # 1) A list of unsorted scores # 3) The highest possible score in the game # And returns a sorted list of scores in O(N) time unsorted_scores = [37, 89, 41, 65, 91, 53] highest_possible_score = 100 # Should return [91, 89, 65, 53, 41, 37] # SOLUTION def sort_scores(unsorted_scores, ...
2bdeac362fae8bde551a37fc5337279a7b07ca6c
apollopower/interview-prep
/python/python_datastructures_algorithms/binary_tree_traversals.py
1,359
4
4
from queue import Queue class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def add_node(root, val): if not root: return TreeNode(val) elif val < root.val: root.left = add_node(root.left, val) else: root.right = add_node(root.right, val) ...
3571072c1cb2545b72faeb305a02d56db454ddfe
apollopower/interview-prep
/python/python_questions/binary_tree_level_sum.py
3,184
4.125
4
# Write a function that returns the sum of values of nodes at a given depth # for a binary tree, where 0 would be the root, and each level after # increments by 1: class TreeNode(): def __init__(self, val): self.val = val self.children = set() def add_node(self, val): self.childre...
50ed4f2ad3f71fa8f105a154859d2af69f23483d
apollopower/interview-prep
/python/python_questions/tree_num_of_nodes.py
1,078
4.09375
4
# Return the count of nodes in a binary tree: class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def add_tree_node(root, val): if not root: return TreeNode(val) elif val < root.val: root.left = add_tree_node(root.left, val) ...
f1183187ef6df7e57a9437a8dfe8534e74b80cf5
Anthonina/lesson1
/training_while_loop_2.py
474
3.671875
4
def get_answer(question): if question == 'Как дела?': answer = 'Хорошо' elif question == 'Что делаешь?': answer = 'Занимаюсь' else: answer = 'Не понимаю вопрос' return answer def ask_user(): while True: question = input('Введите вопрос: ') if question == ...
8171cf09324548c1d2518a5974b5694e153b771f
slimdim/edu-python-basics
/hw_8/lesson8_1.py
1,695
3.78125
4
# Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». # В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, месяц, год и # преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен п...
5a90dd9171a9bedc0ca59b9d8fa17c3a461a2c9a
slimdim/edu-python-basics
/hw_2/lesson2_3.py
1,103
4.03125
4
# Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года # относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. user_month = int(input('Введите номер месяца (от 1 до 12): ')) while user_month < 1 or user_month > 12: user_month = int(input('Кажется,...
94f6c25acb451c3c21356e3c9f1121694f44dae1
paulBit3/awesome-python
/python_projects/games/rps_game.py
2,967
4.25
4
import random, sys """Rock, Paper, Scissors game""" print('ROCK, PAPER, SCISSORS') # Track th number of wins wins = 0 losses = 0 ties = 0 while True: # The main game loop print("%s Wins, %s Losses, %s Ties" % (wins, losses, ties)) while True: # player input loop print("Enter your move: (r)ock (p)ap...
89540be81e47d076aa341ad5f015a4202c041622
SirCodesABunch/210CT-CourseWork
/210CT-CourseWork-Final/Week 4 Task 1 Binary Search.py
774
3.90625
4
import math L = [2,3,5,7,9,13] left = 0 right = int(len(L) -1) min1 = int(input("Enter a Left Number: ")) max1 = int(input("Enter a Right Number: ")) def binarySearch(L, left, right,min1,max1): #print("run") #print (half) mid = (left+right)//2 print(mid) if L[mid] == min1: ...
82c62e73fb491c7337d88e048d645c9cb5047759
SirCodesABunch/210CT-CourseWork
/210CT-CourseWork-Final/Week 7 Task 2 Graph DFS BFS.py
3,066
3.796875
4
from queue import * class Node(): def __init__(self,value): self.value = value self.edges = [] def get_edges(self): return self.edges def update_Edges(self,G,X): self.edges.append([X,G]) def get_value(self): return self.value class Graph(): ...
14a94f5f0814d61010ead9d95f7afd3cd206d60f
harrysandhu/dalgo
/prac/Graph/graph/lab8/graph.py
1,373
3.671875
4
import sys import os class Graph: def __init__(self, v, directed=True): self.directed = directed self.nvertices = v self.nedges = v self.edges = [[0 for i in range(v)] for i in range(v)] self.degree = [0 for i in range(v)] def read_graph(self, filename): ...
0927529c0aa2c09b268cedb72b522aebdda57273
harrysandhu/dalgo
/prac/cycleLength.py
904
3.515625
4
def cycleLen(n): c = 1 while n != 1: if n % 2 != 0: n = 3* n + 1 else: n /= 2 c += 1 return c def cyc(n): if n == 1: return 1 elif n % 2 != 0: return 1 + cyc( 3*n+1) return 1 + cyc(n/2) def maxCycleLength(i, j): prevals = {...
ce5632023fb8042c9b3e489b2b14b692cbda6893
Lukin559/pythonlessons
/1lesson/cait.py
248
4
4
num1 = input("Введите число 1: ") num2 = input("Введите число 2: ") print(num1 + num2) command = input("Введите число: ") if command == "+" : print(num1 + num2) elif command == "*" : print(num1 + num2)
e9481effe8f0a1b422268cb0cfdf30aef571fa5d
nostalgialee/treasure-
/practice.py
577
3.75
4
# -*- coding:utf-8 -*- # @Time : 2022/6/21 21:37 # @File : practice.py # Author: lee # 循环一个列表 li = [1,2,3,43,] def generation(li): yield from li # # for i in generation(li): # print(i) # 编写一个生成器, # 将一个二维的列表转化为一维的列表。 li2 = [ [1,2,3], [4,5,6], [7,8,9] ] ...
e917fe7dd0bf0e3133356b5dda2851e65de168b0
EdanSneh/Search-Engine
/csvformat.py
995
3.90625
4
import csv #gives coords of school def locatecoords(school): return { "Stanford" : [0,0], "Harvard" : [1,2], "UCLA" : [5,6] }.get(school,"null") #checks if schools are in list def checklist(school, list): counter = 0 for i in list: if i.keys()[0] == school: return counter counter+=1 return -1 ...
3325ca71e801ea032dd538b4d7740c3178d0e6c9
AymanMagdy/hands-on-python
/lists/sum_list.py
384
4.125
4
# Write a simple fucntion that takes a list and sum all the elements in the list. # The function to sum the list. def sumList(listElemets): sum = 0 for element in listElemets: sum += element return sum # The main function. if __name__ == "__main__": listValues = [1, 2, 3] sumResult = sumLis...
40912bd1dbfa29547181b250b3ba5d133ecb20fa
AymanMagdy/hands-on-python
/lists/rm_even_numbers.py
352
4
4
# Write a func that remove the even numbers from a list def rmEvenNumbers(listElements): evenNumbers = [] for element in listElements: if element %2 != 0: evenNumbers.append(element) return evenNumbers if __name__ == "__main__": listSample = [1, 3, 5, 8, 10] result = rmEvenNumbe...
5c8524b3aeb1003b2f1245b3e7b2e56d8c456771
AymanMagdy/hands-on-python
/Sets/loop_set.py
255
3.671875
4
# Write a func that would iterate over sets def loop_sets(set_items): for item in set_items: print("Item: {}".format(item)) return set_items if __name__ == "__main__": sample_set = {1, 3, 4, 7} loop_result = loop_sets(sample_set)
afc537f88d1c3347c8f3f3e407d1337f0638d635
AymanMagdy/hands-on-python
/tuples/conv_tuple_srting.py
352
3.9375
4
# Write a func to covnert tuple to string def convTupleToString(tupleSample): try: return ''.join(tupleSample) except: return "Error with the conversion.\nCheck the tuple's element." if __name__ == "__main__": firstTuple = ('ay', 'man' ) concatenatedTuples = convTupleToString(firstTupl...
4dfe4bed61cc5e264654db35bb8aed55f95504e7
AymanMagdy/hands-on-python
/Sets/min_max.py
584
4.21875
4
# Write a func that returns min and max elements of a set def min_max(given_set): min = next(iter(given_set)) max = next(iter(given_set)) # Getting the min value. for element in given_set: if element < min: min = element # Getting the max value. for element in given_set: ...
5a19d22beb29394180572efd0c601664d62a23d0
AymanMagdy/hands-on-python
/tuples/concate_tuples.py
307
4.125
4
# Write a function to concate 2 tuples. def concateTuples(firstTuple, secondTuple): return firstTuple + secondTuple if __name__ == "__main__": firstTuple = ('ayman', 45 ) secondTuple = ('Ahmed', 15 ) concatenatedTuples = concateTuples(firstTuple, secondTuple) print(concatenatedTuples)
03f583da16adfaf157e628f1e172a161e39f3bca
Mini-Proyectos/laboratorio1-miguel
/TestBusquedaBinaria.py
823
3.59375
4
#Se importan las funciones que se usaran from Busquedas import LecturaDeDatos from Busquedas import BusquedaBinaria from Busquedas import Ordenan arreglo=LecturaDeDatos(input("Ingrese el nombre del archivo: ")) #Se carga el arreglo desde el archivo que ingrese el usuario e = int(input("Ingrese el elemento a buscar: ")...
7ef81ba87986b6f1b9f684e28d1d2577cd0662db
epsalt/aoc2017
/day01/day1.py
613
3.515625
4
from collections import deque ## Part 1 def captcha(n): string = list(str(n)) deq = deque(string) deq.append(deq.popleft()) pairs = zip(string, deq) total = 0 for pair in pairs: i, j = map(int, pair) if i == j: total = total + i return(total) ## Part 2 def cap...
1455a9b607d282a41e2876b427ba89da558a0568
epsalt/aoc2017
/day11/day11.py
1,102
3.75
4
# Thanks to https://www.redblobgames.com/grids/hexagons/ class Cube: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def move(self, direction): dir_map = {'n' : Cube( 0, 1, -1), 'ne': Cube( 1, 0, -1), 'se': Cube( 1, -1, 0),...
8277a8503737396966225e40842618061fe5d066
alessandropaticchio/Fake-News-Detector
/models.py
730
3.515625
4
import torch class Network(torch.nn.Module): def __init__(self, activation=None, input=1, layers=2, hidden=50, output=2): super(Network, self).__init__() if activation is None: self.activation = torch.nn.Sigmoid() else: self.activation = activation self.fca ...
05815d7f9de61a1e17121ea525d4f55c722434f3
rathoddilip/DataStructurePython
/List_Programs/difference_between_lists.py
620
4.0625
4
class Difference: def __init__(self): self.list1 = list1 self.list2 = list2 self.list_differcence = [] def difference_of_two_list(self, list_differcence): """ getting the difference between two lists """ for elements in list1: if elem...
f3924ccbfe36effcf8b4a5acea15008e235f4e00
AParashar/Python
/area_circle.py
351
4.03125
4
import math input_status = True while input_status: try: radius = int(input("Please enter Radius: ")) input_status = False except: print("Invalid Entry. Try again!") input_status = True def calculate_area(): return math.pi * radius * radius print("Area of the circle is: "...
d55487be74beda44d875b488be6d0cb6684a7e72
AParashar/Python
/user-auth.py
837
3.921875
4
def prompt_user(): user_name = input("Enter user name to check: ") password = input("Enter password: ") return user_name, password def check_user(lists, user, password): for index, element in enumerate(lists): if(element.split()[0] == user and element.split()[1] == password): return...
09d7ae3091c082016c5c8f6c960bef140402c701
MasterLeg/LinesVisualizer
/utils/auxiliary_methods.py
2,673
4.1875
4
from datetime import datetime def transform_valuetodate_to_date(excel_date): """ Transform from an Excel only understandable values to ISO date format The 44081 are the days far from 1st January 1900. The 0.627417 is the % from completing the day. Where 00:00h is 0% Example: 44081.627417 is in fac...
0b5e19f24d9261ee891c72492035fe3a23b046c8
GasserMarc/Doctolib
/MVP2/tout_MVP2.py
9,772
3.671875
4
''' Cette fonction renvoie la proportion de texte dupliqué ''' ''' Ces fonctions indiquent la pertinence du nom des variables, si elles sont explicites ou si elles ne commencent pas par une majuscule (convention) ''' def listes_de_variables(code_candidat): ''' Donne la liste et le nombre des variables util...
620f2f14e005842fd66c6dd1d607def09b01fe6e
fearlessfreap24/pcap
/classes/weedayerror.py
1,017
3.859375
4
class WeekDayError(Exception): pass class Weeker: __days = { 'Sun' : 0, 'Mon' : 1, 'Tue': 2, 'Wed': 3, 'Thu': 4, 'Fri': 5, 'Sat': 6 } def __init__(self, day): if day in Weeker.__days: self.__today ...
3626c272a2840c15ffad0b359b71ad09df1d0faa
fearlessfreap24/pcap
/classes/classPlay.py
1,323
3.875
4
class Stack: def __init__(self) -> None: self.__Stack_List = [] self.__top = None def push(self, val): self.__Stack_List.append(val) self.__top = val def pop(self): val = self.__Stack_List[-1] del self.__Stack_List[-1] if len(self.__Stack...
d371d3881a32a6c83a06f92aa036f3053021c8de
PanosRCng/just_war
/justwar/data/Graph.py
2,150
3.984375
4
######################## # a simple graph module ######################## # graph class class Graph(): def __init__(self): self.graph = {} # returns a list with all the edges of a given node def getEdges(self, node): edges = [] for pair_node in self.getNodes(node): edges.append( Edge(node, pair_...
4a78b8a27ce7cd2b30e297f9bafc3cb6fb50d88a
MichaelBieniek/python_training
/basics.py
1,515
3.953125
4
#https://app.pluralsight.com/player?course=python-getting-started&author=bo-milanovich&name=python-getting-started-m2&clip=0&mode=live # Python - no typing answer = 42 pi = 3.14 print(int(answer + pi)) """comment""" 'comment' "comment" # def add_numbers(a, b) # print(a + b) # add_numbers(5, 5) # print("{0} and ...
3c05e310f277432a05728ecabb54273ddee22c38
meda123/Hackerrank_Challenges
/Python/strings/stringFormatting.py
594
4.15625
4
# https://www.hackerrank.com/challenges/python-string-formatting/problem ''' INPUT: A single integer denoting n OUTPUT: Print n lines where each line i contains the respective decimal, octal, capitalized hexadecimal, and binary values for i. Each printed value must be formatted to the width of the binary value n. ''...
8f5a3652dc958a82deec65648d24e8775d3c74ad
meda123/Hackerrank_Challenges
/Python/basicTypes/listComprehension.py
711
4.15625
4
# HR: https://www.hackerrank.com/challenges/list-comprehensions/problem ''' Sample Input: 1 1 1 2 Sample Output: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] Cocenpt: List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one Explantion: Y...
856ece724964cb36230c9248a98c71fbec0b7572
jacksonhenry3/CDT
/cdtea/visualization/coordinates.py
6,940
3.65625
4
import numpy as np from math import pi from cdtea import event import math """ a coordinate function is one that takes in a spacetime and outputs a dictionairy with node indices as keys and coordinate tuples as values. """ # utility functions # finds the minimum angular distance beween two given angles def angular_s...
810e6b9ee50ea61aba19da3a2ea6cf9ce52267b1
XuTan/PAT
/Advanced/1050.String Subtraction.py
991
3.609375
4
""" 1050. String Subtraction (20) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1 - S2 for any given strings. However, it might not be tha...
a9c3b5e0bd6ef8b691bf87a1bffd3c74df05283c
XuTan/PAT
/Advanced/1116.Come on,Let's C.py
2,473
3.890625
4
""" 1116. Come on! Let's C (20) 时间限制 200 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue "Let's C" is a popular and fun programming contest hosted by the College of Computer Science and Technology, Zhejiang University. Since the idea of the contest is for fun, the award rules are funny as the following: 0. T...
63737de409ec72fe21951b89c0fa15b47743d4c3
XuTan/PAT
/Advanced/1010.Radix.py
2,604
3.9375
4
""" 1010. Radix (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number. Now for any pair of positive integers N1 and N2, your task is t...
882d3474a3877549effdd4a04d3abb9d56e66465
XuTan/PAT
/Advanced/1113.Integer Set Partition.py
1,509
3.6875
4
""" 1113. Integer Set Partition (25) 时间限制 150 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given a set of N (> 1) positive integers, you are supposed to partition them into two disjoint sets A1 and A2 of n1 and n2 numbers, respectively. Let S1 and S2 denote the sums of all the numbers in A1 and A2, respec...
f5405fee8fc835c8953d8e5505a190c5f5f1a46e
thinksource/GarvanInstitute
/insertionSort.py
441
4.03125
4
size=int(input()) str_arr = input().split(' ') Arr=[int(num) for num in str_arr] def myprint(arr): ps="" for i in arr: ps+=str(i)+" " print(ps[:-1]) def insertionSort(arr): size=len(arr) p=arr[size-1] for i in range(size-2, -2,-1): if arr[i]>p and i>=0: arr[i+1]=arr[...
de3a64f965f8a353f3b4796ed23ff69816593941
lewislwb/workshop
/leetcode2.py
931
3.71875
4
# Definition for singly-linked list. #class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): if l1 is None: return l2 if l2 is None: return l1 num1=0 num2=0 ...
ec193acbd50a89f8193dcc5a1466bcf4bc2a5a2d
spudtrooper/fugaziliveserives
/genHtml.py
1,853
3.5625
4
import fileinput, sys """ Reads from STDIN and outputs HTML. Input is in the form: <fileName>|<title>|<song-1>|...|<song-2> And should be created from fugaziLiveSongs.py """ def main(argv): songs = [] titles = [] titles2fileNames = {} titles2songs = {} for line in fileinput.input(): li...
7aba6cbd941a3f2c686605956ef9b981673cdd0f
Tuzexin/computationalphysics_N2013301020142
/Chapter2/velocity adjust.py
1,793
3.5
4
import numpy as np import math # define a function which takes the y, velocity, wind, and angle as input, then give you the x def get_x(y0,velo,angle,vwind): # initialize x=[0.0] y=[0.0] vx=[float(velo)*float(np.cos(angle))] vy=[float(velo)*float(np.sin(angle))] v=[float(velo)] ...
5899412b40271df743d5cc238b34c69703858610
Tuzexin/computationalphysics_N2013301020142
/Interesting-Programs/21点游戏.py
2,634
3.953125
4
from random import shuffle #initialize the cards and groups Table = {'Ace':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10} group_player=[] group_computer=[] #define two decks and card groups for player and computer Deck_player=['Ace','2','3','4','5','6...
df5c02a62303fd779680dcb29ac40605b6069254
fabrilopez/Python
/BFS.py
1,758
4
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 26 20:02:04 2018 @author: Fabricio Breadth First Search for a graph # This code is contributed by Neelam Yadav https://www.geeksforgeeks.or """ from collections import defaultdict class Graph: #construsctor def __init__(self): #dicciona...
61c0a398db7c830d388a1233ee45e282df836f43
fabrilopez/Python
/dict_counter.py
550
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 3 20:00:01 2018 @author: Fabricio """ ''' dictionary creation whith counter json ''' from collections import Counter sentence='Pablito clavo un clavito que clavito clavo palblito' ''' Peter Piper picked a peck of pickled peppers A peck of pickledpeppe...
eea8c082fbf7863baeeb790b5c607e6d4121bfb2
JacksonTolliday/Cryptography
/cryptography.py
2,774
3.609375
4
""" cryptography.py Author: Jackson Tolliday Credit: https://stackoverflow.com/questions/4978787/how-to-split-a-string-into-array-of-characters, https://stackoverflow.com/questions/31175223/append-a-tuple-to-a-list-whats-the-difference-between-two-ways, https://stackoverflow.com/questions/5618878/how-to-convert-list-to...
bfe0555eb1f8c2c7901e1883838081444727ac27
SensibilityTestbed/indoor-localization
/gyro_step_online.r2py
6,231
3.6875
4
""" <Program Name> pedometer.r2py <Purpose> This is a script for walking step counter. Analysis of the sensor data from accelerometer to detect the walking / running steps. Introducing pre-calibration stage, noise level threshold and moving average filter to accurate step detection for difference devices. ...
0c935cb7783db04260737268f0ede49770e710c8
karuna7/python-pratice-
/my_square.py
256
4.125
4
def my_square(x): """ takes a value and returns the squared value. <<<<<<< HEAD """ return (x**4) print(my_square(2)) ======= uses the ** operator """ return (x**2) print(my_square(3)) >>>>>>> 20f18992c4773b8f1a5e10435bee7b42cb893560
f6d345fbceb934e089d39fe942851e81215c5031
vesso8/Comprehensions
/10. Matrix Modification.py
669
3.921875
4
def is_valid(r,c): if 0 > r or 0 > c or r > (len(matrix)-1) or c > (len(matrix)-1): return False return True matrix = [[int(el) for el in input().split()]for _ in range(int(input()))] command = input() while not command == "END": command_type, row , col , value = command.split() row , col , va...
a30812b055fb992086e919267f85b33f84a28057
vesso8/Comprehensions
/03. Even Matrix.py
268
3.828125
4
def even_nums(number): if number % 2 == 0: return True return False n = int(input()) matrix = [[int(el) for el in input().split(", ")]for _ in range(n)] even_matrix = [[num for num in sublist if even_nums(num)] for sublist in matrix] print(even_matrix)
508537c81a798d54e87dc90a721dd9ce5c841f99
sangsura/linear-regression
/gianha.py
1,044
3.53125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('data_linear.csv').values N = data.shape[0] x = data[:, 0].reshape(-1, 1) y = data[:, 1].reshape(-1, 1) plt.scatter(x, y) plt.xlabel('mét vuông') plt.ylabel('giá') x = np.hstack((np.ones((N, 1)), x)) w = np.array([0.,1.]).resh...
c37a96e579452572bda087fe9c6012912209c32f
javedmughal-058/python_basic
/if else in python.py
264
4
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 15 18:03:45 2021 @author: Muhammad Javed """ # if else statement in Python a=10 b=12 if a>b: print("A is greater") else: print("b is greater") #keep in mind the proper indenting.
0db1509801be0d7c5f36e9235155012276657208
AxeKosCode/LearnPython
/lesson1/3.py
121
3.78125
4
d = {'city': 'Москва', 'temperature': '20'} print(d['city']) d['temperature'] = int(d['temperature']) - 5 print(d)
b3446fa93ad55b94ea786653a157e0d441237cce
khampton353/python-orrery
/buildorbit.py
10,071
3.578125
4
''' buildorbit.py A utility that parses a planetary ephemeris file for orbit data and creates a binary file for use by the planets.py. It understands the JPL Horizons Jul 31, 2013 'Vector' format. It reads the file once to determine points closest/farthest from the sun in order to choose an orbit, and...
3a65da9018b708fb759ceb2b9668d8a88cd7fa4b
Adama1997/TP_Python_M_NIANG
/adama_exo11.PY
322
3.625
4
import random n = random.randint(1,100) nbr_tenter=48 i=1 while (nbr_tenter > 0): nbr_tenter-=1 var=int(input("entrer un nombre: ")) if var < n: print("c'est petit hein......") elif var > n: print("plus grand quand meme.... ") else: print("t'as gagné wei.......") ...