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
44984d1ba51aa457a883a2e1429d5dae58705132
Timur597/First6team
/6/Tema5(Tuple,List)/1.t_12.py
272
3.625
4
1 Задание list = [ (10,1,14.5, "Timur"), (3,4,1.3, 'Newyear'), ("Good", 5, 3.431, 999),(341, "cool", 12.3, "job"), ("4", 63, 91) ] print (len (list) ) 2 Метод a = (1,2,3,4,5) a1 = (2,34,56,7) a3 = (5,3,5,78,3) a4 = (1,23,46,7,8) lis = [a,a1,a3,a4] print (lis)
aa579e52c724f8f7627daccb63ef2832d4d92baa
Timur597/First6team
/6/Tema1(HelloPython)/2.p_1.py
379
3.859375
4
#1 Метод # a = 17925 # b = 34**2 # c = 26*3 # d = 17*33 # f = 4394*4 # print (a >= b) # print (a >= c) # print (a <= d) # print (a >= f) #2 Метод a = 17925 b = 34**2 c = 26*3 d = 17*33 f = 4394*4 if b >= a: print ('b >= a') if c >= a: print ('c >= a') if d >= a: print ('d >= a') if f >= a: print ('f >= a') el...
714037c4fb9d9ddc02677c876b518057b4b3c0ed
N1kken/PythonProjects
/PythonPodstawy/list2.py
344
3.765625
4
#filter(funkcja, sekwencja) zwraca sekwencje (tego samego typu, gdy to możliwe) #zawierającą te elementy z listy wejściowej, dla których wywołanie funkcja(element) #zwróci wartość prawdziwą. Oto przykład obliczania liczb pierwszych: def f(x): return x % 2 != 0 and x % 3 != 0 x = list(filter(f, range(2,100)...
14e5b26ac617c4e2f871fd162b8c07d64132ce9f
koltpython/python-slides
/Lecture7/lecture-examples/lecture7-1.py
828
4.34375
4
# Free Association Game clues = ('rain', 'cake', 'glass', 'flower', 'napkin') # Let's play a game. Give the user these words one by one and ask them to give you the first word that comes to their mind. # Store these words together in a dictionary, where the keys are the clues and the values are the words that the us...
ec9a757fbf7807641a17c4f4eb73feab391f8033
koltpython/python-slides
/Lecture3/code-examples/branching_example.py
238
4.15625
4
operation = int(input()) num1 = int(input()) num2 = int(input()) if operation == 1: sum_two_numbers(num1, num2) elif operation == 2: multiply_two_numbers(num1, num2) else: divide_two_numbers(num1, num2) print('I am here')
99cf48eac5a7288bf9c6add0c945bc9fbe2fc5df
olivaa/TIA-Master
/Geneticos/read_data.py
947
3.59375
4
import os import sys def read_data(filename): dic_city={} with open(filename) as f: lineas=f.readlines() for i in range(1,len(lineas)-1): if lineas[i].rstrip() == 'EOF': break city=lineas[i].split(' ') try: val = int(city[0]) ...
ae32c68b7256baeedd173220e068b5d149166fa8
tarkadaal/AoC2017
/day-6/6.py
946
3.859375
4
#!/usr/bin/python def _redistribute(banks): index = banks.index(max(banks)) to_redistribute = banks[index] banks[index] = 0 while to_redistribute > 0: index = (index + 1) % len(banks) banks[index] += 1 to_redistribute -= 1 def redistribute(banks): seen = set() seen...
b11051af998d84ad6c1ea90b94f886b34089f237
umousesonic/zinc
/xmlreader.py
971
3.53125
4
import xml.etree.ElementTree as et import os class Reader: def __init__(self, path, filename): # change working directory os.chdir(path) # parse xml file into a tree tree = et.parse(filename) # get the root of the tree self._root = tree.getroot() def getQuestion...
a746fe34c81ab0b257425cefd6e8370ade7bc282
xFobz/Python-Exercises
/Exercise_1.py
476
4.03125
4
name = input("What is your name? ") age = input("How old are you? "); age = int(age) cent = 2017 - age + 100 line = ('Hi %s, you are %s which means you will turn 100 in %s' % (name, age, cent)) print (line) repeat = input("Would you like to print that line again? Y/N: ") if repeat == 'Y' or repeat == 'y': t...
41137efc71af93fd406de5d9fe81895b66dda0db
JulianTrummer/le-ar-n
/code/01_python_basics/examples/05_classes/ex5_class_properties.py
560
3.859375
4
import random import math # Rectangle class class Rectangle(): def __init__(self, length, width): self.length = length self.width = width # Classmethod, creates a class from a class function @classmethod def as_square(cls, length): return cls(length=length, width=length...
8013c5a1d5760cd65eca1c8c3c009003dc53b8a3
JulianTrummer/le-ar-n
/code/01_python_basics/examples/02_lists_tuples_dictionaries/ex4_tuples.py
333
4.34375
4
"""Tuple datatypes""" # A tuple is similar to a list, however the sequence is immutable. # This means, they can not be changed or added to. my_tuple_1 = (1, 2, 3) print(my_tuple_1, type(my_tuple_1)) print(len(my_tuple_1)) my_tuple_2 = tuple(("hello", "goodbye")) print(my_tuple_2[0]) print(my_tuple_2[-1]) print(my_...
483d8c2a95519c1e81242ec1420e7b80640595bc
JulianTrummer/le-ar-n
/code/01_python_basics/examples/05_classes/ex1_class_intro.py
606
4.25
4
# Classes introduction # Class definition class Vehicle(): # Initiation function (always executed when the class object is being initiated) def __init__(self, colour, nb_wheels, name): self.colour = colour self.nb_wheels = nb_wheels self.name = name # Creating objects from class vehicl...
44712e0fbd75dd14e249a32416a4d47a55df1280
JulianTrummer/le-ar-n
/code/01_python_basics/examples/01_datatypes_operators_conditionals/ex4_arithmetic_operators.py
315
4.15625
4
"""Arithmetic Operators""" # using values: a = 10 b = 5.5 c = 3 # Addition and Subtraction d = a + c e = d - b print(d) print(e) # Multiplication and Division f = c / 10 + b * 5 print(f) # Exponentation f_square = f**2 print(f_square) # Modulus f_modulus_2 = f_square % 2 print(f_modulus_2) print(f_square % 3)
1d7659b09b39394fbc031fe4799a21530d5cf8f1
jarrettdunne/coding-problems
/daily/problem1.py
1,077
4.21875
4
import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): ''' input: [1, 2, 3] ...
68b9dc0b1217d0659d4c0478479b1ae2e6edb104
mhladnik/DataInDictionary
/main.py
1,318
3.84375
4
import random import json import datetime secret = random.randint(1, 30) attempts = 0 wrong_guesses = list() with open("score_list.json", "r") as score_file: score_list = json.loads(score_file.read()) print("Top scores: " + str(score_list)) #sort lists in dictionary by number of attempts print((sorted(score...
e296f6833d75f7cec9e9ad333f506aa908932824
Halal375657/Data-Structure
/Linked_list/Doubly linked list.py
2,383
3.8125
4
#Doubly Linked List. #Time for Result() method is O(n). #Time for append() method is O(n). #Time for prepend() method is O(1). #Time for search() method is O(n).But it's for wrost case. #Time for remove() method is O(n).But it's for wrost case. class Node: def __init__(self, data=None, prev=None, next=None): ...
6a14a3c185dfc6e9b5e927386839489ad0d6f7e5
Halal375657/Data-Structure
/Disjoint_set/Disjoint_set_1.py
953
3.640625
4
# makeset() Time: O(1) # union() Time: O(1) # find() Time: O(n)-worst case. class Disjoin(object): def __init__(self, n): self.parent = [None] * (n+1) for i in range(1, n+1): self.makeset(i) def makeset(self, n): self.parent[n] = n # Assaign n as a parent of t...
8cbda08ff979592fa08fff3cd7ee91d0cd06603a
slowback/myproject
/main.py
1,302
3.578125
4
import argparse morse_code = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--'...
83acd0fc80d137a62d8fdab8421e6ed03ceea2e0
nihawhp/basic-python-b7-b
/Soal-3.py
438
3.921875
4
teori = float(input("Masukkan nilai ujian teori : ")) praktek = float(input("Masukkan nilai ujian praktek : ")) if teori >= 7.0 and praktek >= 7.0: print("SELAMAT ANDA LULUS!") elif praktek <= 7.0 and teori >= 7.0: print("Anda harus mengulang ujian praktek.") elif teori <= 7.0 and praktek >= 7.0: ...
b60b99b7e68eb6d45407b3bd05cb08bae15f5525
jakewhite5/ice-cream-and-freezers
/ice_cream_categories.py
1,203
3.578125
4
# """ # Interesting idea to use Enums and map status of icecream to value to then compare, # Enum Class doc seems to indicate it's not the right tool for this, but worth exploring # A foot note to comeback for later follows: # """ # # from enum import Enum # # class Chocolate(Enum): # # WATERY = 0 # # WATERY ...
e2059b57492aa8e01d426ec9c9d05f48c45c9f7a
Melvynkoh94/FYP_RealTime_EmotionDetection
/python/tkinter_test.py
258
3.515625
4
import tkinter as tk import datetime def set_label(): currentTime = datetime.datetime.now() label['text'] = currentTime root.after(1, set_label) root = tk.Tk() label = tk.Label(root, text="placeholder") label.pack() set_label() root.mainloop()
eb7bc39f59c1d5ed19f206a85ccec13c4a6a7e00
winniewjeng/StockDatabase
/Example.py
2,330
4.40625
4
#! /usr/bin/env python3 """ File: Jeng_Winnie_Lab1.py Author: Winnie Wei Jeng Assignment: Lab 2 Professor: Phil Tracton Date: 10/07/2018 The base and derived classes in this file lay out the structure of a simple stock-purchasing database """ from ExampleException import * # Base Class class ExampleBase: # c...
86269c8a314e3bf28d484eada7776fba8bcf2cd2
ekramulpavel/python_basic
/funny_game.py
198
3.859375
4
print("Let know when you will die") n = input("Enter your name here --") a = float(input("Enter Your age here : ")) c = 2075 - a print("You will die at : " ,c, n) input("Please give your feedback")
e3dff2f79838b6f041f9394022d70749c3a537df
TheLateOne/TryingGithub
/Shared_Features_Odds(birthdays).py
1,230
3.890625
4
from random import randint def odds_of_shared_features(number_of_cases,number_of_tests,upper_range): total_occurrences = 0 for s in range(number_of_tests): listofstudents = [randint(1,upper_range) for z in range(number_of_cases)] occurrences = 0 countI = 0 for i in listofstuden...
715774278f4d569fd7f7e2e9307e0f51df1ebf8f
nebuasystems/deep-learning
/02.neural-network/05.mnist-neural-network/ex03.py
1,437
3.84375
4
# MNIST 손글씨 숫자 분류 신경망(Neural Network for MNIST Handwritten Digit Classification): 전체 시험(test) import sys import os from pathlib import Path import numpy as np from PIL import Image from matplotlib import pyplot as plt try: #sys.path.append(os.path.join(os.getcwd())) sys.path.append(os.path.join(Path(os.getcw...
e994e7f94f08b062e6413fa0322b0f7c1cb03198
darkodekan/crud-generator
/templates/tkinter/the.py
705
3.75
4
from tkinter import Tk, Label, Entry, Button class Window: def __init__(self, master): self.master = master self.label = Label(master, text="Unesi ime") self.entry = Entry(master) self.add_button = Button(master, text="Ok", command=self.click_ok) self.close_button = Button(m...
14f34d465b61b3beacfa3d27faec4c8231b49efd
Mihika16/Project-Euler-Solutions
/Problem10.py
363
3.765625
4
def Primefunction(num): if num<2: return "False"#From the next 3 lines, I got help from a website but I understood it fully for i in range(2, int(num**0.5) + 1):#this if num % i == 0:# and this return False return True sum=0 for i in range(2, 2000000): if Primefunction(i): ...
c145820dfe8508a0091293b96dbf1b45d5507bd1
Stephania86/Algorithmims
/reverse_statement.py
449
4.5625
5
# Reverse a Statement # Build an algorithm that will print the given statement in reverse. # Example: Initial string = Everything is hard before it is easy # Reversed string = easy is it before hard is Everything def reverse_sentence(s): word_list = s.split() word_list.reverse() reversed_sentence = " ".jo...
c09cbd12035fbd857e646f2379691090df8e267c
Stephania86/Algorithmims
/Even_first.py
674
4.34375
4
# Even First # Your input is an array of integers, and you have to reorder its entries so that the even # entries appear first. You are required to solve it without allocating additional storage (operate with the input array). # Example: [7, 3, 5, 6, 4, 10, 3, 2] # Return [6, 4, 10, 2, 7, 3, 5, 3] def even_first(arr):...
8fb6a2464a7c668ea237ed170a3e84a237c4a049
Lincxx/py-PythonCrashCourse
/ch3 lists/motorcycles.py
1,470
4.59375
5
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) # change an element in a list motorcycles[0] = 'ducati' print(motorcycles) # append to a list motorcycles.append('Indian') print(motorcycles) # Start with an empty list friends = [] friends.append("Jeff") friends.append("Nick") friends.append("Corey"...
fddb55fdc2d951f6c8dbcf265ee894ed6b853c43
Lincxx/py-PythonCrashCourse
/ch3 lists/exercises/3-5.py
1,030
4.25
4
# 3-5. Changing Guest List: You just heard that one of your guests can’t make the # dinner, so you need to send out a new set of invitations. You’ll have to think of # someone else to invite. # • Start with your program from Exercise 3-4. Add a print statement at the # end of your program stating the name of the guest...
9d96fff0ea4287c9fb47cdd3f0a1f0fc7d259298
Lincxx/py-PythonCrashCourse
/ch4 workingwithlists/numbers.py
148
4.0625
4
#range() function makes it easy to generate a series of numbers for value in range(1,6): print(value) number = list(range(1,6)) print(number)
ec339af34ee862e4be09aa357477f6be7512c868
Lincxx/py-PythonCrashCourse
/ch3 lists/exercises/3-4.py
577
4.34375
4
# 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who # would you invite? Make a list that includes at least three people you’d like to # invite to dinner. Then use your list to print a message to each person, inviting # them to dinner. interesting_people = ['Einstein', 'Jack Black', 'The Q...
876ead574f48ffa74816f01371c376f6eae61e32
StuMcA/multiclass_TDD_homework_ccc
/tests/room_tests.py
765
3.53125
4
import unittest from classes.room import Room from classes.song import Song class TestRoom(unittest.TestCase): def setUp(self): self.room = Room("Haddaway's Hideaway", 15) self.song = Song("Friday I'm In Love", "The Cure") def test_room_has_name(self): self.assertEqual("Haddaway's H...
e4f5a1f09d9a9ff5576a9b43ee6386ca33bb58ce
rahulpasunuri/nlp
/Assignment 3/Solution1.py
6,311
3.828125
4
#!usr/bin/python import sys import WordsTagsProbability import math def calculate(sentence, tagSequence,wordsGivenTags, tagsGivenTags) : previousTag = None #Used to keep track of the preceding word #just storing the logs separately for simplicity logTags = 0 logWord = 0 log0Flag = False #This will be used to...
848f4bc1b5f870eb8938aca74002f232e892fafe
txmayush22/searchfunctionality
/searchFunctionality.py
1,794
3.515625
4
search_google=input("Search:: ") fruits=["apple","orange","banana"] color=["red fruits blog","orange fruits blog","yellow fruits blog"] trendingNews=["apples extinct","oranges infected","bananas production increased"] shape=["round fruits","round fruits","moon shape fruits"] if search_google=="apple": p...
06c4c893f8ed133e71b66d276ee69644e710ccba
dwangus/CS440-Project-Assignments
/HMM/optimize.py
8,983
3.53125
4
##Pattern Recognition: Implementation of the "forward part" of forward/backward ##algorithm. Reports observation probability of input sequence. import sys # ------------------------------- # HMM CLASS # ------------------------------- class HMM: def __init__(self): pass # Reads HMM values from ...
c827ecee341c3daebb05cff111e1f85d2ff6b497
Tejaswe7/tejaswe-121910313038
/multiply.py
297
3.703125
4
n=int(input()) li=[] product=1 for i in range(n): x=float(input()) li.append(x) lowest=li[0] largest=li[0] for i in li: if i<lowest: lowest=i if i>largest: largest=i for j in li: if j!=largest and j!=lowest: product *= j print(product)
818dc90b264fa326240231816d470b0d03c6fd06
megodoonch/birdsong
/surface/as_numeric.py
412
3.53125
4
# This module can convert the corpus to numeric values, # based on the vocabulary list. f = open('../corpus/Sigma8.txt') vocab = [ w.strip() for w in f.readlines() ] f.close() def corpus_to_numeric( corpus ): # Given a list of a list of words, output the corpus as numeric # values. For simplicity, conv...
a2045583a6ab1ad192ff4cebf9430c0779effb19
951237/TIL
/210704_KNeighborsClassifier 분석.py
1,170
3.59375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd # pip install mglearn import mglearn # 그래프 표혀ㄴ # mglearn.plots.plot_knn_classification(n_neighbors=1) # 테스트 세트 후ㄴ려ㄴ세트 나누기 from sklearn.model_selection import train_test_split X, y = mglearn.datasets.make_forge() X_train, X_test, y_train, y_tes...
01fe86c3d4af3846c4b3099a795a0cd3e86af26a
951237/TIL
/TIL_2020/200827_TIL_행맨 게임만들기.py
1,356
3.96875
4
from random import * words = ["apple", "banana", "orange"] # 문제 단어들 word = choice(words) # 단어들을 랜덤으로 선택하기 print("answer : " + word) # 출력문 letters = "" # 입력한 알파벳을 저장하는 변수 while True: # 성공할 때까지 계속 반복 succeed = True # 성공변수 일단 print() # 한칸 띄기 for w in word: # 선택한 단어를 한글자씩 뿌려줌. if w in letters:...
a76890c3befddd734538db2879fefe253b891a68
951237/TIL
/TIL_2021/일상/210410_클래스_따라하기_상자부피구하기.py
720
3.625
4
class Box: def __init__(self, width = 0, length = 0, height = 0): # 생성자 self.__width = width self.__length = length self.__height = height def setWidth(self, width): # 값을 변경 self.__width = width def setLength(self, length): self.__length = length def s...
b359c7392be07fc5eaa77df4a1e15b9acb469250
sgwyrk17/100knock
/section1/08.py
284
4
4
# coding:utf-8 def cipher(str1): ret = "" for char in str1: if char.islower() == True: ret += chr(219 - ord(char)) else: ret += char return ret if __name__ == "__main__": str1 = "I am hungry" angou = cipher(str1) print angou hukugou = cipher(angou) print hukugou
273df9a51601a4cbb575ac27feef77309c2ce88d
sgwyrk17/100knock
/section1/09.py
471
4
4
# coding:utf-8 import random str1 = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ." def change(word): if len(word) <= 4: return word else: mid_list = list(word[1:-1]) random.shuffle(mid_list) return word[0] + "".join(mid_list) + word[-1] d...
cf9e309793686ad87a21c8a70d3b14e105e1e793
Prableen5819/my-repository
/Assignment/Assignment1.py
1,197
3.9375
4
def solution(list_len, ele, fibonacci_list): result_list = [] for i in fibonacci_list: if (ele == i): print(ele, 'already lies in the series') break else: for y in fibonacci_list: result = abs(ele - y) result_list.append(result) ...
0844e3671310e47db5643cb402d180e6d4d79ee9
hsiouhua/practice
/35_practice.py
186
3.53125
4
c = input('請輸入攝氏,程式將轉成華氏') c = float(c) f = c * 9 / 5 + 32 # 要留空格 print ('華氏溫度為:', f) # print 字串後面要加其他東西前要加, 空格
7598c2b9009f1f5d6fcc4e7c7c0a2da8b1259dd3
4l3n20/NOT-FreeCell
/not_Freecell.py
28,439
3.71875
4
from deck import Deck from card import * from stack import Stack # borrowed from Monash Alexandria article import card class notFreecell: # Temp_Cell_Slote are used for temporary and reserved cells on the left hand side Temp_Cell_Slots = 4 # Fundation_Slots are used in form of stack to collect 4 ordered...
6b62ab21c2268296db1080921db84219e376a6f9
tramxme/CodeEval
/Hard/GridWalk.py
364
3.65625
4
import sys, re, math def isValid(num1, num2): s1 = str(num1) s2 = str(num2) v = 0 for c in s1: v += int(c) for c in s2: v += int(c) return (v <= 19) def main(): res = 0 M = [] i = 0 while True: j = 0 arr = [] while True: print(re...
42ab61361b181d15deeb79ddcee10368643786c2
tramxme/CodeEval
/Easy/RollerCoaster.py
1,043
4.125
4
''' CHALLENGE DESCRIPTION: You are given a piece of text. Your job is to write a program that sets the case of text characters according to the following rules: The first letter of the line should be in uppercase. The next letter should be in lowercase. The next letter should be in uppercase, and so on. Any characters...
569fb617c5b2721bd3df06cf09fd12cc80cd071b
tramxme/CodeEval
/Easy/ChardonayOrCabernet.py
2,096
4.1875
4
''' CHALLENGE DESCRIPTION: Your good friend Tom is admirer of tasting different types of fine wines. What he loves even more is to guess their names. One day, he was sipping very extraordinary wine. Tom was sure he had tasted it before, but what was its name? The taste of this wine was so familiar, so delicious, so ple...
88ccdb7a6a37ed5b5d84d83178740295edfbff8f
tramxme/CodeEval
/Hard/ClimbingStairs.py
356
3.578125
4
import sys, re, math def doStuff(stairs): S = [1,2] for i in range(2, stairs): S.append(S[i-2] + S[i-1]) print(S[stairs-1]) def main(file_name): fileName = open(file_name, 'r') for line in fileName.readlines(): line = re.sub(r'\n','', line) doStuff(int(line)) if __name__ =...
fba8a8d2706b8c27df646d83584fcf47a46b2386
aquintero/rl_practice
/carlot.py
6,733
4
4
# Problem Statement # There are 2 car lots with a maximum of 10 cars that # can be stored at each location. At the end of each day, # the total number of cars rented and returned are # tallied. These numbers are drawn i.i.d. from a Poisson # distribution. Location 1 has a expected rental and return rate of 3 cards. # L...
7d40b3b517b9b94f00e52432a5b84d5decbadf81
tzyl/project-euler
/28.py
491
4.09375
4
def sum_number_spiral_diagonals(n): """Returns the sum of the diagonals on an nxn number spiral (n must be odd).""" if n % 2 == 0: print "n must be odd." return else: current_n = 1 sum_diagonals = 1 num = 1 while current_n < n: for i in xrange(4): ...
9701a7c075e8b5457cf9fdb505de0972ea0ffc3b
tzyl/project-euler
/41.py
1,301
3.71875
4
from time import time def prime_sieve(n): """Returns a list of all primes <= n.""" primes = [] a = [True] * n a[0] = a[1] = False for (i, is_prime) in enumerate(a): if is_prime: primes.append(i) for j in xrange(i, n, i): a[j] = False return set...
1acc2851a18bce50d11d036f4e5e2ad30221e40c
tzyl/project-euler
/24.py
503
3.671875
4
def find_permutations(lst): """Returns all permutations in a list of the string elements in lst.""" if len(lst) <= 1: return lst permutations = [] for elt in lst: reduced_list = list(lst) reduced_list.pop(lst.index(elt)) permutations.extend([elt + perm for perm in ...
6c9367cc301f8e5883b89668263d0a2d12ef0d0d
tzyl/project-euler
/56.py
235
3.9375
4
def digit_sum(n): """Returns the sum of the digits of the integer n.""" return sum(map(int, list(str(n)))) print reduce(lambda x, y: x if x > y else y, [digit_sum(a ** b) for a in range(100) for b in range(100)])
f78f231145b031de661340f6bb6dbedcd567b837
randalsallaq/data-structures-and-algorithms-python
/data_structures_and_algorithms_python/challenges/array_reverse/array_reverse.py
350
4.4375
4
def reverse_array(arr): """Reverses a list Args: arr (list): python list Returns: [list]: list in reversed form """ # put your function implementation here update_list = [] list_length = len(arr) while list_length: update_list.append(arr[list_length-1]) l...
02bd9b17d04efabd81c14e03bf73db926bb953b7
faresZzz/CS-DEV
/CSDEV/TP1/EXO6/ex6.py
342
3.75
4
def tricolore(n): carreParfait=["1","4","9"] nb=n*n for chiffre in str(nb): if chiffre not in carreParfait: return False return True def tous_les_tricolore(N): trico=[] for i in range(N+1): if tricolore(i): trico.append(i) return(trico) print(tous_...
2bfd20949df8d0abea8dd50cfaee1a478d235328
NeoGlanding/python-masterclass
/02-program-flow/and-or-in.py
521
3.953125
4
age = int(input('How old are you? ')); # if age > 16 and age <= 50: # penggunaan and if 16 < age <= 50: #Simplified Chaining print('You are welcome to surprise me!') else: print('Have a nice rest') if age < 16 or age > 50: print('Have a nice rest') else: print('You are welcome to surprise me!') to...
fd5500fd69b09a7fba25b87ddf5ba1a39d5b29c9
NeoGlanding/python-masterclass
/01-python-introduction/string-formatting.py
280
3.6875
4
# > untuk rata kanan # < untuk rata kiri # :8 untuk spasi for i in range(1,11): print("No {0:8}, cubed is {1:>9}, squared is {2}".format(i, i ** 2, i **3)) # f-strings, sama seperti backtick pada js, untuk melakukan formatting nama = "Ihsan" print(f"Hallo nama saya {nama}")
49aa7d5c7bac93bd45c1e53ec02d8e094c829d04
kas/pie
/05-trees-and-graphs/03-preorder-traversal-no-recursion.py
629
3.9375
4
class Node: def __init__(self, data, left, right): self.data = data self.left = left self.right = right class NodeStack: def __init__(self): self.stack = [] def push(self, node): self.stack.insert(0, node) def pop(self): return self.stack.pop(0) def pr...
f6a542e60940694d64d78abcdca1fe98d37886ba
phivk/getting-started-with-python
/code/tictactoe.py
6,517
4.09375
4
""" tictactoe.py An interactive game in Python Created by Philo van Kemenade """ import random class TicTacToe(object): """A game of Tic Tac Toe""" def __init__(self): self.playing = True self.board = Board() self.turn = self.whoStarts() # start the game def start(self): ...
fc77ac3c1e1e8461066564d304b4de33459a09f2
cgkevork/Coursera
/Intro_Python/3_2/RegExp.py
370
3.703125
4
#!/usr/bin/python import re hand = open ('regex_sum_340373.txt') numlist = list() for line in hand: line = line.rstrip() stuff = re.findall('[0-9]+',line) if len(stuff) < 1 : continue #print stuff #num = float(stuff) num = [int(i) for i in stuff] numlist.extend(num) count = len(numlist) sum = sum(numlist)...
e57a528694538755db8947a21d14081bce3160fa
nuass/lzh
/多任务编程/mytest.py
649
3.5625
4
from multiprocessing import Process,Value import os import time num=Value('i',1) def addNum1(): while True: num.value+=1 # time.sleep(0.1) if num.value==1000: break def addNum2(): while True: num.value+=1 # time.sleep(0.1) if num.value==1000: ...
a4665a8a63cdd5b3b3caf0bcb0e7969027ea3069
nuass/lzh
/数据分析/day06/demo02_vec.py
366
3.5625
4
# coding=utf-8 """ 函数矢量化 """ import numpy as np import math as m def f(a,b): return m.sqrt(a**2+b**2) print(f(3,4)) a=np.array([3,4,5,6]) b=np.array([4,5,6,7]) #矢量化过后的函数 f_vec f_vec = np.vectorize(f) print(f_vec(a,b)) print(f_vec(a,5)) #np.frompyfunc() 也可以实现函数矢量化 f_fpf = np.frompyfunc(f,2,1) print(f_fpf(a,b))
8ff7e7b25fa251914cefc9ac48073768cc06c745
nuass/lzh
/The_diffcult_point/iter_iterable.py
1,104
4.21875
4
#coding:utf-8 #迭代器一定是迭代对象,反过来则不是, #迭代对象是定义__iter__()方法,返回迭代器 #迭代器是定义了__iter__()和__next__() #生成器是特殊的迭代器,yeild的作用和__iter__()和__next__()的作用相同 from collections import Iterable,Iterator class Myrange(object): def __init__(self,start,end,step=1): self.start=start self.end=end self.step=step ...
bbfb676aaf1cbd215625295f144b44d8e6ad2a55
ankitsingh03/patterns-using-python
/diamond-pattern.py
281
3.546875
4
n = 6 s = [] for i in range(1, n+1, 2): s.append(["*"*i]) for i in range(len(s)): print(" "*(len(s)-1-i), end=" ") print(*s[i]) for i in range(len(s)-2, -1, -1): print(" " * (len(s) - 1 - i), end=" ") print(*s[i]) # output ''' * *** ***** *** * '''
70d19e9d142068baec76ef7f27a4ad868caf198d
dhoekwater/csprag-w19-rpn
/rpn.py
768
3.953125
4
#!/usr/bin/env python3 import math import operator operators = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.truediv, '^' : operator.pow, '//' : operator.floordiv } def is_numeric(text): try: float(...
da7575f749d805424cfb75b25965c7a882833909
smsbd21/PythonProject
/Largest_value_3.py
313
3.921875
4
# nested if -- else control statement mahin, mim, sazzad = 15, 22, 18 if mahin > mim: if mahin > sazzad: print("Mahin is elder than all") else: print("Sazzad is elder than all") elif mim > sazzad: print("Mim is elder than all") else: print("Sazzad is elder than all")
40fb2106da8182dbeaa14dba584b49082f36ff85
smsbd21/PythonProject
/prog_05_prime_series.py
281
3.96875
4
def return_primes(n): my_list = [] for i in range(2, n + 1): for j in range(2, i): if i % j == 0: break else: my_list.append(i) return my_list num = int(input("Enter your number : ")) print(return_primes(num))
b6f14e3412058492e7dd123ed5b911fa7a3a9b76
cgb0008/Electric-Discharge-Using-DLA
/ElecDiff.py
4,143
3.609375
4
#Christopher Basham #Class Containing All Required Functions import numpy as np import random as rand class Walk(): def __init__(self): ''' Initializes Class ''' def SeedStart(self,N,spot): ''' Assigns Starting Location of Seed Arguments: ...
28a80c8ffa7c60649a8afe4aa64782427f9ae502
dinorego/SFE311T2021
/expanded_form.py
756
3.921875
4
def expanded_form(input_int): input_str = str(input_int) str_length = len(input_str) expanded = "" for i in range(len(input_str)): if input_str[i] is not "0": expanded += input_str[i] + "0"*(len(input_str) -1 - i) if i < len(input_str) -1: expanded += " +...
8c70ab1d4ea4be468ebf36cba126ed7f6982a6d2
king1991wbs/leetcode
/excsheetcol2num.py
508
3.78125
4
#Given a column title as appear in an Excel sheet, return its corresponding column number. # #For example: # # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26 # AA -> 27 # AB -> 28 class Solution: # @param s, a string # @return an integer def titleToNumber(self, s): s = s[::-1] #pri...
755169f0b281135475a3b2c89b83548c15664773
dnwigley/Python-Crash-Course
/more_loops.py
252
3.9375
4
#4.12 my_foods =['pizza','falafel','carrot cake'] fried_foods = my_foods[:] print("My favorite foods are;-") for food in my_foods: print(food.title()) print("My friends favorite foods are ;-") for food in fried_foods: print(food.title())
057dfd51b477f56960647c8f364c99f9aedcbc60
dnwigley/Python-Crash-Course
/pizzas.py
165
3.59375
4
#try it yourself 4-1 pizzas pizzas=['hawaiian',"cheese and tomato",'peperoni'] for food in pizzas: print('I like '+food+' pizza') print("\nI really like pizza")
70291137c6c759f268f7ab8b45591a3d1ec95cd9
dnwigley/Python-Crash-Course
/make_album.py
492
4.21875
4
#make album def make_album(artist_name , album_title): """"Returns a dictionary based on artist name and album title""" album = { 'Artist' : artist_name.title(), 'Title' : album_title.title(), } return album print("Enter q to quit") while True: title = input("Enter album title: ") i...
8dcaa5d1754e11b89c8465033227a33d301b83b8
dnwigley/Python-Crash-Course
/myownlist.py
134
3.609375
4
list=['car','bike','plane','tardis'] print("I own a "+list[0]+" I used to ride a "+list[1]+" but ultimately a "+list[-1]+ " is best")
24ce3d26f3adce4a7a7833369abc8b36bf0b30df
dnwigley/Python-Crash-Course
/mypizzas.py
341
4.03125
4
#try it yourself 4-1 pizzas pizzas=['hawaiian',"cheese and tomato",'peperoni'] friend_pizza = pizzas[:] for food in pizzas: print('My favourite pizzas are '+food) print("\nI really like pizza\n") friend_pizza.append('ham') for food in friend_pizza: print('My friend favourite pizzas are '+food) print("\nHe ...
8a55703686a3c55ef4fe840aabe8b2737b7a026b
crito/hellbench
/src/hellbench.py
7,198
3.703125
4
#!/usr/bin/env python import os, sys from multiprocessing import Pool import optparse import time import random import threading from time import sleep class ThreadPool(object): """Flexible thread pool class. Creates a pool of threads, then accepts tasks that will be dispatched to the next available thre...
dfb65702d5c2d6a6c1c49f6118256a6cf5bac638
naveensambandan11/PythonTutorials
/assignment_Arrays.py
244
3.9375
4
#declare array and sort it import array as ar x = ar.array('i',[100,201,72,81,99]) print (sorted(x)) #program to find factorial x = int(input('enter the number:')) temp = 1 for i in range(1, x+1): temp = temp*i print (temp)
6a4af18ac05579d734588a3f4e10e5d22bca4afc
naveensambandan11/PythonTutorials
/tutorial 37_PassListToFunctions.py
495
3.875
4
#Pass Lst to the function def Func_1(lst): even = 0 odd = 0 for i in lst: if i%2==0: even+=1 else: odd+=1 return odd, even lst = [] a = int(input('enter the length of list')) for i in range(a): b = int(input('enter the next value:')) ls...
d110f5a47b5c0dcf9c0984ec843856438f9540b8
naveensambandan11/PythonTutorials
/tutorial 54_Oops_InnerClass.py
922
3.96875
4
# Oops - Inner Class class univ: def __init__(self, m1, m2, m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 # these are instance variable self.col_details = self.college() # adding the sub class as argument def m_total(self): return self.m1 + self.m2 + self.m3 ...
53fb20fc1ba77ca145dea0b93a89cc020f887619
naveensambandan11/PythonTutorials
/tutorial 39_Factorial.py
224
4.34375
4
# Funtion to calculate factorial def Fact(n): fact = 1 for i in range(1, n+1): fact = fact * i return fact n = int(input('enter the number to get factorial:')) result = Fact(n) print(result)
cf9d36dcb26e9b184afb36e0ff14b4cade027e64
naveensambandan11/PythonTutorials
/tutorial 22_BreakContinuePass.py
450
3.796875
4
for x in range(1,100): if x >= 51: break print ('bus ', x) print("Don't have more than " , x-1 , " buses") #-------------------- for x in range(1,100): if x % 5 == 0: break print(x, "Buses") #-------------------- for x in range(1,100): if x % 5 == 0: continu...
4811d417868dd3cac082b1a1b21ef18ae1088d1f
naveensambandan11/PythonTutorials
/assignment_ifstatement.py
460
3.953125
4
#x = int(input('enter the number:')) #if x > 0: # print('x is positive') #elif x < 0: # print('x id negative') #else: # print('x = 0') a = int(input('enter 1st num:')) b = int(input('enter 2nd num:')) c = int(input('enter 3rd num:')) if a>b: if a>c: print ('a is gretest number')...
be857ba4a911f8e116e283c6c7b4872fd5ca2ded
naveensambandan11/PythonTutorials
/tutorial 51_Oops_Constructors_Self.py
1,296
4
4
# Oops - object creation and execution with different inputs class engg: def __init__(self): self.name = 'naveen' self.dept = 'ECE' self.sem = 3 def update(self): self.dept = 'IT' def update_2(self,a): self.sem = a def compare(self,x): i...
28f566dbe65cadcaec3a62b0eda241f778568d7a
naveensambandan11/PythonTutorials
/tutorial 32_functions.py
357
3.515625
4
#Funtion def func_1(): print ("hello world") def func_2(x, y): sum = x+y print(sum) def func_3(a, b): sum = a+b return sum func_1() func_2(5,6) result = func_3(100, 200) print(result) def func_4(a,b,c): x = a+b+c y = (a+b)-c z = a-c return x,y,z result...
11521e79c79585671a31aa3265f2399a0da1b25e
Muhammad5943/Cleaning-Data-in-Python-
/12.DuplicateandMissingData.py
896
3.546875
4
import pandas as pd df = pd.read_csv('/home/muhammad/apps/Learn_python/Cleaning Data in Python/duplicate_data.csv') # print(df) df = df.drop_duplicates() print(df) print('\n') df2 = pd.read_csv('/home/muhammad/apps/Learn_python/Cleaning Data in Python/missing_data.csv') print(df2) print('\n') print(df2.info()) prin...
83ead8757fc29e120bf8763cca496bb1425ea138
Handakai/aads_Cython
/binary_search.py
882
4.03125
4
"""Binary Search""" def in_search(array: object, item: object) -> int: """ Index searching :param array: array :param item: element :return: element index """ start = 0 mid = 0 end = len(array) - 1 while start <= end: mid = (start + end) // 2 mid_value = array[m...
01d95e2b1a80bf249f6f4ae8f26945a9f4c7ba1a
marioloera/python_google_course
/e_AutomatingReal-WorldTasksWithPython/c5_pdf.py
3,390
3.53125
4
#!/usr/bin/env python3 import os from reportlab.platypus import SimpleDocTemplate # Each of these items (Paragraph, Spacer, Table, and Image) # are classes that build individual elements in the final document. from reportlab.platypus import Paragraph, Spacer, Table, Image # reportlab needs style for each part of the...
da85714a0fea257a811e53d95d5b0bf3d99717a5
TwitchT/Learn-Pythonn-The-Hard-Way
/ex4.py
1,687
4.4375
4
# This is telling me how many cars there is cars = 100 # This is going to tell me how much space there is in a car space_in_a_car = 40 # This is telling me how many drivers there is for the 100 cars drivers = 30 # This is telling how many passengers there is passengers = 90 # This tells me how many empty cars there is ...
1dfed477aa45a48f640d4d869f5ae051c99b363a
TwitchT/Learn-Pythonn-The-Hard-Way
/ex13.py
984
4.125
4
from sys import argv # Read the WYSS section for how to run this # These will store the variables script, first, second, third = argv # Script will put the first thing that comes to the line, 13.py is the first thing # So script will put it 13.py and it will be the variable print("The script is called:", script) # If y...
33115232faf0951e37f4b48521e3e22f6bbc2a00
TwitchT/Learn-Pythonn-The-Hard-Way
/ex23.py
916
4.125
4
import sys # Will make the code run on bash script, input_encoding, error = sys.argv # Defines the function to make it work later on def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding, errors) return main(language_file, encoding, e...
cf5fb556b165ef7cec6834faa4b8960543a4554c
TwitchT/Learn-Pythonn-The-Hard-Way
/ex17.py
1,372
3.53125
4
from sys import argv; from os.path import exists; script, from_file, to_file = argv; print(f"Copying from {from_file} to {to_file}"); in_file = open(from_file); indata = in_file.read(); print(f"The input file is {len(indata)} bytes long"); print(f"Does the output file exist? {exists(to_file)}"); print("Ready, hit RETUR...
578497df0821f5c54a10a6a88b6d99fd57888f01
gt11799/findjob
/top_k_heapq.py
1,923
3.984375
4
#! /usr/bin/env python ''' Top k element with heapq. minimum k and maxmum k ''' import heapq import random class MaxkHeap(object): ''' Given k, return maxmum k elements, and sorted have two method: push and topk, just like heapq ''' def __init__(self, k): self.k = k self....
2380f5d728587fe3a4be15b2428754d7426df96e
henryxian/euler
/triplet.py
293
3.71875
4
#!/usr/bin/env python from math import sqrt if __name__ == '__main__': found = False for a in xrange(1, 1001): for b in xrange(a, 1001): result = a + b + sqrt(a ** 2 + b ** 2) if result == 1000: print a * b * sqrt(a ** 2 + b ** 2) found = True break if found: break
03cd39bc59234bd30b84a89ae3157a44363f8a93
Ishan-Bhusari-306/applications-of-discrete-mathematics
/dicestrategy.py
988
4.28125
4
def find_the_best_dice(dices): # you need to use range (height-1) height=len(dices) dice=[0]*height #print(dice) for i in range(height-1): #print("this is dice number ",i+1) # use height for j in range(i+1,height): #print("comparing dice number ",i+1," with dice number ",j+1) check1=0 check2=0 fo...
20762d78b7ae93a7c83f5a54b1815426247e0402
Ishan-Bhusari-306/applications-of-discrete-mathematics
/modularexponentiation.py
999
3.921875
4
import math """ Compute b^e mod m by log running time """ def FastModularExponentiation(b, e, m): exList = exponentialOfTwo(e) #print(exList) result = 1 for n in exList: #print(2 ** n) #print(partialExponentiation(b, 2 ** n, m)) result *= partialExponentiation(b, 2 ** n, m) while result > m: result -= (res...
42ee6792f304da2c355a6d6ff40fdba1e998f91d
mglacayo07/DailyCodingTip1
/main.py
817
3.984375
4
# return a new sorted merged list from K sorted lists, each with size N. import heapq def merge(lists): merged_list = [] heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) print("heap",heap) print() while heap: val, list_ind, element_ind = heapq.heappop(...
4bf95848fa8b03b26b81a736b88961d7e4e9f035
Dylan-Barclay/User
/chaining_meathods.py
838
3.734375
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount return self def make_withdraw(self, amount): self.account_balance -= amount retur...