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
54785e654145533309b1197a6f17aea09a8d7b28
go1227/PythonLinkedLists
/DoubleLinkedList.py
1,655
4.1875
4
__author__ = "Gil Ortiz" __version__ = "1.0" __date_last_modification__ = "4/7/2019" __python_version__ = "3" #Double Linked List class Node: def __init__(self, data, prev, next): self.data = data self.prev = prev self.next = next class DoubleList: head = None tail = None d...
56bfaaa56ffb54a986b9d7ea862cb670405b785e
carloslorenzovilla/21NumberGame
/main.py
2,291
4.34375
4
""" Created on Sun Jul 14 10:17:48 2019 @author: Carlos Villa """ import numpy as np # This game is a take on a 21 Card Trick. 21 numbers are randomly placed # in a 7x3 matrix. The player thinks of a number and enters the column that # the number is in. This step is repeated three times. Finally, the number # that t...
9401fcb0d84dcd23fc22a91bbf5c676b799085b6
Waterdrips/shop-coding-test
/test/test_percentage_discount.py
4,397
3.578125
4
import unittest from typing import * from goods.apples import Apples from goods.bread import Bread from goods.shop_item import ShopItem from goods.soup import Soup from offers.percentage_offer import PercentageOffer class TestPercentageOffer(unittest.TestCase): @staticmethod def count_items_of_type(basket: L...
978b7eb7f78f53400d8b9678293b57b7b3c08eb9
levietanh0001/pp2021
/pw5/pw4/domains/Engine.py
13,014
3.796875
4
import input import output import curses class Engine: # List students to store student objects students = [] # List students_id to store students id, so that we can fetch id more easily afterwards students_id = [] # List courses to store course objects courses = [] # List courses_id to st...
67902ff2860bfd45f93f0ea85678be0e62d82206
vm356jo3/104-2_Python
/A1023336_ch4_hw2.py
586
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import random t=1 answer=random.randint(1,99) num=[1, answer, 99] print u'終極密碼, Start!!!' print u'請輸入你猜的數字>>' guess=input() while guess!=answer: if answer<guess: t=t+1 print u'現在範圍是%d~%d' %(num[0], guess) num[2]=guess print u'請輸入你猜的數字>>' guess=input() if guess<a...
f7e6ef2007bcea37aa7aa2d7ba71a125b0bde471
yulyzulu/holbertonschool-web_back_end
/0x00-python_variable_annotations/7-to_kv.py
442
4.15625
4
#!/usr/bin/env python3 """Complex types""" from typing import Tuple, Union def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]: """ type-annotated function to_kv that takes a string k and an int OR float v as arguments and returns a tuple. The first element of the tuple is the string k. ...
386e978004ab932c24a13558789b1dfd78721547
kimbim/Bio4
/python/acs.py
1,557
3.5
4
from ant import Ant from graph import Graph from node import Node class Acs: def __init__(self, problem): self.problem = problem self.numberOfAnts = 100 self.generations = 100 self.generationNumber = 0 self.ants = [] self.graph = Graph(self.problem) for i in range (1,self.numberOfAnts+2): #Iterate x...
5e1816ef1384ba6d66df4cd9639bbcd08a4e4805
jaeheon-lee/pre-education
/quiz/pre_python_02.py
1,010
4.15625
4
""""2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오 예시 <입력> 첫 번째 수를 입력하세요 : 10 두 번째 수를 입력하세요 : 15 어떤 연산을 하실 건가요? : * <출력> 150 """ def calculator(a,b,c): if c == '*': print(a*b) elif c =='/': if b == 0: print('0으로 나눌 수 없습니다.') b= int(input('두 번째 수를 입력하세요.:')) ...
81534ce25473b7346bd2d9881de45131f3982a98
Spiderjockey02/CodeSnippets-Python
/files/iterative_factorial.py
190
4.15625
4
def factorial(n): res=1 if n<2: return res for i in range(2,n+1): res*=i return res print(factorial(int(input("Enter the Number Whose Factorial You Need:"))))
bda4bef8411621571549deb15d4cc4ee32b684ef
Spiderjockey02/CodeSnippets-Python
/files/Hangman-CLI/game.py
2,531
3.953125
4
import random f = open('./nounlist.txt', 'r') words_list = f.read().splitlines() f.close() words_len = len(words_list) - 1 # minus one to prevent IndexError def get_word(): # assuming this is a HUGE array, using random.randint is better than random.choice return words_list[random.randint(0, words_len)].lower...
b11db17156b6c51b534939bc498157fcf836953d
Spiderjockey02/CodeSnippets-Python
/files/join-lists.py
986
3.734375
4
list1 = ["apple", "pear", "orange", "peach"] list2 = ["pineapple", "watermelon", "grapefruit"] list3 = ["strawberry", "banana", "lemon"] range1 = range(5, 9) joined1 = list1 + list2 joined2 = list1 + list2 + list3 print(joined1) #['apple', 'pear', 'orange', 'peach', 'pineapple', 'watermelon', 'grapefruit'] print(join...
75984ce68b85c5a1b20e89c25f1425ad336eb1f8
marikelo12/geekbrains_python
/lesson_5/hw_5_1.py
325
3.625
4
with open("text_5_1.txt", "w") as my_obj: line = input('Вводите текст: ') while line: my_obj.writelines(line + "\n") line = input('Вводите текст: ') if not line: break with open("text_5_1.txt") as my_obj: for element in my_obj: print(element)
ebf469444dfd33a3fef35c470675e45a4ffbd182
marikelo12/geekbrains_python
/lesson_8/hw_8_3.py
581
3.609375
4
class NewException(Exception): def __init__(self, *args, **kwargs): self.text = args[0] def division(x): if not x.isdigit(): raise NewException('Введено не число', [1, 2, 3]) return x my_list = [] my_str = '' while 'stop' not in my_str: try: my_str = input('Введите число или "...
1ec12a31f0e38ec1cc7287b6973b47ed40eb1491
marikelo12/geekbrains_python
/lesson_2/hw_2_4.py
146
3.5
4
my_str=str(input("Введит строку: ")) my_list=list(my_str.split( )) for x,el in enumerate(my_list,1): print(f"{x}. {el[0:10]}")
6583eb5f58a2470d91317b0c78e163e547bdb8ca
marikelo12/geekbrains_python
/lesson_3/hw_3_5.py
413
3.71875
4
sum_res = 0 x = True while x: element = input('Введите числа или $ для выхода: ').split() res = 0 for el in range(len(element)): if element[el] == "$": x = False else: res = res + int(element[el]) sum_res = sum_res + res print(f'Промежуточная сумма: {sum_res}'...
e8ea9b554296b81a85172cf54965b6d214e09a7b
ellyluan/edX
/Introduction to Computer Science and Programming Using Python/L3 Simple Algorithms/L3_template.py
6,532
4.3125
4
# coding: utf-8 # #Introduction to Computer Science and Programming Using Python # ##Simple Algorithms # ###Problem 1 # In[1]: num = 0 while num <= 5: print num num += 1 print "Outside of loop" print num # In[2]: num = 10 while True: if num < 7: print 'Breaking out of loop' break ...
577fdb87b53af5c288fe1fda17035afaea23d082
boyko11/DinosaurIsland_DLAI
/data_service.py
748
3.515625
4
import pprint class DataService: def __init__(self): pass @staticmethod def get_data(): data = open('data/dinos.txt', 'r').read() data = data.lower() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print('There are %d total character...
85edbde9b9be87dd48fb94f83cc8a1a930112d42
giridhersadineni/pythonsrec
/02.Operators & Conditional Statements/if_demo_2.py
161
4.0625
4
a=int(input("Enter a Number")) b=int(input("Enter another Number")) if a>b: print(a,"is the greatest number") else: print(b,"is the greatest number")
471541bc0844c48633d5867cb927f42a90f8feb9
giridhersadineni/pythonsrec
/10. Modules, PIP & PyPI/mathlib/gen.py
190
3.890625
4
def sqaure(n): ''' Arguments: n => Number Mandatory Returns the square of the number passed to it ''' return n*n def cube(n): return n*n*n PI=22/7
488026f2e1903f5893f0ff2c03167cfc8ccb6337
giridhersadineni/pythonsrec
/06.Lists & Tuples/listaccess.py
160
3.703125
4
i=0 numbers=[x for x in range(100)] for i in numbers: print(i) i=0 numbers=[x for x in range(100)] while(i<len(numbers)): print(list[i]) i=i+1
50d6de4f5b517594862e256ee165050cb30aaa6e
giridhersadineni/pythonsrec
/12. Classes & Objects/sis.py
1,309
4.09375
4
class student: ''' This represents student data ''' name="" fathername="" rollno=0 marks=[] __total=0 average=0 def __init__(self,rollno,name): self.rollno=rollno self.name=name self.get_details() def calculate(self): for i ...
340f5d3c5f96375b61ac3b8e53ac3894663a1ddd
giridhersadineni/pythonsrec
/06.Lists & Tuples/loop.n.py
53
3.515625
4
list=['10','12','13,'11'] for i in list: print(i)
8c4ce54c462db5ecab3b4a6a2c4f71fd60b84a78
giridhersadineni/pythonsrec
/09. File Handling/task1.py
347
3.953125
4
filename=input("Enter the name of the file you want to read") fr=open(filename,"r") ch="" # def readline(FileReader): # line="" # ch="" # while ch != '\n': # ch=FileReader.read(1) # line=line+ch # return line # for i in range(10): # print(readline(fr),end="") for l...
db57f17d5037be0cfe4afae8854a5e51d888c01f
brucebannerme/secret
/secret.py3
316
3.75
4
import os import sys #fill the path of the downloaded folder to know the answer. #"path to the file" path = r" " def rename_files(): file_list = os.listdir(path) os.chdir(path) for file_name in file_list: os.rename(file_name , file_name.translate(None, "0123456789")) print(file_name) rename_files()
ef2652d5c235359b045f41e5a95f1e9a81e6fb41
svenJonis138/Project_3_Artwork_Catalog
/artwork_db.py
4,515
4.0625
4
import sqlite3 import artist from artwork import Artwork from config import db_path """This module holds all database code""" def create_tables(): """create the artwork table""" with sqlite3.connect(db_path) as conn: print(db_path) conn.execute('CREATE TABLE IF NOT EXISTS artwork ' ...
8df4d2f5c97560d274da6a748509d65175d6b90c
je-castelan/Algorithms_Python
/Python_50_questions/4 Slicing window/sliding_window.py
1,706
3.515625
4
import random def max_k_sum_force_brute(arr,k): # We can check on samples than complexity timer is O(n*k + k) -> O(n*k). n = arr's length pasos = 0 maxsum = -99999 for i in range(len(arr)+1-k): tempsum = 0 for j in range(i,i+k): tempsum += arr[j] pasos += 1 ...
d4d47e92f11fbac4d36867562b0616dd8fad565e
je-castelan/Algorithms_Python
/Python_50_questions/10 LinkedList/merge_sorted_list.py
1,009
4.1875
4
""" Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. """ from single_list import Node def mergeTwoLists(l1, l2): newList = Node(0,None) pos = newList while (l1 and l2): if l1.value < l2.value: ...
42ea8bfbfab0cda471b19eb65d3981a235888341
je-castelan/Algorithms_Python
/Python_50_questions/19 Tree Graphs/max_path_sum.py
1,457
4.125
4
""" A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given th...
aa33bd7b65796080567459b2873e9155d8c02070
je-castelan/Algorithms_Python
/Leetcode/roman_to_integer.py
3,075
3.6875
4
# https://leetcode.com/problems/roman-to-integer/ # Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. # Solucion O(n) class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ romanos = {"I": 1...
15bd5c4f7a9d8a01178d63e038a01a873e3759b8
je-castelan/Algorithms_Python
/Python_50_questions/13 Graphs/undirected_graph_matrix.py
806
3.828125
4
""" Directed Graph Implementation using Matrix """ from collections import defaultdict class Graph: def __init__(self, size): self.size = size + 1 self.graph = self.graph = [[0 for x in range(size+1)] for y in range(size+1)] def insertEdge(self, x, y): if...
5b18902dcc5b1022521d4525b0bc326eb2e1d7b7
je-castelan/Algorithms_Python
/Python_50_questions/13 Graphs/undirected_graph_list.py
592
3.890625
4
""" Directed Graph Implementation using List """ from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def insertEdge(self, value1, value2): self.graph[value1].append(value2) self.graph[value2].append(value1) def printGraph(self):...
7d5ae8459c8de401a58d1682a42038680b4e0431
je-castelan/Algorithms_Python
/Python_50_questions/8 Hash tables Maps/lru_cache.py
3,509
4.125
4
""" Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Up...
e0ab7d1a6480364656894d4a5e206da451cea4e0
EgbieAndersonUku1/multipleZipFileExtractor
/un_zipper.py
8,374
3.59375
4
#!/usr/bin/python ################################################################################ # # Created By : Egbie Uku # Name Of The Program : Unzipper.Py # Created on the 20/05/2016 at 15:08:15 hrs # This is version : 2 # Updated on 15th of June 2016 # # # File description # # A command line script that co...
1da7d9af3efebb92519d6fffe9d030811c83691d
engmwm/marleendetector
/MarleenDetector/src/marleendetector/pyfaces/imageops.py
1,147
3.859375
4
import Image class XImage: """ This class represents an Image """ def __init__(self, filename): """ Reads an image from a file @param filename: path to an image """ self._readImage(filename) def _readImage(self, fname):...
de930837bd62444f559dbbd731e30a47263a96a1
pythonwins/PracticingPython
/RPStime.py
1,184
4
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 25 16:15:44 2018 @author: dhoop """ import sys player1 = input("Enter Player 1's Name: ") player2 = input("Enter Player 2's Name: ") player1_choice = input("Rock, Paper, or Scissors %s? " % player1) player2_choice = input("Rock, Paper, or Scissors %s? " % pl...
d83f7a58c718d02c806e8180e4047219f9a213ca
vrbloke-minor/minor-old
/Python/CodeBat/Excercise9.py
87
3.578125
4
#not_string def not_string(str): return str if str[0:3] == "not" else "not " + str
bae2e5987593f2dc2240e17ad76fd870beaef0fc
NetoTravizan/classifier
/src/distance_calculator.py
1,177
3.9375
4
import math def euclidean_distance(train_data, test_data): print("Deve retornar a matriz de distancia entre o vetor de teste e o de treinamento"); print("Quantidade de linhas: tamanho do vetor de teste"); print("Quantidade de colunas: tamanho do vetor de treinamento"); numberColumns = len(train_data[0]) # Calcula...
6c8974807d165228b8465c8fbf0f469b7d6ac8c6
dmoncada/python-playground
/stack.py
1,359
4.1875
4
class Stack: '''A simple, generic stack data structure.''' class StackNode: def __init__(self, item, next_node): self.item = item self.next = next_node class EmptyStackException(Exception): pass def __init__(self): '''Initializes self.''' self....
9bf226e11166b7a5117d0db51895b133bbc63618
sreekurulez/mypythonscripts
/LargestNumberMadeFromAList.py
415
3.890625
4
def create_largest_number(number_list): number_list.sort() number_list.reverse() print(number_list) temp ='' for i in number_list: temp += str(i) largest_number =int(temp) return largest_number #remove pass and write your logic here ...
6d551f973ad42fd4e99d397b323fbe5690c09c56
MayowaFunmi/Algorithm-Problem-Solutions
/string_validator.py
1,862
3.953125
4
''' s = input() def func(s): for i in range(len(s)): if s[i].isalnum(): return True break return False def func2(s): for i in range(len(s)): if s[i].isalpha(): return True break return False def func3(s): for i in range(len(s)...
54cc838da2ca514f104a118fcc1e536d10528482
MayowaFunmi/Algorithm-Problem-Solutions
/nestedList2.py
576
3.6875
4
list = [["yes", 5.87], ["me", 2.29], ["them", 4.55], ["him", 0.34], ["she", 2.29], ["our", 4.55]] names = [] scores = [] arranged = [] unique = [] my_dict = {} for i in list: names.append(i[0]) scores.append(i[1]) arranged.append(i[1]) arranged.sort() my_dict[i[0]] = i[1] # names as keys and sco...
482a4a41afe081d99083c6c3637438e1b1d4a320
MayowaFunmi/Algorithm-Problem-Solutions
/nestedList_32.py
463
3.96875
4
dic = {} s = list() for _ in range(int(input("Enter number of students: "))): name = input("Enter name of student: ") score = float(input("Enter score of student: ")) if score in dic: dic[score].append(name) else: dic[score] = [name] print(dic) print() if score not ...
b8e55ec74dbbb410f937d1d180f5aa45c38ff658
MayowaFunmi/Algorithm-Problem-Solutions
/string_formatting1.py
532
3.96875
4
#String Formatting in Python - Hacker Rank Solution def print_formatted(number): # your code goes here # String Formatting in Python - Hacker Rank Solution START for i in range(1,number+1): binlen = len(str(bin(number))) octf = oct(i).split('o') hexf = hex(i).split('x') binf ...
dc8e2629cde401c54da102cf390fe8a43c5e00b3
MayowaFunmi/Algorithm-Problem-Solutions
/CountDigits.py
522
4.0625
4
n=int(input("Enter number:")) count=0 while(n>0): count=count+1 n=n//10 print("The number of digits in the number are:",count) ''' Program Explanation 1. User must first enter the value of the integer and store it in a variable. 2. The while loop is used and the last digit of the number is obtained by using th...
ead33f28ee5a34a377e3a6d75590cfee1e131e52
rtfernan/astr-119-hw-1
/if_else_control.py
485
3.8125
4
#define a function def flow_control(k): #define a string based on the value of k if(k==0): s="variable k=%d equals 0." % k elif(k==1): s="variable k=%d equals 1." % k else: s="variable k= %d oes not equal 0 or 1." % k #print the variable print(s) #define a main function def main(): #declare an...
ff0bd95a2f13b6acc85a69a15e652347b6aeab45
YangzlTHU/RNN-Stega
/Huffman_Encoding.py
1,194
3.609375
4
#Huffman Encoding #Tree-Node Type class Node: def __init__(self,freq): self.left = None self.right = None self.father = None self.freq = freq def isLeft(self): return self.father.left == self #create nodes def createNodes(freqs): return [Node(freq) for freq in freqs]...
1e44293dcdfa498e05b765d38e84083c3427a6de
ganeshchand/kathmandu-apache-spark-meetup-introduction-to-spark-2.0
/notebooks/py/wordlen.py
1,458
4.03125
4
#!/usr/env python # this small Spark application reads any texfile and computes the number of words per line and sorts them into an ascending order # It filters out any all empty lines or lines with words == 0 # This is an excercise for me to learn how to write a simple spark app, submit it as an application, and run i...
3d856157db31c3f37054eb2460aae68e5a8888df
amanverasia/crypto-mark2
/encrypter.py
1,139
3.84375
4
#encrypting from random import randint import os zero = False try: g = open("main_data.txt", "r") text = g.read() g.close() except IOError: print("File does not exist, make main_data.txt file first or input text below.\n") text = input('Enter the text you want to convert:\n \n') crypt = '' def random_n(n): ran...
83d72f1ff9e61fd390f9d7d4836dcd8dafac21f6
pangxiong2008/hellopython
/hello.py
1,683
3.53125
4
a=100 if a>100: print(a) else: print(-a) s='i \'m \"ok"' print (s) print('''line1 line2 line3''' ) def is_odd(n): return n%2==1 number=list(filter(is_odd,[1, 2, 4, 5, 6, 9, 10, 15])) print(number) def f(x): return x*x number2=list(map (f,[1,2,3,4])) print(number2) class S...
307d3d02ef80288abf83ae4118be458e9ae6893b
zhao94254/fun
/data_structure/sort/sort.py
2,377
3.765625
4
import time import argparse def log(data: list, sleep: float): print("\r" + ''.join(data), end='', flush=True) time.sleep(sleep) def bubble_sort(data): for i in range(len(data)): for j in range(i): if data[i] < data[j]: data[i], data[j] = data[j], data[i] ...
cf5fbcf08dfd73db222c465534f0b2ebc9343f86
abmestri25/python-basics
/Misc/friendshipcal.py
633
3.953125
4
############################## #Frindship Calculator# ############################## alphabet = 'bcghjklmpqrtvwxyz' score = 0 names = input("Enter the first name ang give space then enter second name : -\n") for character in names: if character in 'aeiou': score+= 5 if character in 'friends': ...
c3e80876544f7fc702992570ae777e14cbecb927
abmestri25/python-basics
/Telusko/OOPS/class.py
364
3.5
4
# Class is blueprint of object in OOPS # From classes we can create objects class Computer: def config(self): print("i5,1TB SSD,16GB") # Object is created comp = Computer() # This is precesural way to access method Computer.config(comp) # This is most preffered way to access method # Accessing the con...
92d724bee672c688ac1627111d1dab7eb1fd7984
abmestri25/python-basics
/Telusko/OOPS/iterator.py
469
3.5625
4
# Construct own iterator class TopTen: def __init__(self): # counter variable self.num = 1 def __iter__(self): return self def __next__(self): if self.num <=10: val = self.num self.num+=1 return val else: raise St...
93a9719616a86b24f8e24bbbc7a9a07aeb63b3c1
abmestri25/python-basics
/Telusko/Sorting Methods/selectionsort.py
414
4.0625
4
# Selection Sort def sort(list): for i in range(len(list)-1): minpos = i for j in range(i,len(list)): if list[j] < list[minpos]: minpos = j temp = list[i] list[i] = list[minpos] list[minpos] = temp return list list ...
bc8284d701cb2ab62894daaa905aa89930fe5aa3
abmestri25/python-basics
/Telusko/Exception Handling/error.py
229
3.921875
4
try: print("File is opened.") a = int(input("Enter a number\n")) b = int(input("Enter a number\n")) print(a//b) except Exception as e: print("Something went wrong.. ",e) finally: print("File is closed.")
64b485676d06c618c4edc300b1cd9fcfe7499fc4
zacharyluck/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/buddymove_holiday.py
880
3.515625
4
import sqlite3 import os import pandas as pd df = pd.read_csv('buddymove_holidayiq.csv') df.columns = ['UserId', 'Sports', 'Religious', 'Nature', 'Theatre', 'Shopping', 'Picnic'] df.set_index('UserId') conn = sqlite3.connect('buddymove_holiday.sqlite3') curs = conn.cursor() if not os.path.isfile('buddymove_holida...
b67594f083b8e3f15a8156c60321e5dccba5fb62
kasemiro/AulasCursoEmVideo
/Mundo1/ex011.py
263
3.875
4
larg = float(input('Insira a Largura em metros: ')) alt = float(input('Insira a Altura em metros: ')) area = larg*alt tinta = area/2 print('Essa parede de {}X{}, a área é de {}m².'.format(larg, alt, area)) print('Será necessário {}l de tinta.'.format(tinta))
bca7cedf4915f5eeacb8c69b832b96612dcd697d
kasemiro/AulasCursoEmVideo
/Mundo1/ex024.py
127
3.859375
4
#Saber se o nome da cidade começa com Santo city = str(input('Qual é a sua cidade: ')).strip() print('Santo' in city.title())
5da0b329d6c99e566f6d05b9525db74821e25515
LuisEnriqueVelascoGomez4A-ISC/Metodos-Numericos
/metodos.py
2,815
4.03125
4
#!/usr/bin/env python # coding: utf-8 # In[6]: #metodo de biseccion import math #funcion a sustituir def poli(x): y = math.tan(x)-0.1*x return (y) #Programa principal print ("Este programa encuentra una raíz, por el método de bisección") xi=float(input('Introduce el valor de xi: ')) xs=float(input('Intro...
3b4a49e57c5b52faafc9fe41bdb51611afd0c827
asaii-tone/Atcoder
/ozaki/mount_dir/training/068b.py
107
3.515625
4
N = int(input()) count = 1 while True: if N < count * 2: print(count) exit() count = count * 2
777fd18cc5431f55a827beda62664bc97ec871bb
santhoshvai/Competitive_Programming
/FCTRL2/main.py
291
3.703125
4
cache = {} #recursive implementation def fact(n): if n in cache: return cache[n] if n == 0: return 1 else: ans = n * fact(n-1) cache[n] = ans return ans t = int(raw_input()) for i in range(t): n = int(raw_input()) print fact(n)
6716714bac4e840e993b50155e9771a1004da091
ROHINI-23/Patterns
/Pyramid_Shape_Reverse.py
183
3.75
4
n = int(input()) k = n for i in range(n,0,-1): for j in range(0,n-i): print(end=" ") for j in range(0,k): print("*", end=" ") k = k-1 print()
d1d7b75b5ec958718f2e0518ee1a7b1662f161ad
chrispy141/decryptor
/Decode.py
382
3.796875
4
def decode(string, shift): newstr = "" for c in string: if c == ' ': newstr = newstr + c else: newchar = ord(c) + shift if newchar < ord('a'): newchar = newchar + 26 if newchar > ord('z'): newchar = newchar - 26 ...
bdd2787d13b195c95176b0764b6dc1ea221bf2b6
nsteward96/PythonClass
/FileExamples/Snork.py
649
3.890625
4
print "Enter a sentence to be snorkified:", sentence_original = raw_input() sentence_encrypted = sentence_original sentence_encrypted = sentence_encrypted.replace('a', str(len(sentence_original))) sentence_encrypted = sentence_encrypted.replace('e', str(len(sentence_original)+1)) sentence_encrypted = sentence_encrypte...
29833566dccfc1bfde6275fa8d429a21355ebf32
ejoerns/candis
/tools/mdgen.py
780
3.546875
4
#!/usr/bin/env python # Simple parser to generate markdown files from templates import argparse import re def replaceInclude(obj): """Reads the given file to include its contents""" txt = file(obj.groups()[0], "r").read() return txt def parseMD(intxt): """Parse an given template string and returns the new mar...
d9481d1d8ceefa9c46b5de421e1db56778d04260
wixor/wi
/tests/check_unwanted_chars.py
848
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Mateusz Dereniowski, Wiktor Janas # Wyszukiwanie informacji lato 2011 import sys import re word = ur"""a-zß-öø-ÿĀ-ſ""" unwanted_char = re.compile(ur"[^-{word}0-9.'\"]".format(word=word), re.U) def check_unwanted_chars(filename): with open(filename, 'rb') as f: for ...
b4addeaf9f3281050561822d0a75cc4be804e24b
Vikas6206/PythonBasics
/home/sample/beginner/Tuples.py
262
4
4
#Tuples are immutable #we can store value in tuples numbers=(1,2,3) print(numbers) print(numbers[2]) #Tuples cant be modified #numbers[1]= 10 print(numbers) #Unpacking in python i.e shothand coordinates =(1,2,3) x,y,z =coordinates print(x) print(y) print(z)
5819e8885eb25ff1c1e4487da63d923fad2e0fda
Vikas6206/PythonBasics
/home/sample/After3Hours/InheritanceExample.py
326
3.921875
4
class Mammal: def walk(self): print("Walk") #Dog class inherits all the methods of mammal class class Dog(Mammal): def bark(self): print("bark") class Cat(Mammal): def meaw(self): print("Meaw") #createing objec dog1= Dog() dog1.bark() dog1.walk() cat1= Cat() cat1.meaw() Cat().me...
e38f50986f926361a2892b662ca6022206feb757
mwilkosz/Evolutionary-Algorithms
/TravelingSalesmanProblem/TravelingSalesmanProblem.py
11,084
3.5625
4
#! /usr/bin/env python3 import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt from numpy.random import choice from random import choices import numpy as np import itertools import operator import random import copy class Select(): def __init__(self): self.itaretion=0 ...
c1bdd716d56823d7161f72c00c21f351da5fe8b1
kalinka-koz/hardcorder
/Pola figur.py
1,880
3.921875
4
import math def circle(r): if r>0: return(4*math.pi*math.pow(r,2)) else: print("Podano nie poprawny promień koła") def triangle(a,h): if a>0 and h>0: return(a*h*0.5) else: print("Któryś z podanych wymiarów jest równy 0 lub mniejszy od 0") def rectangle(a,b): if a>0 an...
5945225e1ab154d75e6b9cf84b92fa79704bf8c8
mosamp/Python_Basics
/String_Operations.py
105
3.5625
4
a = "Hello \t" b="World!" c= a+b print (c) print ("Hello" + "World!") print (len("HelloWorld"))
233002cbfc0eb1d6af09f122239849867700c1f4
BaselOmari/BlackJack
/BJ.py
6,597
3.5
4
from random import * turn = 0 wins = 0 draws = 0 losses = 0 cash = 0 bet = 0 def cashIn(): globals()['cash'] = int(input("How much do you wish to cash in?\n")) def blackJack(): impot deckBuilder cards = deckBuilder.cards shuffle(cards) globals()['turn'] = 3 pcards = [cards[0],cards[1]] ...
c122d2a776f88be7797cfbd7768db9be8e54e8a3
murthyadivi/python-scripts
/Prime number check.py
864
4.1875
4
# returns the number input by user def input_number(prompt): return int(input(prompt)) # Checks if the given number is a primer or not def check_prime(number): #Default primes if number == 1: prime = False elif number == 2: prime = True #Test for all all ...
a178b43c125a7969592f181ade393729b2af67b9
TaoCurry/Basic_Python3
/Generator.py
1,068
3.90625
4
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- #Generator 生成器 #要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator. g =(x for x in range(0,10))#可以通过next()函数获得generator的下一个返回值。 for n in g: print(n) #也可以通过循环获得generator的所有返回值。 #定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator def odd():...
da4be3a59e10efd46c69195b9f9839561e9039de
TaoCurry/Basic_Python3
/高阶函数/埃拉托色尼筛选法.py
499
4.15625
4
#!/usr/bin/env python3 #-*- coding:utf-8 -*- def _is_odd(): n = 1 while True: n = n + 2 #筛选出奇数 yield n def _not_divisible(n): #筛选函数 return lambda x: x % n > 0 def primes(): yield 2 it = _is_odd() #初始序列,3开始的奇数 while True: n = next(it) #返回序列的第一个数 yiel...
376661828a44b8f31a00e37c1d3639b47c4d0ed5
TaoCurry/Basic_Python3
/No3.py
167
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- temp = input('请输入数字:') num = int(temp) if 1<num<100: print('符合要求') else: print('不符合要求')
7e7a5ee611f781253110e4d9e88d554bd8c503e2
TaoCurry/Basic_Python3
/reduce.py
990
3.859375
4
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- from functools import reduce def func1(s): return {'1':1,'2':2,'3':3,'4':4,'5':5}[s] def func2(x,y): return 10*x + y r = reduce(func2,map(func1,'1345')) print(r) #优化1.0 from functools import reduce def str2int(s): def str2(s): return {'1':1,'2':2,'3':3,'4':4,'5':5}[...
2354a70e5d709cb6fe64bd6c9b34fbf0167b8423
TaoCurry/Basic_Python3
/dict&set.py
3,378
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #key-value hash值 #dict是一种映射 Mapping 一一对应。 #字典中的键是唯一的,值并不唯一。 d = {'Micheal':95,'Curry':30,'MacGrady':1,'Kobe':24,'KD':35}#dict d['Micheal'] d['Curry'] d['KLAY'] = 11 #通过使用key 往dict加入元素 d['KLAY'] #由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉: d['Jack'] = 90 d['Jack'] ...
2dc76111d1c8b6ec27afd57ab807d957d7242f55
anweshan2001/Hacktoberfest-1
/Beginner/03. Python/Factorial.py
128
3.765625
4
def multiplyx(n): if n==1: return 1 return n * multiplyx(n-1) a = int(input('Enter a number ')) print(sumx(a))
da7813b03aac27cd834329d2f36deac1cbe9eff9
yuanyuanzijin/Offer-in-Python
/Chapter4_解决面试题的思路/38d_八皇后问题.py
776
3.5625
4
## 题目描述:在8x8的棋盘上摆放八个皇后,使得任意两个皇后不得处在同一行,同一列或者同一条对角线上,问共有多少种摆法? class Solution: def Queen(self, size): # write code here import itertools result = [] for p in itertools.permutations(range(size), size): result.append(p) for c in itertools.combinations(range(size)...
6e9e12c2069129cade41d6339b4ebc67098299e5
yuanyuanzijin/Offer-in-Python
/Chapter2_面试需要的基础知识/12_矩阵中的路径.py
1,888
3.671875
4
## 题目描述:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始, ## 每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 ## 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径, ## 因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。 ## 和书上思路相似,不同的是使用了成员变量保存各个参数 class Solution: def hasPath(self,...
4e55299f1efb3da256f8b67202981bf281ccb041
yuanyuanzijin/Offer-in-Python
/Chapter4_解决面试题的思路/33_二叉搜索树的后序遍历序列.py
1,691
3.78125
4
## 题目描述:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。 ## 递归自己的写法 class Solution: def VerifySquenceOfBST(self, sequence): # write code here if not sequence: return False if len(sequence) == 1: return True root = sequence[-1] inde...
29b85abb3c3a88052187eac05075e8802ed27faa
yuanyuanzijin/Offer-in-Python
/Chapter6_面试中的各项能力/54_二叉搜索树的第k大节点.py
691
3.5
4
## 题目描述:给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。 class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here if not pRoot or not k: return None self.result = [] self.midOrder(pRoot) if k > len(self.result): ...
935bd690c2ccf211e09d5305436770c7c1652298
yuanyuanzijin/Offer-in-Python
/Chapter2_面试需要的基础知识/06_从尾到头打印链表.py
1,362
3.90625
4
## 题目描述:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。 ## 思路一,使用栈可以反转链表 class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here s = [] head = listNode while head: s.append(head.val) head = head.next return [s.pop...
9bdc24f1f369f1849ab8da45bdf72c19ef6d2a81
yuanyuanzijin/Offer-in-Python
/Chapter3_高质量的代码/23_链表中环的入口节点.py
1,528
3.734375
4
## 题目描述:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 ## 设置两个指针,一个每次走两步,一个每次走一步,如果相遇则存在环。两个指针走过路径的差是环数量的倍数,2v-v=v,这个值和慢指针走过的路程相等。 ## 将快指针放到起点,此时两个指针的路程差是环节点数的倍数。两个指针每次都走一步,当两个指针相遇时,相遇的位置即为入口节点。 class Solution: def EntryNodeOfLoop(self, pHead): # write code here if pHead == None or pHead.next == None or pHea...
e2fdeb9dfe2706ee3eee86e871f49b4df3c8ae92
yuanyuanzijin/Offer-in-Python
/排序算法/insertion_sort.py
1,142
4.28125
4
""" 插入排序(Insertion Sort) 插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 算法描述 一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下: 从第一个元素开始,该元素可以认为已经被排序; 取出下一个元素,在已经排序的元素序列中从后向前扫描; 如果该元素(已排序)大于新元素,将该元素移到下一位置; 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置; 将新元素插入到该位置后; 重复步骤2~5。 """ def insertion(array): for...
95772ecbb09e8d41a8b039800af47b7173a208b4
GilgameshH0/python
/lesson21.py
175
4
4
# ДЗ words = ['мадам', 'топот', 'test', 'word'] for word in words: if word == word[::-1]: # Строка переворачивается print(word)
cd813aed1d06d919e660705b60c523d9933344e2
GilgameshH0/python
/lesson11.py
704
3.8125
4
# Циклы # While x = 0 while x < 11: x += 1 print(x, end=' ') # В функции принт можно добавить разделитель # и изменить конец строки чтобы не переходило на новую строку print('hello', 'kek', sep='?', end=' ') print('heh') # for s = "Hello world" for l in s: # Для каждой буквы в строке print(l, end=" ") ...
aa0e7c6de3ba9440db7d5673356b488aa0de9946
GilgameshH0/python
/lesson30.py
1,508
3.546875
4
# Работа с файлами # r для чтения # w для записи, если файл существует то он будет очищен # a для добавления в конец # + чтение + запись f = open('test.txt', 'a', encoding='utf-8') # Создаем ссылку на файл. Указываем путь к файлу, режим работы и кодировку # text = f.read(1) # Указатель смещается # text = f.read(2) # ч...
61dc5310a3b0bdf25ba685068089975e966c09ba
GilgameshH0/python
/lesson40.py
324
4.03125
4
# lambda выражения # Когда нужна функция в качестве аргумента и она размером в 1 строчку def get_square(num): print(num ** 2) # Вторая степень print(get_square(5)) # Использование лямбды print((lambda num: num ** 2)(10))
b58fef8f4d63244c82bf3c9d088ad462289cf61b
GilgameshH0/python
/lesson5.py
269
3.84375
4
# Преобразование типов # str() # int() ПРИ ОКРУГЛЕНИИ ОКРУГЛЯЕТ В МЕНЬШУЮ СТОРОНУ # float() # bool() x = 5.2 print(x, type(x)) x = int(x) print(x, type(x)) x = 0 print(x, type(x)) x = bool(x) print(x, type(x))
93bdfcf69dcc7f650f6536bfb0c9fd52cdec4209
pankajscodingforkids/programs
/projecteuler/Problem4.py
693
3.890625
4
def IsPalindrome(n): digits = list() while (n > 0): digits.append(n % 10) n = n // 10 numDigits = len(digits); for counter in range(numDigits // 2): if (digits[counter] != digits[numDigits-1-counter]): return False return True palindromes = list() for i in range(...
34392a31263eacbadbf573c7983d7d58cdffd197
XianwuLin/block_games
/区字棋/1_random.py
3,897
3.65625
4
#!/bin/python3 import tkinter as tk import time import random class Point(): def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return "(%d, %d)" % (self.x, self.y) ...
0403b6a715a91d3fd3899fe84117efa172a46e46
doctorf18/ASR_utils
/cal_distance.py
165
3.96875
4
# -*- coding:utf-8 -*- import Levenshtein while 1: str1 = input("str1:") str2 = input("str2:") dist = Levenshtein.distance(str1, str2) print(dist)
39e709691bad62a1cdbec198e75cfb1df875528a
Casper-V/Eigen_testprogrammaatjes
/vakantieplannen.py
537
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 2 19:23:47 2020 @author: Casper """ vakantieplannen = {} doorgaan = True while doorgaan: naam = input("Hoe heet je? ") bestemming = input("Waar wil je naartoe op vakantie? ") vakantieplannen[naam] = bestemming nog_meer = input("Wil je nog meer vakantiep...
955706b6eb6db96d903a2ca010d7c6d91f656c72
EthanOtholvinBrown/MowingBot
/GridWork.py
2,350
3.84375
4
# -*- coding: utf-8 -*- """ @author: Ethan This super class is for building the grid and determining where the bots are and where they have been. """ import matplotlib.pyplot as plt # Class for building the grid based on the user's specifications class GridPlotting(): #Takes in the width and height of th...
eba206f339e529b0c09661825ef6b4d24a36808a
AlexHoang2012/hoangtheduong-python-D4E12
/Session2/Homeworks/Homework2.py
356
4.15625
4
print("BMI calculation") h = int(input("Please input your height (cm): ")) w = int(input("Please input your weight (kg): ")) BMI= w/(h*h/10000) print("Your BMI is: ",BMI) if(BMI<16): print("Severely underweight") elif(BMI<18.5): print("underweight") elif(BMI<25): print("Normal") elif(BMI<30): print("Ov...
0feb8198f168d69a45fec0eecf62ab6561bdacdf
AlexHoang2012/hoangtheduong-python-D4E12
/Session1/Hello.py
105
3.84375
4
birthyear=input("enter your birthyear here") age=2020 - int(birthyear) print("You are", age, "years old")
f1655dea3804132283517019934651ff48c3d692
lalitsachdeva/3pillarglobal
/Random_ex3.py
583
3.59375
4
import random import math M = math.ceil print M(random.random()) # Random float x, 0.0 <= x < 1.0 #0.37444887175646646 print M(random.uniform(1, 10)) # Random float x, 1.0 <= x < 10.0 #1.1800146073117523 print random.randint(1, 10) # Integer from 1 to 10, endpoints included #7 print random.randrange(0, 101, 2...
0800d71f4948b8d97a84f7b058af64cb877e5dda
S-Des/Tuflow_tools
/Timestep_switch_POlines.py
2,973
3.625
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 06 12:45:41 2016 @author: simon.desmet """ # read in a csv file, #identify line 1 of the time series data, # ask user for current time step and desired timestep #delete additional timesteps (rows) down to desired timestep - auto save output #if possible do ...