blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
96e9ef1c4195f85fe75038978f21e3ab8863f64c
hepimen/learn-python
/lists_delete_item.py
621
3.921875
4
animals = ["Ayam", "Bebek", "Cicak"] # Menghapus item tertentu (Bebek) pada "Lists" dengan method "remove" animals.remove("Bebek") print(animals) # ["Ayam", "Cicak"] # Menghapus item terakhir pada "Lists" dengan method "pop" animals = ["Ayam", "Bebek", "Cicak"] animals.pop() print(animals) # ["Ayam", "Bebek"] # Me...
d6af1dcd6df170f1fdfbcdaee7019ace1149b8c8
zhanglintc/leetcode
/Python/Remove Duplicates from Sorted Array II.py
1,045
3.71875
4
# Remove Duplicates from Sorted Array II # for leetcode problems # 2014.10.20 by zhanglin # Problem Link: # https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ # Problem: # Follow up for "Remove Duplicates": # What if duplicates are allowed at most twice? # For example, # Given sorted array A = [1,...
3b87eba24bae73e89563e8aa597d617ed8d638b3
wagner30023/fundamentos_python
/mundo1/cores.py
212
3.53125
4
'''print('\033[7;33;46mOlá, Mundo\033[m') print('{}Olá, Mundo{}'.format('\033[4;34m', '\033[m')) ''' x = 'carlos wagner pereira de morais' convert = x.split() print(' O ultimo valor do array: {} '.format(convert[len(convert)-1]))
ee38d90620cfa2c264ce20b35198b170dbce8769
Ahmad-Magdy-Osman/IntroComputerScience
/Files/mOsmanWk09P1.py
1,137
4.15625
4
################################################################ # # CS 150 - Worksheet #09 --- Problem #1 # Purpose: Practicing how to read a file's content into a list, # sort the list alphabetically, and write the sorted # list to another file # # Author: Ahmad M. Osman # Date: November 21, 2016 # # Filenam...
0c748061c2c6b54760d3f4f429790fd2650fb6fc
jnepal/CS101-udacity
/Basics/Dictionary.py
622
4.15625
4
''' Dictionary is Key value pair It is mutable like list It is analogous to Hash Table ''' elements = { 'hydrogen': 1, 'helium': 2, 'carbon': 6 } print(elements['hydrogen']) elements['nitrogen'] = 7 print(elements) #Checking whether the key is present in Dictionary or not print('boron' in elements) pri...
58d04146562af9bb51f370533b307abc4a564e0f
VCloser/CodingInterviewChinese2-python
/36_ConvertBinarySearchTree.py
1,270
3.9375
4
class TreeNode(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def convert(root): if not root: return [] last_node = None last_node = convert_core(root, last_node) while last_node and last_node.lef...
d37da4637c2a33af51fa564ea778efe0fe2d6d55
yemao616/summer18
/Google/2. medium/757. Pyramid Transition Matrix.py
2,182
4.03125
4
# We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. # For every block of color `C` we place not in the bottom row, we are placing it on top of a left block of color `A` and right block of color `B`. We are allowed to place the block there only if `(A, B, C)` is ...
8848a43da2880285f0e0faddc137ab9cf28677a4
pacharapol1454/robotics_lab3
/week2.py
294
3.609375
4
def validate_pin(psw): c=0 state=0 for i in psw: if i.isalpha(): c=c+1 if c==0: psw_int = int(psw) digit = 0 while(psw_int > 0): psw_int = psw_int//10 digit = digit + 1 if digit == 4 or digit == 6: state=state+1 if state==1: return True else: return False
d97b1ab5b1894189dee826bffccbf5fd79dd2983
duanwandao/PythonBaseExercise
/Day18(核心编程)/Test06.py
1,089
4.1875
4
""" 创建生成器的方式: 1. 列表推导式 g = (列表推导式) generator 2. yield 定义任意一个方法,在方法中加入yield关键字 生成器生成数据3中方式: next(g) g.__next__() g.send() 如果使用send生成第一个数据的时候,必须有一个None参数 yield: 携程 """ # def test(): # for x in range(10): # p...
318165271f55dba013e7b596934cdc9ff05fcd4d
yzhong52/AdventOfCode
/2020/day24.py
2,052
3.65625
4
import collections from typing import List, Iterator, Dict, Tuple directions = {"e": (2, 0), "se": (1, -1), "sw": (-1, -1), "w": (-2, 0), "nw": (-1, 1), "ne": (1, 1)} def parse() -> Iterator[List[str]]: file = open("day24.txt") lines = file.read().splitlines() for line in lines: instruction = [] ...
4288fe9870048fa9a851df0fb08afa06148eea8f
Felienne/spea
/7183 Python Basics/11 Chapter 2.3 - About For/03 Accumulating to new lists and better translation/86912_05_code.py
1,021
3.734375
4
# For reference, here is the original code:<div> </div><div><pre><code>calculations_to_letters = {'2':'two', '+': 'plus', '=':'equals', '4':'four'} input = "2 + 2 = 4" calculation_elements = input.split() element_1 = calculation_elements[0] word_1 = calculations_to_letters[element_1] element_2 = calculation_elements[...
4d19343cf3c08d9b515dccf340eb6cb6d18537b6
Nicolas-Fernandez/grid_path_challenge
/myAntsArmyAnswerYourQuestion.py
5,607
3.640625
4
""" myAntsArmyAnswerYourQuestion is a python script that try to answer the question: "How many paths do you have from point A to point B in a square of 10 per 10 ?" With fact that you can just use 2 movings : to the Right and to the Bottom! This question was asked to Nicolas by Fabrice in 2017 the Wednesday 22th of nov...
8d496315e98ce7d62cb80a170db65e7ed457a62f
ubante/poven
/projects/odds/nba_finals.py
1,588
3.609375
4
from __future__ import print_function import random from collections import defaultdict iterations = 999 odds_game_for_t1 = 0.90 win_count = defaultdict(int) for i in range(1, iterations+1): print("Iteration #{0:2}: ".format(i), end="") t1_wins = 0 t2_wins = 0 scores = "" game_number = 1 w...
b5eac55ac4fb3752c7a63db3153d832dbc54dd41
nathan29849/pirogramming13
/algorithm_class_3_0711.py
1,985
3.578125
4
count = int(input()) #aabb -> ["a", "b"] def check_group(word): # input = str,output = Boolean last_alphabet = "" alphabets =[] for letter in word: if letter == last_alphabet: continue else: if letter in alphabets: # 문자가 이미 있는지 없는지 검사 return False...
25ddb1301b2cd37c3e0eced96499bcbfc9a007b4
suhyeonjin/CodePractice
/Baekjoon/4344.py
492
3.96875
4
testCase = input('') CaseList = [] for i in range(testCase): CaseList.append(raw_input('')) def get_AVG(ArrayList, aver): result = [] for i in ArrayList: if float(i) > float(aver): result.append(i) return '%.3f'%((float(len(result))/len(ArrayList))*100) for k in CaseList: k ...
671463991f05b4e70215a0a68e6532dfc857a0bc
juansalvatore/algoritmos-1
/ejercicios/2-programas-sencillos/2.3.py
354
3.953125
4
# Ejercicio 2.3. # Utilice el programa anterior para generar una tabla de conversión de temperaturas, # desde 0 °F hasta 120 °F, de 10 en 10. from helpers import fahrenheit_to_celsius def generar_tabla(): for i in range(0, 13): fahrenheit = i * 10 print(str(fahrenheit) + 'F', fahrenheit_to_celsiu...
f4cdb53b55a79b6002dab67b58be4523c9431708
Aadesh-Shigavan/Python_Daily_Flash
/Day 13/13-DailyFlash_Solutions/28_Jan_Solution_Three/Python/Program1.py
519
3.875
4
''' Problem Statement Write a Program which detects whether the entered number is perfect or not A Perfect number is a number which is equal to the sum of its Perfect divisor A perfect divisor of x is the number giving remainder 0 on dividing x by number, where number != x ''' num = int(input("Enter a Number\n")) s...
47e93fba32e6f979c70fad33f8ce8cb8e8a0733d
Mattiezilaie/TicTacToe.py
/k.py
5,411
3.765625
4
class TicTacToe: def __init__(self): self._board = [['','',''],['','',''],['','','']] self._current_state = "UNFINISHED" self._num = 0 def horizontal_win(self, row, player): if row>2 or row<0: return False if self._board[row] != "": retur...
64b746060c53e94de3fe592241352a153d6a88a1
django-group/python-itvdn
/домашка/starter/lesson 6/Aliona Baranenko/task_2.py
377
4.53125
5
def reversed(string): reversed_string = '' for i in string: reversed_string = i+reversed_string print('reversed string is: ', reversed_string) if string == reversed_string: print("it's a palindrome") else: print("it's not a palindrome") string = input('enter a stri...
9e4a73ffe8f3c2a9e4ae0ef7cd10242d3ca237f3
GYGeorge/py
/leetcode/129SumRootToLeft.py
1,263
4.09375
4
# * @Author: gaoyuan # * @Date: 2020-07-01 16:57:08 # * @Last Modified by: gaoyuan # * @Last Modified time: 2020-07-01 16:57:08 class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): "...
27f7cbdea2eb1fa0bc784e265787d1c8c3895270
prasun-biswas/python_assignments
/named_parameters.py
681
3.96875
4
# TIE-02107: Programming 1: Introduction # MAHABUB HASAN, mahabub.hasan@student.tut.fi, Student No.: 281749 # Solution of Task - 4.5.2 # A program that prints box def print_box(width, height, border_mark="#", inner_mark=" "): for x in range(1, height+1): for y in range(1, width+1): if x == 1 or...
75ab30b66ddab88e4de956cd5a79675918056d83
SagarKulk539/APS_Lib_2020
/CodeChef/LECANDY.py
303
3.5625
4
''' APS-2020 Problem Description, Input, Output : https://www.codechef.com/problems/LECANDY Code by : Sagar Kulkarni ''' n=int(input()) for _ in range(0,n): N,C = map(int,input().split()) list1=[int(x) for x in input().split()] if sum(list1)<=C: print('Yes') else: print('No')
49f31990fc0ee1550fbd71aee2f7292fcea55115
ege-erdogan/comp125-jam-session-02
/24_11/strings.py
1,021
4.03125
4
''' COMP 125 - Programming Jam Session #2 November 23-24-25, 2020 1. Write a function dna_replica, which takes a DNA sequence of arbitrary length as input, and returns the complementary sequence as a string. 2. Implement a function, remove_whites, which takes a string as input and returns a new string by removing t...
1338ed44634d2ed9c976699a97b786cd29acf252
Whitie/AdventOfCode
/2019/Day_10/day10p1.py
1,340
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import sys from collections import defaultdict, namedtuple Point = namedtuple('Point', 'x y') def read_file(filename): coordinates = [] with open(filename, 'r') as fp: for y, line in enumerate(fp): line = line.strip() ...
ac344e36f3dce324aae4767dc22ef38ce73d50d6
SebastianThomas1/coding_challenges
/hackerrank/data_structures/linked_lists/merge_two_sorted_linked_lists.py
892
3.578125
4
# Sebastian Thomas (coding at sebastianthomas dot de) # https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists # # Merge two sorted linked lists class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None def merge_lists(head1, head2): if he...
7a1befdca37081fe4fbbeb9efaf89862b0f16a3c
eprj453/algorithm
/KAKAO/2019winterIntern/크레인인형뽑기.py
797
3.5625
4
def solution(board, moves): answer = 0 basket = [] for m in moves: i = 0 while i < len(board): doll1 = board[i][m-1] if doll1 != 0: if not basket: basket.append(doll1) else: doll2 = bas...
f84db76a017f0ffd5a28c8c62b969c9616b8f92a
rnarodit/100daysofcode
/Day 16/objectOriantedProgramming.py
1,331
4.4375
4
#OOP -> instead of having one long an complicated code (procedural). you simplify the relationships in your code by seprating it into different components that can later reused in other code. #OOP tries to model real world objects -> divide to what object has (attributes -> fancy way to say variable) and what object do...
d5f2dd3a507ace4c76d9f881262c331e6313d1d4
dilyanpenev/advent-of-code
/python/day2.py
1,454
3.65625
4
def check_occurrences(str, letter, min_chars, max_chars): count = 0 for char in str: if char == letter: count += 1 if count >= min_chars: if count <= max_chars: return True else: return False def check_positions(str, letter, pos1, pos2): if len(str) ...
e11e6db8f7fa8ad886a7ec287ed9d04c7b334287
Vladimir-Surta/Vladimir-Surta
/task_1_3.py
142
3.515625
4
# Task №3 l = int(input('Введите значение "l_длина ребра куба:"')) v = l ** 3 s = 4 * l ** 2 print({v, s})
b95c0c7a7440c0b57e89b77d74da70ee8a390bec
masterchief164/schoolprojects
/l5q3.py
226
3.5625
4
def fibo(): a = 1 b = 1 def fib(): nonlocal a, b n = a + b b = a a = n return b return fib f = fibo() inp = int(input()) for i in range(inp): print(f(), end=" ")
cb92340dda44cb84fd10dcc8f13506b10604a5cd
SURGroup/UQpy
/docs/code/surrogates/pce/plot_pce_ishigami.py
5,479
3.765625
4
""" Ishigami function (3 random inputs, scalar output) ====================================================================== In this example, we approximate the well-known Ishigami function with a total-degree Polynomial Chaos Expansion. """ # %% md # # Import necessary libraries. # %% import numpy as np import ...
7a7bf09f18ddb37cb36ca832c5b198f6ac76bde0
lineva642/08.11.2016
/vector2.py
531
3.5
4
class Vector: def __init__(self, x, y): self.x=x self.y=y def __str__(self): return str(self.x)+', ' + str(self.y) def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector(self.x - other.x, self.y...
b6106da3ddd902d597a38c8dc95034144fafa904
webclinic017/algorithmic_trading_in_python
/hult_classes/class_5/bt_loops.py
2,499
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 28 22:33:04 2019 Showing looping with bt.py This is a very inelegant way of looping. I did it this way to make it very clear what was going on and how it relates to the steps described in class. It is often useful to start with an inelegant program when you are trying...
9a727f2e5801d2a62157cfc3b1fd53cda89e1593
martanunesdea/coding-club
/encryption/encrypt_file.py
482
3.640625
4
from cryptography.fernet import Fernet key = Fernet.generate_key() # Saving the key in a separate file for later usage file = open('key.key', 'wb') # Open the file as wb to write bytes file.write(key) # The key is type bytes still file.close() # Open the file to encrypt f = open('test.txt', 'rb') data = f.read() ...
762f3b2d29a68b57e19b968fec445eef5d580685
gtg7784/2020_summer_algoritim
/2110.py
637
3.71875
4
import sys N,C = map(int, sys.stdin.readline().split()) home = [int(sys.stdin.readline()) for _ in range(N)] home.sort() def routerInstall(distance): count = 1 cur_home = home[0] for i in range(1,N): if (distance <= home[i] - cur_home): count+=1 cur_home = home[i] return count ...
265b10d854421b80c83bb3443102728859e04f77
PRINCEHR/Python
/c5.py
189
3.734375
4
'''def f(int ): #print ("i") pass f()''' m= input("enter no") def f(): for x in range(1, 11): list1 = x *m print ("%s x %s = %s" %(m,x,list1)) f()
2927a7a7deaace222d66fde9a6e365523614c2ff
ShalomVanunu/SelfPy
/Targil6.1.2.py
240
3.5625
4
def shift_left(my_list): a , b ,c = my_list new_my_list = [b ,c, a] print(new_my_list) def main(): # Call the function func shift_left([0, 1, 2]) shift_left(['monkey', 2.0, 1]) if __name__ == "__main__": main()
583347c741490cc0c06113b46ea51462df16fa53
Jeetuyadav82/Take-Home-Coding-Challange-consultadd
/Exercise_3_Balance Bots/Balance Bot.py
1,178
3.796875
4
import collections import re bots = collections.defaultdict(list) outputs = dict() # here we are taking input as .txt file lines = open('input3.txt') rules = [line.split() for line in lines] # input3.txt is file name while rules: for r in rules: if r[0] == 'value': bots[int(r[5...
13856a934d9a3a29416b107262c9a0abae850957
santhosh-kumar/AlgorithmsAndDataStructures
/python/problems/string/add_two_binary_strings.py
1,620
3.796875
4
""" Add two binary strings Given two binary strings, return their sum (also a binary string). Example: a = "100" b = "11" Return a + b = “111”. """ from common.problem import Problem class AddTwoBinaryStrings(Problem): """ AddTwoBinaryStrings """ PROBLEM_NAME = "AddTwoBinaryStrings" NOT_FOUND...
f4da423a210e5c34c7152a6f0f2c2a371177757a
labulel/python-challenge
/PyPoll/main-LL.py
3,065
3.859375
4
import os import csv csvpath = os.path.join("Resources","03-Python_Homework_Instructions_PyPoll_Resources_election_data.csv") #Import and read csvfile: with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #skip header: csv_header = next(csvreader) #set starting value of running ...
e1f4dfe9b1fe22f5512e9f871af89110f097ae41
nihao-hit/leetcode
/Third Maximum Number.py
619
3.8125
4
import sys class Solution: def thirdMax(self,nums): ''' :type nums:List[int] :rtype:int ''' nums = set(nums) first = second = third = -sys.maxsize for n in nums: if n > first: first,second,third = n,first,second elif n >...
3eb60a27fc3fb4d66b948e572654a1e2c2573665
dpneko/algorithmTest
/11. 盛最多水的容器.py
903
3.734375
4
""" 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def maxArea(self, height...
049f7cf9cf2f79c47332d7e5b8829df985c1d122
Leonardo-KF/Python3
/ex018.py
315
4.09375
4
from math import cos, sin, radians, tan a1 = float(input('Digite um ângulo: °')) cos = cos(radians(a1)) sen = sin(radians(a1)) tg = tan(radians(a1)) print(f'O seno do angulo {a1}° é: {sen:.2f}°') print(f'O cosseno do angulo {a1}° é: {cos:.2f}°') print(f'A tangente do angulo {a1}° é: {tg:.2f}°')
0cf10137a153ee33f9c87707b2004d6f03fee738
aditiwalia350/100DaysOfAlgorithms
/Recursion/factorial.py
185
3.828125
4
def factorial(n): if n == 0: return 1 elif n > 0: return n * factorial(n - 1) print(factorial(5)) print(factorial(0)) print(factorial(1)) print(factorial(-1))
4924e290786a88fc322fde9d374f1e53a243f184
Venkatesh123-dev/Python_Basics
/Day_15.py
1,939
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 15 16:30:03 2020 #itertools.product() @author: venky A = [1, 2] B = [3, 4] AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] """ from itertools import product A = [int(x) for x in input().split() ] B = [int(y) for y in input().split() ] print (*product(A...
f907f3db9cc16d24930aa482b05a2e2f65b5f932
Ruslan5252/all-of-my-projects-byPyCharm
/курсы пайтон модуль 3/Задание 22.py
186
3.53125
4
a=1 s=0 k=0 while a != 0: a = int(input("введите число")) s += a k+=1 print("среднее значение суммы введенных чисел ",s/(k-1))
0cc63017e465bb328a4f0618c683edc113a33229
yuzurunishimiya/python-trick-01
/merging_dict.py
243
3.625
4
dict1 = { "name": "Hanekawa Tsubasa", "meta": 50, } dict2 = { "friend": "Senjougahara Hitagi", "meta": 100 } merged = {**dict1, **dict2} print(merged) # NOTE: # If there are overlapping keys, the keys from the first dictionary will be overwritten.
7e14676a28e7c764f566e3a74539ed6e8e8f282b
gabrielos307/cursoPythonIntersemestral17-2
/Básico/ProgramaciónFuncional/recursion.py
424
4
4
###### #Recursion ###### def factorial(num): if num<1: return 1 else: return num*factorial(num-1) #print(factorial(5)) ##### # Iteracion ##### def factorial2(num): fack=1 for i in range(2,num+1): fack*=i return fack #print(factorial2(5)) ###### #Map ##### items = list(range(1...
7d94ac2d577d301eaff7eafc052476ed630d64ae
SandeepShewalkar/Demonstrations
/Python/generator.py
835
3.890625
4
# A simple generator function def my_gen(): n = 1 print('This is printed first') # Generator function contains yield statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n def rev_str(my_str): length = len(my_str) ...
6eb18f2ef10d9558abb045595b5bfc1b9fd8f4d6
pyplusplusMF/202110_44
/_44semana06clase18Matplotlib.py
3,158
3.609375
4
# clase martes 8 de junio import matplotlib.pyplot as plt def ejemplo1(): # grupo A x1=[2,5,6,14] y1= [11,22,33,44] # grupo B x2=[2,5,6,15] y2=[4,12,18,45] #Graficar 2 lineas en la misma grid plt.plot(x1,y1, color="blue", linewidth = 3, label = 'Linea 1') plt.plot(x2,y2, color="green", linewidth ...
6841b32c92e75fbf3237549a83a508ba03d87716
swell1009/ex
/ForKids/appendixb/ch11-octagon.py
138
3.84375
4
import turtle t = turtle.Pen() def octagon(size): for x in range(1, 9): t.forward(size) t.right(45) octagon(100)
cdb70923c9882e7b8d52bfeffb2fe41673b9be9b
AmeyaChavre/py-01-rep
/Spreadsheets and PDFs/csv_data_extrct.py
1,121
3.90625
4
import csv open_file = open("C:\\Users\\User-PC\\Desktop\\example.csv",encoding="utf-8") csv_data = csv.reader(open_file) extracted_data = list(csv_data) print(f"Extracted Data : {extracted_data}\n") print(f"Number of rows in the spreadsheet : {len(extracted_data)-1}\n") print("List of Columns:\n") column_count=0 f...
2927ee0097dec28d5bc943467f4cb2ab8bc2cff3
pyaiveoleg/semester_4_python
/homeworks/homework_1/task_2/tail.py
742
3.859375
4
import argparse from typing import List def print_tail(file_names: List[str], rows_number: int = 10): print_file_name = len(file_names) > 1 for file_name in file_names: try: with open(file_name) as f: if print_file_name: print(f"==> {file_name} <==") ...
148dc9af09011a332be81b4b788b99c0605b29a4
MilindShingote/Python-Assignments
/Assignment6_1.py
354
3.65625
4
class Demo: Value=10; def __init__(self,Value1,Value2): self.No1=Value1; self.No2=Value1; def Fun(self): print(self.No1); print(self.No2); def Gun(self): print(self.No1); print(self.No2); def main(): obj1=Demo(11,21); obj2=Demo(51,101); obj1.Fun(); obj2.Fun(); obj1.Gun(); obj2.Gun(); i...
e652c9f1128135fe711a463b49f5597da6ec548e
ranguisheng/python_test_project
/test/itertest.py
1,372
3.546875
4
#!/usr/bin/env python3 #-*- coding:utf-8 -*- ''' iter test @author: Micahel Ran ''' import itertools import struct import hashlib # na=itertools.count(1) # na=itertools.cycle('ABC') na=itertools.repeat('A',10) for n in na: print(n) natuals = itertools.count(1) ns=itertools.takewhile(lambda x:x<=10,natuals) print(li...
424c2b61704004f75119bffd0732a0d5d9f86238
chidieberex/cfo-thinkcspy3-python
/numbers in the list-squares-total sum-total multiplication.py
668
3.65625
4
''' # 3.8 Exercises, number 5a: xs = [12, 10, 32, 3, 66, 17, 42, 99, 20] for c in xs: ca = str(c) + " is one of the numbers in the list." print(ca) ''' ''' # 3.8 Exercises; number 5b: xs = [12, 10, 32, 3, 66, 17, 42, 99, 20] for c in xs: ca = str( c) + " is one of the numbers in the list and it...
1cbe8ddb71242a8a573d8aabcc08218a308c49a5
jntushar/leetcode
/1047. Remove All Adjacent Duplicates In String.py
659
3.8125
4
""" Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. ""...
d6a5071a1a7791e46d8730bfb8418c83df18498e
mkzia/eas503
/old/spring2020/week7/oop_example2.py
1,644
3.734375
4
# Create a Person class with first name and last name # Create a Student class that inherits from person name # and adds credit_hours and q_point # The Person class should define __repr__ function # The student class must define get_gpa() # Read from data.tsv each line and create a student object and # store it in a l...
1db308270debf19d1acb7f3a6a8d594b7cdd6ac2
kaiCbs/pycookbook
/Chapter8/8.13.implementing_a_data_model_or_type_system.py
2,061
3.65625
4
class Descriptor: def __init__(self, name=None, **opts): self.name = name for key, val in opts.items(): setattr(self, key, val) def __set__(self, instance, value): instance.__dict__[self.name] = value class Typed(Descriptor): expected_type = type(None) def __set__...
f32428eb6c59c9e627541b0dc007c335aa3f8d22
Vykstorm/numpy-examples
/creation.py
2,184
4.21875
4
''' This script shows different ways to create an numpy ndarray object ''' import numpy as np if __name__ == '__main__': # Create an array from a iterable np.array([3,1,4,1,5]) # dtype is guessed from value types np.array([3,1,4,1,5], dtype=np.float64) # dtype can be specified as an argument. # Yo...
1e1a71968beb46b216cefc57af3bd7f83a446b20
diegotbl/Exercicios-How-to-Think-Like-a-Computer-Scientist
/Aula 2/Exercicio6.9.17.py
753
4.0625
4
import sys def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def is_multiple(a, b)...
d66326197f6de84d2dfea0f82c61552371da39f8
duanzhihong/python--language
/algorithm/bucketSort.py
287
3.828125
4
#桶排序 def bucketSort(arr): newArr = [0]*len(arr) # print(newArr) result =[] for i in range(len(arr)): newArr[arr[i]] += 1 for j in range(len(arr)): result += [j]*newArr[j] print(result) arr = [5,3,6,1,2,7,5,4] bucketSort(arr) # print(result)
55d1127e6c17fe1d177aca515b287c84412b6329
erbaowu/spider
/test1.py
5,774
3.765625
4
#判断字符串是否是整数、浮点数、复数 '''def isNum(str): print(isinstance(str,(int,float,complex)))''' #判断是否是质数 '''def isPrime(i): l=[] for x in range(2,i): if i%x==0: l.append(x) if len(l)==0: print(True) else: print(False) isPrime(24)''' #编写函数计算传入的数字、字母、空格和其他字符的个数 '''def counts(st...
2ac48c536296fb31ee5ec5856cae6c6ed56d7970
ilkerthegeek/binary_search_compareTo_NaiveSearch
/main.py
1,771
4.3125
4
# implementation of binary search algorithm # I will prove that binary search is faster than naive search # Naive search basically search every index iteratively and ask if it is equal to target value # if array consists the value it returns # if it is not in the array it returns -1 import random import time def nai...
9bfb65def6f62f01e66babcb2533f041769c0777
HelloFranker/CS-Algorithms
/Recursive/sum.py
476
3.796875
4
# 数组求和的递归方法 # 如果列表为空,返回0 # 如果列表不为空,计算列表中第一个数字+数组中剩余其他的数字组成的数组 def sum_iter(lst): if not lst:# 列表为空 return 0 else:# 列表不为空 return lst.pop(0)+sum_iter(lst) l=[1,2,3,4,5,6] print(sum_iter(l)) # 更简洁的写法 def sum(lst): if lst == []: return 0 return lst[0]+sum(lst[1:]) l2=[1,2,3,4,5,6...
e5e2a52448c987abc55a0c65b9922b85bbdec091
gameboy1024/ProjectEuler
/src/lib/math_utils.py
4,424
3.796875
4
import math ################################################################################ # Basic operations ################################################################################ def is_even(n): return n % 2 == 0 def is_square(n): root = math.sqrt(n) return root == int(root) def is_palindrome(...
3a84883cd14817b44d2415370ccc6f109d47424a
WonyJeong/algorithm-study
/koalakid1/If/bj-9498.py
151
3.53125
4
import sys input = sys.stdin.readline n = int(input()) print(n >= 90 and "A" or n >= 80 and "B" or n >= 70 and "C" or n >= 60 and "D" or "F")
1fa093c69932f2b28279b0ec22b4bf551fc08a64
learnerofmuses/slotMachine
/152Spr13/testp3.py
387
3.890625
4
def guess(my_list): count = 0 sum = 0 new = [] for i in my_list: if(i % 3 == 0): count = count+1 sum = sum + i new.append(i) if(i % 2 == 0): print("invalid input") else: average = float(sum)/count return sum, average, new def main(): my_list = [3, 6, 5, 7, 2, 45, 12, 9, 24, 27, 33] su...
da3b4e36b02d7e78bf084af4ff1e932f08405a47
alaindet/learn-python
/courses/bootcamp_udemy/02-strings/string_methods.py
1,342
4.375
4
# This displays all the methods for strings print(dir(str)) # Currently prints 81 methods! # This displays an help about the given method help(str.replace) # replace(self, old, new, count=-1, /) # Return a copy with all occurrences of substring old replaced by new. # # count # Maximum number of ...
d1573c044b84608538aff708588a9547ee17901f
kfei/code2html
/code2html/util.py
4,228
3.5
4
# -*- coding: utf-8 -*- import sys import re import os import platform from os.path import expanduser, isfile, isdir, exists, normcase, join import glob from shutil import rmtree from fnmatch import fnmatch def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answe...
ce740060323f833d882d4f4d009f85fb564d705e
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/43.5. enum/figures.py
268
3.578125
4
import math def area_of_square(a): return a * a def area_of_rectangle(a, b): return a * b def area_of_circle(r): return math.pi * r ** 2 def area_of_triangle(a, h): return 0.5 * a * h def area_of_trapeze(a, b, h): return (a + b) / 2 * h
b634aba393315a149b2fe7df7e021d7aa00799f7
mandelina/algorithm
/baek_2675_문자열 반복.py
152
3.515625
4
n=int(input()) for i in range(0,n): n,s=input().split() n=int(n) for j in range(0,len(s)): print(n*s[j],end="") print(end="\n")
2977283067bca4b05c4da030dba74083b3a328ff
pfiaux/PythonChallenge
/level3.py
396
3.65625
4
# Python Challenge Level 3 # http://www.pythonchallenge.com/pc/def/equality.html # use Reg exp to tryyy import re inputfile = open("./level3_data.txt") data = "" #for line in inputfile: # data = data + line.strip() pattern = "[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]" matches = re.findall(pattern, inputfile.read()) count ...
6e087a96e591402522cc1d3207686c96e9b4cf99
szhmery/leetcode
/Offer/Offer21-OddBeforeEven.py
793
3.59375
4
from typing import List class Solution: # two pointers def exchange(self, nums: List[int]) -> List[int]: left, right = 0, len(nums) - 1 while left <= right: while left <= right and nums[left] % 2 == 1: left += 1 while left <= right and nums[right] % 2 ==...
4a71aefcabfc34206d7c2a8a379fef14bdc5c8a8
chyt123/cosmos
/coding_everyday/lc500+/lc836/RectangleOverlap.py
762
4.03125
4
from typing import List class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: # - - | | if rec1[0] == rec1[2] or rec1[1] == rec1[3] or rec2[0] == rec2[2] or rec2[1] == rec2[3]: return False line1 = [rec1[1], rec1[3], rec1[0], rec1[2]] l...
667f43f7f74b4735843e24cc47b0f0a793c6a7b8
kyletau67/tauK
/03_occupation/portendGreatness_tangM-tauK.py
1,294
3.5
4
#Portends Greatness -- Michelle Tang and Kyle Tau #SoftDev1 pd 6 #K06 -- StI/O: Divine your Destiny! #2018-09-13 import csv import random file = open("occupations.csv", "r") #open and read the file occupations = file.readlines() #lines of the file are put into the list, occupations file.close() #close the file since...
9d27515483c4ac217fc7d75da3e87bc484c4943d
ChandraSiva11/sony-presamplecode
/tasks/final_tasks/math/23.prime_no.py
290
4.1875
4
# Python Program to Check if a Number is a Prime Number def main(): num = 13 flag = 0 for i in range(2, num): if num % i == 0 : flag += 1 if flag == 0: print(num, "Number is a prime number") else: print(num, "Number is not a prime number") if __name__ == '__main__': main()
957e20c26555c98cbb87e4fd7371edbfa8b81ef6
hideyk/Challenges
/leetcode/26. diagonalSum/diagonalSum.py
261
3.5625
4
from typing import List def diagonalSum(mat: List[List[int]]) -> int: size = len(mat) sum = 0 for i in range(size): sum += mat[i][i] sum += mat[i][size-1-i] if size % 2 == 1: sum -= mat[size//2][size//2] return sum
3be371e620261cb9874190eafe9004fe2bc4a319
butterfly1of4/python_CLI_project
/lib/main.py
4,600
3.671875
4
from peewee import * from models import Contacts on = True while on == True: print("-----------------------------------------------------") print("***** My Contacts: *****") def intro(): print("\nPlease choose from the following menu options: \n") print("--------------------------------...
90ceed1beb564980fe57ee96c87d60616fa6636d
Blackdevil132/MachineLearning
/src/qrl/Qtable.py
1,542
3.59375
4
import pickle class Qtable: """ base class for qtables contains save/store functions get/update have to be overridden if qtable has multi dimensional format """ def __init__(self): self.table = {} def fromFile(self, path): """ Loads QTable from given Path :...
54f473e64fd5ce2e3096181ad6cdb83db3f6f910
SrikarValluri/Software_Engineering_2
/hw7/q2_test.py
432
3.5
4
import unittest from q2 import leapyear class TestCase(unittest.TestCase): def test1(self): self.assertEqual(leapyear(2000), "Leap Year") def test2(self): self.assertEqual(leapyear(100), "Not Leap Year") def test3(self): self.assertEqual(leapyear(2320349), "Not Leap Year") def ...
cb782b84104a2f6a37573982b28083f70bb977d3
SandeepDevrari/py_code
/py_ds/examplebinarytree.py
3,835
4.28125
4
##this is an implementation of Tree in python3 ## Node class class node: def __init__(self,item): self.data=item; self.L=None; self.R=None; ##Tree class class binary_tree: def __init__(self,items): if items==None: print("No Tree!!"); else: i=0; ...
15b5a0a9d557b7bb82016088e9294a4ace70afd6
MarinaFirefly/Python_homeworks
/OOP5/models/interview19.py
929
3.5
4
import datetime class Interview: def __init__(self,vacancy,programmer,recruiter,candidate,dt,feedback,result): self.vacancy = vacancy self.programmer = programmer self.recruiter = recruiter self.candidate = candidate self.dt = dt self.feedback = feedback sel...
fe699b780310ec113b02ade88f0504dae45cc2cc
GraceSnow/GraceSnow.github.io
/story.py
1,972
4.21875
4
startstory = ''' You wake up one morning and find that you aren’t in your bed; you aren’t even in your room. You’re in the middle of a giant maze. A sign is hanging from the ivy: “You have one hour. Don’t touch the walls.” There is a hallway to your right and to your left. Type 'left' to go left or 'right' to go right...
0666f9c21ff16b21254e83d536818f8980ef23c7
francoislegac/algorithms
/maze_puzzle.py
4,720
4.40625
4
import copy import math # This class is used to store the idea of a point in the maze and linking it to other points to create a path. class Point: def __init__(self, x=0, y=0): self.x = x self.y = y self.parent = None self.cost = math.inf def set_parent(self, p): self...
8d0bfe0c06601b7543275ad0f6ea2df564aec199
pfletcherhill/LING-227
/Assignment1/sample.py
902
4.375
4
# this is a command line version of fib # import sys to make command line arguments accessible import sys # The following is a multiline comment ''' store first argument as 'num', first check that user provided a number if not, exit gracefully ''' try: num = int(sys.argv[1]) except ValueError: print "Please...
21f5c7232f5be6fe0dd59e18dc5c09a8e7b1e95d
NidhinAnisham/PythonAssignments
/pes-python-assignments-2x-master/FilePackage/52.py
126
3.53125
4
for line in reversed(open("example.txt").readlines()): print line.rstrip() fo = open("example.txt").read() print fo[::-1]
e8a45317a45d64456f1de9442d68f3c5c031bf7e
shivani-tomar/Data_stuctures_with_python
/sorting/bubble.py
644
3.9375
4
class Bubble: def __init__(self, lists): print("this is bubble sort example") self.lists = lists def bubble(self): size = len(self.lists) print(self.lists , size) swapcount =0; for i in range(size): for j in range(size-i-1): if self.lis...
264fe720afe1d84aec32cac207dc8bb2501e00ab
1054/Crab.Toolkit.michi2
/test/test_py_copy/test_py_copy.py
617
3.71875
4
#!/usr/bin/env python import numpy as np from copy import copy, deepcopy aa = [] a = {'var':np.array([1,1]),} aa.append(a) b = copy(a) b['var'] += np.array([1,1]) print(a, b) # a value changed aa = [] a = {'var':np.array([1,1]),} aa.append(a) b = copy(aa[0]) b['var'] += np.array([2,2]) print(a, b) # a value ch...
6a44635d136d3b511059097710bac41fe344c306
MarsWilliams/PythonExercises
/practiceProblems/check_braces.py
1,268
3.53125
4
def check_braces(expressions): l = len(expressions) braces = { 'curly': { "}": "cr", "{": "cl", "count": 0 }, 'paren': { ")": "pr", "(": "pl", "count": 0 }, 'square': { "]": "cr"...
02e0388d289b6192c98ca47187a2bdaaa6eb9cc9
hanjiuz/MyPython
/flashcard.py
910
3.921875
4
#sys is a module. it let us access command line arguments through sys.argv. import sys import random #print(sys.argv) if len(sys.argv) < 2: print("Please supply a flashcard file.") exit(1) flashcard_filename = sys.argv[1] f = open(flashcard_filename, "r") question_dict = {} for line in f: entry = line.st...
b61f1ca485b107a8a6e69ae113a43d89dbc6d458
zyyxydwl/Python-Learning
/1-基础/eatPeach.py
1,122
3.765625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2018/1/1 17:55 # @Author : zhouyuyao # @File : eatPeach.py # 2. 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半, # 还不瘾,又多吃了一个,第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 # 以后每天早上都吃了前一天剩下的一半零一个。 # 到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 # 程序分析:采取逆向思维的方法,从后往前推断。 n=1 #'''定义第9天有n个桃''' for day in ...
8adec887b2f1dfca36b8abfef7c343b5bc32d1b5
aronnax77/python_uploads
/tutor2.py
1,342
3.5625
4
#!/usr/bin/python3 ############################################################################################# # # # PLEASE NOTE THAT THIS CODE WILL NOT RUN IN THE SOLOLEARN CODE PLAYGROUND. # # ...
c1d4df20e85c94d283c478f40d1b2174c419132f
rachelktyjohnson/treehouse-py-project3
/phrasehunter/game.py
2,827
3.609375
4
import time import random from phrasehunter.phrase import Phrase class Game: def __init__(self): self.active_phrase = None self.missed = 0 self.phrases = [ "Knowledge is power", "Whatever you do do it well", "What we think we become", "Turn ...
69376bef591ba742fb38562db388763ca3369229
DevoteamDigitalFactory/code-sharing
/Data_structures/yield_from_example.py
598
3.890625
4
'''A function solving the problem of sums square ie: Can order number from 1 to n so that each consecutive pair sums to a perfect square This example is a DFS using the yield from syntax''' def square_sums(n): squares = {i**2 for i in range(2, math.ceil((2*n-1)**0.5))} def dfs(): if not inp: yield re...
cdef43e3b272fe475b7f6b8cbe801370122d8ff0
ProjectHusky/CoreVal
/database_admin/course_parser.py
8,166
3.53125
4
from selenium import webdriver import csv import configparser def setup_browser(is_headless): """ This methods sets up the browser object that is to be used for parsing. :param is_headless: This boolean value determines whether the browser is displayed as it is browsing. :return: A Google Chrome brow...
d298f7b5f17b5bdf8dbd4ccb0d6b31980ff6644c
bhushanMahajan460/ineuron_assignment
/Assignment_2/assignment_2(b).py
307
4.15625
4
# ASSIGNMENT_2-B # REVERSE THE INPUT STRING l = input("-> Enter the string : ") # TAKE THE INPUT reverse=l[::-1] # FUNCTION USED TO REVERSE THE STRING print("-> Reversed String : {}".format(reverse)) # PRINT THR REVERSE STRING
c681a26e9e3cecf37ea5bb146460de83b5347c68
wangpengfeido/MyLearn3
/LearnPython/010基础/030函数/030函数的参数/075参数组合.py
291
3.65625
4
# 任意函数都可以使用func(*args, **kw)的形式调用 # 函数调用的 * 和 ** 语法相当于将数组/元组和dict解构为参数 def f1(a, b=1, *c, **d): print(a, b, c, d) f1(*(1, 2,), **{'d': 3}) def f2(a, b=1, *c, d): print(a, b, c, d) f2(*(1, 2,), **{'d': 3})
b307187c5d292800d17929aa742b7616d07c0c7b
tianyu0901/code_basket
/algorithm/factorial.py
798
3.578125
4
# encoding: utf-8 # 输入整数求阶乘末尾的0的个数 # 输入为一行,n(1 ≤ n ≤ 1000) # 解法:要判断末尾有几个0就是判断可以整除几次10。 # 10的因子有5和2,而在0~9之间5的倍数只有一个, # 2的倍数相对较多,所以本题也就转换成了求N阶乘中有几个5的倍数。 # 也就是每多出来一个5,阶乘末尾就会多出来一个0, # 这样n / 5就能统计完第一层5的个数,依次处理,就能统计出来所有5的个数。 # 如65 除以5 = 13, 25算两个5, 50算两个5,...,125 = 5*5*5 算三个5 import math if __name__ == '__main__': n = i...
8c37b5d1b2297d2c0d4ee1e6cc7a97d0652e25b7
Rogerio-ojr/EstudosPython
/Exercicio28.py
227
3.703125
4
from random import randint, randrange from time import sleep n = int(input("Qual o numero? ")) numSorteado = randrange(5) print('PROCESSANDO...') sleep(2) print(f'Você Ganhou!') if n == numSorteado else print(f'Você Perdeu!')