blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b7f7ee62c81148dd28dcb6fdf1c68029e7717dd3
MATTALUI/cs101
/w10-number-guesser.py
419
3.953125
4
from random import randint min = 1 max = 75 target_number = randint(min, max) guess = None guess_count = 0 while guess != target_number: guess = int(input(f"Guess number between {min} and {max}: ")) guess_count += 1 if guess > target_number: print("Too High.\n") if guess < target_number: ...
ba57e2ef9f53f78c7f096298c34a7543845e5a7d
le-goff-benoit/Python--Beginner-Course
/Python_Beginner_Course/variables.py
888
4.28125
4
# coding: utf-8 # Simple variables attributions character_name = "Benoit \nLe Goff" character_age = 25 # Data type for strings in Python print(character_name) # Classic str manipulation city_name = "oslo" city_name.capitalize() print(city_name.capitalize()) # Classic list manipulation city_people = ['Benoit', 'Cose...
6c8732ee4aecc9ceaf42ecbc7f6000d3e51046d6
diegoSanchezTorres/myPythonProjects
/print_types.py
397
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Write a program in python that take two string to complete and form a message that we can understand #the message is "python is & language": word1='the' word2='best' print('python is'+word1+' '+word2+' language') print('python is {} {} lan...
14b6375090deef9bed5709b23eb1a9c0f334e927
Hariharan-SV/Scientific-Computing
/Open Methods/secant_method.py
650
3.984375
4
# Defining Function def f(x): return x**3 - 5*x - 9 # Implementing Secant Method def secant(x0,x1,e,step): if f(x0) == f(x1): print('Divide by zero error!') return x2 = x0 - (x1-x0)*f(x0)/( f(x1) - f(x0) ) abs(f(x2)) > e print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2))) ...
d15d756fdaf9a522b1a4b89bbd47c0cb3cd6521b
yukwok/flight-deals-start
/date_time.py
282
3.578125
4
import datetime as datetime today = datetime.datetime.now() today_short = today.strftime("%d/%m/%Y(%H:%M)") thirty_days_later = today + datetime.timedelta(days=30) thirty_days_later_short = thirty_days_later.strftime("%d/%m/%Y") print(today_short) print(thirty_days_later_short)
8dfffac593386ace6f4a17271c3f1339e95247f3
lbborkowski/engineering-unit-converter
/GUIUnitConverter_200119_Py2.py
23,180
4.28125
4
# Engineering unit converter tool # Created by Luke Borkowski on 06/12/16 # Input: given value(s); given units; desired units # Output: value(s) in desired units # Purpose: This tool allows the user to convert between any consistent units. # The goal is for the tool to be lightweight and easy to use. Thi...
00f0c3478125dd183a6a50ed1416c959ee687b0a
mixxen/jenkins-test
/test/model_test_valueerror.py
754
3.71875
4
""" model_test_valueerror.py Unit tests to demonstrate ValueError for model. AlgorithmHub. All rights reserved. https://www.algorithmhub.com/ """ import unittest import error_funcs class TestType(unittest.TestCase): def setUp(self): pass def test_value(self): """ Function to test w...
82f3378ad495fc9fc6b25b610cf9c8f970c9bbda
tugba-star/class2-module-assigment-week05
/question3.py
662
4
4
import random import time lottery_number_list=[] print("Generate a 100 Lottery tickets...") time.sleep(3)#After waiting for a while I used sleep to explain the winner for i in range(100):#Range 100 is given because we will create 100 lottery tickets. lottery_number_list.append(random.randrange(1000000000,9999999999...
40b0983ddcc1b9b302ec8fb57f26f225c3fd4263
remixknighx/quantitative
/exercise/leetcode/monotonic_array.py
599
3.765625
4
# -*- coding: utf-8 -*- """ 896. Monotonic Array @link https://leetcode.com/problems/monotonic-array/ """ from typing import List class Solution: def isMonotonic(self, A: List[int]) -> bool: lis = [True, True] for i in range(1, len(A)): if A[i] > A[i-1]: lis[0] = False ...
a527e31dacb4fad2c0a67c48706d0f526caf77c2
maxchv/LearnPython
/week08/examples/car/car.py
1,203
4.34375
4
class Car: """ Класс автомобиль """ #color = 'red' # атрибуты класса # name = 'ferrary' # speed = 250 def __init__(self, color): self.__color = color def __del__(self): print("car is died") def set_color(self, value): self.__color = value @property ...
4419447f5b3a7b8a39adf636720788a28f576499
hajaranazeer/python_tutorial
/basics/classes/__init__.py
215
3.71875
4
class democlass: n=56 def add(self): n=89 (self.n)=45 print("inside add n= ",DemoClass.n) n=78 o1=democlass() o2=democlass() o3=democlass() o3.add() o1=28 o2=82 o3=35 print(o1.n) print(democlass.n)
71de3aa307a7e574baddd7bd34e85a6da811c706
nsibal/Linked-List-2
/IntersectionOfLL.py
1,277
3.609375
4
''' Time Complexity: O(n) Space Complexity: O(1) Did this code successfully run on LeetCode?: Not on LeetCode. Problems faced while coding this: None Approach: Find the length of the lists and the last node of the lists. If the last of the two aren...
4547358fd76e5a7df97bab958f52842aed2fa0af
shengwu/solutions
/advent/2016/day16.py
897
3.640625
4
def swap(s): return ''.join('1' if c == '0' else '0' for c in s) def process(a): return a + '0' + swap(a)[::-1] def checksum(s): result = [] for i in range(0, len(s), 2): if s[i] == s[i+1]: result.append('1') else: result.append('0') if len(result) % 2 ==...
194dc21f8705c5081ff15c9ced8f44481fff9ab7
deltonmyalil/PythonTkinterGUI
/3-GridLayout.py
403
3.890625
4
from tkinter import * root = Tk() label1 = Label(root, text = "FirstName") label2 = Label(root, text = "LastName") entry1 = Entry(root) entry2 = Entry(root)#Textfields are called entries in PythonTkinter label1.grid(row = 0, column = 0) #use grid(row = i, column = j) instead of pack() label2.grid(row = 1, column = 0)...
134d92dbb202f251df13db725473aa847c661250
MikeD579/FlightProject
/modules/snapshot.py
3,555
3.828125
4
# This snapshot will find the coordinates of where the plane can land with a given # glide ratio and velocity. The plane's origin is going to be (0,0). All landing # locations will be coordinate pairs. # # Written in Python 3 # Last edit date 04-28-2020 # This is test edit. 4 import math import json BANK_T...
3f0e686677af696213239167ddd0c63b2f39c640
padma108raj/vasuken-padmaraj
/functions/recursive_function.py
152
3.84375
4
def fact(n): if n==0: result=1 else: result=n*fact(n-1) return result print("Factorial:",fact(7)) print("Factorial of 100:",fact(100))
b1a4657082ee76c84b17febf20bc9a4ce366deb4
sanket-khandare/Python-for-DS
/Stage 5.py
1,054
3.578125
4
# Import numpy import numpy as np # ---------------------------------------------------------------- # - Simulate the data height = np.round(np.random.normal(1.75, 0.2, 200), 2) weight = np.round(np.random.normal(60.32,15, 200), 2) np_city = np.column_stack((height, weight)) print(np_city) print(np_city.shape) # --...
2bfd209436c2a0061ea7dc5a50028ac073797f0b
Kr4v3N/Mooc_Python
/Exercice_3.13.py
1,016
4.09375
4
""" Auteur:Fayçal Chena Date : 01 avril 2020 Consignes : Écrire un programme qui additionne des valeurs naturelles lues sur entrée et affiche le résultat. La première donnée lue ne fait pas partie des valeurs à sommer. Elle détermine si la liste contient un nombre déterminé à l’avance de valeurs à lire ou non : si cett...
89a8f6281f79c4420b5012e80fce73ef68d7f907
SinduMP/Daspro
/Jobsheet03.py
3,404
3.90625
4
#Sistem Matematika #Menghitung Luas dan Keliling Bangun Datar def luas_persegi (s): luas = s*s return luas def keliling_persegi (s): keliling = 2*(s+s) return keliling def luas_persegipanjang (p,l): luas = p*l return luas def keliling_persegipanjang (p,l): keliling = 2*(p+l) return keli...
8345ad84bc42e778eae28cce46b114e5d79c43ec
KenanSultan/basic_pytasks
/find_minimum.py
949
3.9375
4
somelist = [12, 45, 87, [65, 34, 76], [34, 76, 43, [8, 446, 23, 48, [23,56,43,787], {"key1": 543, "key2": 65, "key3": [54,2,335,76]} ], 54, 23, 76, 32 ], ...
2e949d189858a3e6317bc124d6d00e458bffa783
404kt/RunescapeBots
/PredictGE.py
3,592
3.84375
4
import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import csv import pandas as pd from collections import Counter import time # File containing data sample, generated by NumberGenerator data_file = '' ...
f1d46db301e38959404dad3d05387db9f39066b2
pikalaw/algorithm
/delete_tree_level.py
4,770
4
4
"""Delete a level of a BST. Space requirement: 2N. Running time: 2N. TODO: Write an in-place version. $ python delete_tree_level.py Orignal tree 19 11 27 7 15 23 31 3 9 13 17 21 ...
58073e45abae177180c7eb31722e8e5ed1f374ac
iaksit/ProgrammingForEverbodyWithPython
/Week5/assignment_3_3.py
766
4.3125
4
''' # 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table: Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F If the user enters a value out of range, print a suitable error messag...
839880ecbee325112fd76e4581d371f1adfd2d58
daniel-reich/turbo-robot
/6RHxTTndfASnPyp8Z_4.py
952
4.375
4
""" The function is given an array of characters. Compress the array into a string using the following rules. For each group of consecutively repeating characters: * If the number of repeating characters is one, append the string with only this character. * If the number `n` of repeating characters `x` is great...
446c94fe16f73187e2737b35ab8f32e47a379617
XingshengLiu/PythonTools
/fluentpython/chapter_1.py
2,095
3.6875
4
# @File : chapter_1.py # @Author: LiuXingsheng # @Date : 2021/2/20 # @Desc : import collections import random Card = collections.namedtuple('Card', ['rank', 'suit']) card1 = Card('7', 'diamonds') print(card1, type(card1)) class FrechDeck: ranks = [str(n) for n in range(2, 11)] + list('JKQA') suits = 'spad...
d68cf874f5996fc1b5de4a5f581d21495182ce36
laura-barluzzi/Learn-Python-hard-way
/ex5.py
661
3.640625
4
name = 'Zed A. Shaw' age = 35 height_in = 74 # inches weight_lbs = 180 # lbs eyes = 'blue' teeth = 'white' hair = 'brown' weight_kg = weight_lbs * 0.45 height_cm = height_in * 2.54 print "let's talk about %s." % name print "He's %d inches and %d cm tall." % (height_in, height_cm) print "He's %d pounds and %d kg heavy...
4b22f71a1164faeae4c7180eb610a2b1721de4c6
nguyenhoangvannha/30-day-of-python
/day06stringsubsituationandformatting.py
564
4.09375
4
text = "This is a {var} string".format(var = "really cool") print(text) my_name = "Nha" name = "My name is {the_name}\n\tOk hi: {the_name}.".format(the_name = my_name) print(name) text = "This is a argument {0} in {1}".format("zero", 2017) print(text) text = "I am %s and I'm %d years old" %(my_name, 20) print(text) im...
838717e390b801f2d5ea3b3edb319717677859f9
ItamarRocha/DailyByte
/week_003/day21_reverselist.py
1,669
4.125
4
""" This question is asked by Facebook. Given a linked list, containing unique values, reverse it, and return the result. Ex: Given the following linked lists... 1->2->3->null, return a reference to the node that contains 3 which points to a list that looks like the following: 3->2->1->null 7->15->9->2->null,...
5615224a53127186be3216e98357e7b8ccc5b300
eliefrancois/Python
/Python Programs Fall 2018 /Labs/M6-L10/Rectangle classes v3.py
903
4.0625
4
class Rectangle: def __init__(self,l=1,w=1): self.l = l self.w = w self.a = (l*w) self.p = 2*(l+w) rec1 = Rectangle() # this creates the object with the values entered rec2 = Rectangle(5,6) def getArea(): return self.a def getPerimeter(): return self.p def getLength():...
92abc90925675d7c80599bc29e5460fb7886dda2
zhanghaiyan-08/mysite
/Data/Common/compareTwoList.py
2,246
3.578125
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = 'zhanghaiyan' #对比两个list或者元组是否相同,如果相同则返回True,如果有一个为空、或者不相同,则返回False #支持字典列表 def islistequal(listA , listB ): if listA == listB: return True if listA==None and listB == None: return True if listA ==None or listB==None: retu...
05ba5b546405859a7d5d00178df2f5e9ecf6c496
Sinjini2508/Dictionary-App-using-Python
/main.py
1,958
3.671875
4
import pandas as pd import tkinter from tkinter import scrolledtext window = tkinter.Tk() window.title("Lexica - The English Dictionary") window.geometry("750x750") window['bg'] = "#f09bd0" window.resizable(width=False, height=False) df = pd.read_csv("C:\\Users\\Sinjini\\final_list_of_words.csv") # Impor...
4d525cf4a4927e7be1f3323489bae91c068ae7bc
MauricioCarreon/AprendaPython
/compara.py
644
4.0625
4
numero1=input("Numero 1: ") numero2=input("Numero 2: ") salida="Numeros proporcionados: {} y {}. {}." if (numero1==numero2): #entra aqui si los numeros capturados son iguales. print(salida.format(numero1, numero2,"los numeros son iguales")) else: #condicionales añadidas, if dentro de otro if. #si los nu...
46f766b2d8fed1a909a6086b69e4200bdbcf58aa
Hilldrupca/LeetCode
/python/Monthly/Oct2020/sortlist.py
5,766
4.25
4
from typing import Tuple class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def _path(self): '''Helper method to ensure correct next values''' res = [] node = self while node: res.append(node.val) ...
66fc76f4da4c95428ea1d4213de9d1c72d67f323
Thirumurugan-12/Python-programs-11th
/#program to read a string and check whether it is a palindrome.py
272
4.3125
4
#program to read a string and check whether it is a palindrome s=input("enter the word ") rev='' l=len(s) print("length of the string",l) for i in range(l-1,-1,-1): rev=rev+s[i] if s==rev: print("it is a palindrome") else: print("not a palindrome")
a0c70e7cb63cfbc78ee167b24713685082acf11d
shadowspray/problem-solving-python
/_lessons_/05_stacks_03_brackets.py
1,397
4.46875
4
# -*- coding: utf-8 -*- # !/usr/bin/env python """ A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: S is empty; S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; S has the form "VW" where V and W are properly nested strings...
127c832e19e517fbf3dcca4c0d7e01ace5e4f41f
TylerBade/Classwork
/IT 210 - Fundamentals of Programming/Labs/LabQuiz3.py
801
3.890625
4
# Tyler Bade from string import ascii_letters, ascii_lowercase, ascii_uppercase from string import digits, hexdigits, punctuation instr = input("Please enter a string: ") digs = set() hexdigs = set() lowlet = set() anylet = set() for char in instr: if char in digits: digs.add(char) if char in hexdigi...
f7e49d23a3ed59ea93b6b4ef8325295268ff17ce
seyidaniels/data-structures-practice
/divide_two_integers.py
612
3.546875
4
import sys def divide(dividend, divisor): isNegative = True if (dividend < 0) != (divisor < 0) else False dividend, divisor = abs(dividend), abs(divisor) summ = divisor quotient = 0 if dividend >= 2 ** 31 - 1: return 2 ** 31 - 1 while summ <= dividend: current_quotient = 1...
6073c41b89a3003adf87213d85db5e39ba1bb08f
Nekonokuro/ICTPRG405-407-Python
/Q2.py
346
4.25
4
#Write a python script that keeps asking for names, until they enter an empty name, #then creates a file called 'people.txt' and adds names on a separate line. name = 0 with open("people.txt", "w") as filename: while name != "": name = input("Enter any name: \n") filename.writelines(str(nam...
678de12c8d5e967f9c6ef1a3703d3e83fbe2301d
MohammadHassanT/vector_math
/base_coordinate.py
4,101
3.6875
4
from math import pi as PI ############################################### class BaseCoordinate: @staticmethod def _is_number(a): return (isinstance(a,(int,float))) and (not isinstance(a,bool)) @staticmethod def is_number(*args): for num in args: if not BaseCoordinate._...
32c614540ed7b1c6612818c0a0e434775199d158
Zahidsqldba07/CodeSignal-26
/The Core/Lab of Transformations/081 - reflectString.py
250
3.546875
4
def reflectString(inputString): d = { chr(x):chr(122 - x + 97) for x in range(ord('a'),ord('z')) } d1 = { chr(122 - x + 97):chr(x) for x in range(ord('a'),ord('z')) } d.update( d1 ) return "".join([ str(d[x]) for x in inputString ])
d3f9b88a59e6341d29fd1ba44b0231009c7ad952
ggozlo/py.practice
/문자열_처리.py
699
3.859375
4
# ____________________________________________________________________________________________________________ 문자열 처리함수 python = "Python is Amazingnnnnnnnnnnnn" print(python.lower()) # 전체 소문자출력 print(python.upper()) # 전체 대문자출력 print(python[0].isupper()) # 대문자인지 진위여부 파악 print(len(python)) # 문자열 길이 print(python.replace(...
539bf459e743e3503854eaef29d47ef90208bc44
dhadbs2/Pycharm
/CodeUp 2001.py
190
3.75
4
list1 = [] list2 = [] for i in range(3): list1.append(int(input())) for i in range(2): list2.append(int(input())) list1.sort() list2.sort() print(round((list1[0]+list2[0])*(1.1), 1))
c51c8581235e28927aec6820823e5579af4d89eb
Preshh0/ElevenPythonProjects
/IsAPalindrome.py
236
4.0625
4
Sentence = input("Enter a word: ") if Sentence == Sentence[::-1]: #::-1 basically just means the inverse of whatever variable it is in. print(f"{Sentence} is a palindrome.") else: print(f"{Sentence} is not palindrome.")
a1e1b1aef92f3a2bfaa2d9ba7d2f025749e1b63f
Thaisdalpozzo/Python
/ex26.py
262
3.984375
4
frase = str(input('Digite qualquer frase: ')).upper().strip() print('Aparece {} vezes a letra A'.format(frase.count('A'))) print('A primeira posição aparece em {}'.format(frase.find('A')+1)) print('A ultima posição aparece em {}'.format(frase.rfind('A')+1))
837eda47228c5311f6e7b98fc800684253ad85a5
umeshror/data-structures-python
/arrays/next_permutation.py
2,388
4.34375
4
""" Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here ar...
e6790d7b2275eb9dfd09550743e55b3cf3eb4328
marcelaaristizabal/programming
/Exámenes/Exámen 4 /punto2.py
2,664
3.515625
4
#Punto2 CIUDAD_1 = '¿ Cuál es tu ciudad favorita en el mundo entero ? : ' CIUDAD_2 = '¿ Cuál es tu segunda ciudad favorita en el mundo entero ? : ' CIUDAD_3 = '¿ Cuál es tu tercera ciudad favorita en el mundo entero ? : ' CIUDAD_4 = '¿ Cuál es tu cuarta ciudad favorita en el mundo entero ? : ' CIUDAD_5 = '¿ Cuál es tu...
41963f296379ff9a053cd7278735d8351532ac6a
das-jishu/data-structures-basics-leetcode
/Leetcode/medium/keys-and-rooms.py
1,515
3.859375
4
""" # KEYS AND ROOMS There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length. A key...
0c362a1dbab7f4e3a9a56dbdc33d28b79a3baf4e
Kinjobek/PythonDenemeleri
/Problemler6/Problem6_1.py
2,994
4.28125
4
""" Kodlama Egzersizimizde yazdığımız Kumanda Sınıfına ek olarak metodlar ve özellikler eklemeye çalışın. """ import time class Kumanda(): sesSeviyesi = 0 kanallar = {} acikKapali = False kanalNumarasi = "1" def menuYazdir(self): print("1 : TV Durumu\n" "2 : TV Aç/Kapat\n" ...
11df4450064880498cfc278e7563d451e1222536
PRKKILLER/Algorithm_Practice
/LeetCode/1507-Reformat Date/main.py
851
4.15625
4
""" Given a date string in the form Day Month Year, where: Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}. Year is in the range [1900, 2100]. Convert the date string to the format YYYY-MM-DD...
6efd5d96f605981e2527edc8ef8be1b1d02dd97e
JayTaylor1/Python
/Week 4 - Hello Capitalise.py
166
4.03125
4
Name = input('Hello, Who are you? ') if Name == "": print("Hello World") else: print('Hello, ' + Name.capitalize() + '. It is good to meet you.') pass
6a6a52000055ee0d36dda2d5c9d5ea2df4548421
ayanchyaziz123/AI-Assignment
/2.py
160
3.546875
4
def make2dList(rows, cols): a=[] for row in range(rows): a += [[0]*cols] return a rows = 3 cols = 2 a = make2dList(rows, cols) a[0][1] = 1 print(a)
28e7a6d0fa379d8db33d5cb9b3ba239913fd339b
bodii/test-code
/python/python_test_002/02/04.py
1,704
3.609375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- class Omelet: def __init__(self, kind="cheese"): self.set_kind(kind) def __ingredients__(self): return self.needed_ingredients def get_kind(self): return self.kind def set_kind(self, kind): ...
8512e411389609d1294aa24bbf1a6fccfe341b26
haydenso/school-projects
/Year 11/themepark_test.py
3,512
3.859375
4
class Overall: def __init__(self): self.num_students = 0 self.ticket_price = 30 self.coach_price = 550 self.max_students = 45 self.all_students = [] def inputNumStudents(self): self.num_students = int(input("How many students are going? ")) return self.n...
ca318a87bc1efc5fc49aa14e8340a85f34641475
Ayushd70/RetardedCodes
/python/elapTime.py
142
3.78125
4
# Python Program to Measure the Elapsed Time in Python import time start = time.time() print(23*2.3) end = time.time() print(end - start)
096cc9d5f67962d2a6634833404672050c4b290b
AdithyaPotu/Innomatics_Internship_APR_21
/Task-8(Statistics Question)/Task- 8(Statistics Questions).py
3,834
3.8125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: # question 1 ## calculating the Binomial distribution problem from math import factorial def b(n,x,p): return factorial(n)//factorial(n-x)//factorial(x) * (p ** x) * (1-p) ** (n-x) b1,g1 = map(float,input().split()) p = b1/(b1 + g1) r = b(6,3,p) + b(6,4,p) +b(6,...
d76743130264a4677af752e3b8ec3068a9f513be
LexiNastos/Karan-Projects-Solutions
/count_vowels.py
299
4.21875
4
#Count vowels of a string input def count_vowels(string): vowels = ['a', 'e', 'i', 'o', 'u'] lower_string = string.lower() vowel_count = 0 for char in lower_string: for vowel in vowels: if char == vowel: vowel_count+=1 return vowel_count print count_vowels(raw_input('>'))
1747b7161f1f43f059290c8f5f132d5e211b265c
nriteshranjan/Deep-Learning-with-PyTorch
/Intro to PyTorch - Working with single layer Neural network.py
1,211
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat May 9 14:57:32 2020 @author: rrite """ #Working with single layer neural network import torch def activation(x): return (1 / (1 + torch.exp(-x))) #Generating some random number torch.manual_seed(7) #manual_seed : Sets the seed for generating random numbers. #Features a...
68af29ea9a81c52c5945135e51e78075ca152bc7
redherring2141/Python_Study
/Python_200/Intermediate/ex_075.py
142
3.625
4
txt1 = 'A tale that was not right' txt2 = 'This too shall pass away' print(txt1[5]) #'e' is printed out print(txt2[-2]) #'a' is printed out
a9522dab29150570b5cbaeb0f07cd2e321ceb320
haresh22/Practice_Python
/string_con.py
803
3.984375
4
################### String Concinate ##################################### x = "HARESH IS GOOD BOY " y = "and he is working with Coverfox" print(x+y) # Concinate ( its add or plus the string ) print(x.replace("is","are")) # is replacec with are print(x.split()) # str...
8fc01a60a445e4fb24698bef7b6094253b4b9f5f
vladimirStest/python_proj
/lesson7_oop_complicated/lesson7_task3.py
1,482
3.875
4
# Задание 3: class Cell: def __init__(self, count): self.count = count def __str__(self): return self.count def __add__(self, added): self.count = self.count + added.count return self.count def __sub__(self, subtrahend): if self.count - subtrahend.count > 0: ...
51b64a6fb84733cdfbf04b60f613526f4a331739
xiaoloinzi/worksplace
/GR1/formal_Class/Algorithm/Algorithm_0714_01.py
3,932
3.890625
4
# encoding=utf-8 class TreeNode(object): def __init__(self,val,left=None,right=None): self.val = val self.left = left self.right = right class BinaryTree(object): def __init__(self,root): self.root = root # # # 先序遍历 def preOrder(retList,node): if node != None: retLis...
392a0b067f58e24f654ddee55dd6d3187f7d99b0
kiya015/Home_kiya
/py_practice/异常处理4.py
594
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/4/26 22:49 # @Author : kiya # @Site : # @File : 异常处理4.py # @Software: PyCharm # 异常中抛出异常 class Test(object): def __init__(self, switch): self.switch = switch def calc(self, a, b): try: return a/b except ...
3124beab056b34c94a5763f1812c306e25b48079
TheDesTrucToRR/Hacktoberfest-2021
/Python/Square_of_elements_in_dictionary.py
460
3.5625
4
class square: def update(self): dict=({1:[1,2,3],2:[4,5],3:[6,8]}) print("Dictionary is:",dict) l={} k=[] v=[] for i in dict.keys(): k.append(str(i)+"_mod") for i in dict.values(): v.append(i) for j in range(0,len(v)): ...
f85540781fe671bfeeddf1a33c4c2e038021f818
luizferreirajr/igti_python
/introduction/python_concepts/lambda.py
135
3.625
4
""" Using def def soma(x, y): print(x + y) """ # Using lambda (nameless function) soma = lambda x, y: x + y print(soma(3, 6))
f8317469252da86b20e574e6e098f3392d5e9da2
VictorJanampa/Sort-Algorithms
/python/Quick_Sort.py
553
3.859375
4
def partition(array,low,high): i = ( low-1 ) pivot = array[high] for j in range(low , high): if array[j] <= pivot: i = i+1 array[i],array[j] = array[j],array[i] array[i+1],array[high] = array[high],array[i+1] return ( i+1 ) def QuickSo...
e187410cd56fc8b202b2ddac4f8efe6a6b8c4ec4
andyzju/PythonPractice
/pythonpractice/algorithm/levenshtein/levenshtein.py
980
3.640625
4
# coding=utf-8 def getLevenshtein(str1, str2): if len(str1) > len(str2): str1, str2 = str2, str1 if len(str1) == 0: return len(str2) if len(str2) == 0: return len(str1) len1 = len(str1) + 1 len2 = len(str2) + 1 matrix = [range(len2) for x in range(len1)] #创建二维数组方法 ...
25742cdc8f33c72fca347f7e47d244fecce7ec65
gitshangxy/tutorial
/L6异常和异常捕获和debug/3 抛异常和自定义异常.py
1,488
3.875
4
# 抛异常和自定义异常 # 引题: 例1 比如电商公司发快递,路上出现突发的龙卷风,然后快递上天了找不到,最后客户投诉,客服人员将这个之前从未有过的状况报告公司。 # 例2 公司里出现一个问题,基层员工没有权利决定,他就叫来了部门经理,部门经理也没有解决,就上报更上一级的领导。 # 例3 一个代码项目比较大,几十个模块但比较相似,如果用户表单输入错误,需要捕获异常打印信息,但每个模块都写提示信息的话重复累。可以抛异常给上层函数,最终由专门的异常处理函数打印信息。 # 所以,代码中遇到问题有时主动抛出异常,交给上层函数处理。遇到新问题需要自定义异常。 错误可控,有点小问题就可以主动抛异常 终止程序运行。 class Division...
4f96ee5590475aa1d1b2e98ae8f4d4c967369858
mattlam88/Exercises
/introduction_and_environment/data_types_and_control_flow/3_count_duplicate/Solution/solution.py
175
3.515625
4
# Code your solution here list_dup = ['a', 'a', 'a', 'n', 'z', 'e'] tot = 0 i = 0 while i < len(list_dup): if list_dup[i] == 'a': tot += 1 i += 1 print(tot)
78ca48f94a4af9886003e7c43b3bdcab0d573f0c
guyleaf/python
/homework/019. 猜數列/test19.py
1,836
3.796875
4
""" 019. 猜數列 小明的家庭作業裏有很多數列填空練習。 填空練習的要求是:已知數列的前四項,填出第五項。 因為已經知道這些數列只可能是等差或等比數列,他決定寫一個程式來完成這些練 輸入說明: 第一行是數列的數目t(1 <= t <= 20)。 以下每行均包含四個整數,表示數列的前四項。 輸出說明: 對輸入的每個數列,輸出它的前五項。 不合法的輸入則輸出E。 input : 2 1 2 3 4 32 16 8 4 output: 1 2 3 4 5 32 16 8 4 2 """ def main(): #main question = [] #儲存數列 num = int(input()) #輸入num...
a7cb85fb08bf9421e0fcbbfe40ff5991713f65fe
arifBurakDemiray/TheCodesThatIWrote
/Python_Projects/probability_statistics/hypothesistestingwithnull.py
3,222
3.625
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 24 13:24:13 2020 @author: burak """ from matplotlib import pyplot as plt import numpy as np import random # All file like matrix ages = np.genfromtxt("titanic_data.txt") first = [] # 1st class second = [] # 2nd class third = [] # 3rd class crew = [] # crew whole = [] # w...
01778a3f5cf6805374d1e4e8bfc643defb6acc28
mrfox321/leetcode
/leetcode/p33.py
1,156
3.625
4
def binary_cut(array,target,start): if len(array) < 4: for i in xrange(len(array)): if target == array[i]: return start+i return -1 center = len(array)//2 if array[0] <= target and target <= array[center]: return binary_cut(array[0:center+1],target,start)...
a888831d783867ce64f33e1e02afa72036fa5774
PhucNguyen12038/PythonLearning
/School-works/sessions/session14/ex2.py
1,106
3.890625
4
def sort_dict_by_value(dates): key_value ={} ascend_value = [] for k,v in dates.items(): key_value[k] = v for i in sorted(key_value.values()) : ascend_value.append(i) ascend_value.reverse() new_date = {} for i in ascend_value: for k,v in dates.items()...
67b0edea8f10237bca42fa713b3bab5e1529bd6e
erjan/coding_exercises
/minimum_speed_to_arrive_on_time.py
1,856
4.15625
4
''' You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each trai...
d5ad142f7959ffb73796181a9cc8e597cd24028a
dbmi-pitt/DIKB-Micropublication
/scripts/mp-scripts/Bio/Graphics/BasicChromosome.py
17,083
3.6875
4
"""Draw representations of organism chromosomes with added information. These classes are meant to model the drawing of pictures of chromosomes. This can be useful for lots of things, including displaying markers on a chromosome (ie. for genetic mapping) and showing syteny between two chromosomes. The structure of th...
c84e715418f86d13700eb0252f597ccc12da1491
dark-glich/data-types
/set.py
3,064
4.65625
5
# set : mutable - unordered - not support duplication set_1 = {1, 2, 3, 4, 5} print(f"original set : {set_1}") # mutable objects like list cannot be used in a set # set.add(value) is used to add a single value in a set set_1.add(6) print(f"tuple.add(6) : {set_1}") # set.update([value]) is used to add multiple value to ...
ceac6a1fa36234393509326cc94cd2eb7ed1aa5e
amartinez808/SE126-Python
/Lab1A.py
487
4.0625
4
#LAB1A #ANTONIO MARTINEZ #STARTING DOCUMENTATION: #-program prompt #-pseudocode #-notes for you to remember #-guidelines / information for anyone reading your documentation #VARIABLE DICTIONARY--------- # max = maximum capacity of the room # ppl = Amount of people who want to attend the event #initialize Varia...
a61e2b60029d607c93cff3f4c0f655a9c916517b
swappy208/projecteuler
/projecteuler1.py
144
3.921875
4
def Multi(n): s=0 for number in range(0,n): if number%3==0 or number%5==0: s+=number return s print(Multi(10))
6e594887740d3db9d87f9208c76d1838af89e61a
DMWillie/simulate_roll_dice
/simulate_roll_dice_v1.0.py
727
3.609375
4
""" 作者:北辰 功能:模拟掷骰子 版本:1.0 日期:04/07/2018 """ import random def roll_dice(): """ 模拟掷骰子 """ roll = random.randint(1,6) return roll def main(): """ 主函数 """ total_times = 10000 # 初始化结果列表[0,0,0,0,0,0] result_list = [0] * 6 for i in range(total_times): ...
52da809aaa45fc4ad89adaebabf582603676cfc0
adam-xiao/PythonMasterclass
/HelloWorld/formatting.py
1,497
3.953125
4
for i in range(1, 13): print("No. {0} squared is {1} and cubed is {2}".format(i, i**2, i**3)) print() for i in range(1, 13): print("No. {0:2} squared is {1:4} and cubed is {2:4}".format(i, i**2, i**3)) # field width (width or 2,4, 4 chracters) in rep fields print() for i in range(1, 13): print("No. {0:2} s...
670e562947510dc149281a657b0064b3c232309c
JonathanGun/Project-Euler
/150+/Prob187.py
205
3.5625
4
from Prime import is_prime # n = 500 # cache = set() # for i in range(1, n // 2 + 1): # is_prime(i, cache) # print(cache) # print(len(cache)) cnt = 0 for i in range(1, 10**8): cnt += i print(cnt)
f4d3b8a597d09c00eb08e9eaa9b3944c6d57958d
imrangosla/predictive_models
/test.py
4,627
3.65625
4
# conventional way to import import numpy as np import pandas as pd #import seaborn as sns #import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression from sklearn import linear_model from skl...
515ef3ae6c5e362728f5ed5c324189b4767c9404
yuniaohappy/LearningPython
/python_reptile/bing.py
383
3.5625
4
from urllib.request import urlopen from bs4 import BeautifulSoup while True: key = input("请输入要翻译的内容:") if key == 'q': break url = "https://cn.bing.com/dict/search?q=" + key response = urlopen(url) soup = BeautifulSoup(response,"html.parser") li = soup.select("div.qdef li") ...
e5602278008c3175c1f330bd7a25748ba9e7a101
LucyNana/PythonLearning
/PY4E/Assignment 1/Exercise_02_03.py
125
3.625
4
a = input("Enter Hours:") b = input("Enter Rate:") c = float(a)*float(b) print("Pay:",c) #input return a function of string
0c3a9ab3701a9f46cd963b7b85a9be7da355f23b
DaveVodrazka/calculator
/_type_check.py
224
3.53125
4
def int_or_float_check(a): if not (isinstance(a, int) or isinstance(a, float)): raise TypeError("Required int or float") def int_check(a): if not isinstance(a, int): raise TypeError("Required int")
2030f16bb38c9e12a5c9f2bbb4b5f70f528ba9b9
mospky/tdd_challenge
/calc_price.py
843
3.75
4
import math class Calc: def calc_price(self, moneys): """受け取ったお金に消費税をかける""" total = 0 for money_i in moneys: total += round(money_i * 1.1) return total def round(self, flo): """少数を丸めます""" return math.floor(flo+0.5) if __name__ == "__main__": c...
28a459f8dfc05f821ca4883e4f72d8fe0ee646a5
VKSi/2019_10_GB_Course_Py_Essential
/les_2/les_2_task_2.py
1,285
4.25
4
# Vasilii Sitdikov # GeekBrains Courses. Python Essential # Lesson 2 task 2 # October 2019 # task: 2) Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются # элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний # сохранить на своем месте. Для...
07793955bfdceb2fb41b1089775cc817bb9257a6
colingdc/project-euler
/23.py
1,336
4.03125
4
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. # For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, # which means that 28 is a perfect number. # # A number n is called deficient if the sum of its proper divisors is less than n and...
cd43f5abb410bdb9067ff39bd58a7fec24d631b4
listenviolet/leetcode
/494-Target-Sum.py
2,780
3.734375
4
class Solution: def findTargetSumWays(self, nums, S): """ :type nums: List[int] :type S: int :rtype: int """ def calculate(nums, i, sum, S, memo): if i == len(nums): if sum == S: return 1 else: ...
4a2255be1e0484170844c1ef9e5c01d0f753fd42
aabs7/Python-for-everybody-Specialization
/Course I/assignment2.3.py
303
4.125
4
#''' #2.3 Write a program to prompt the user for hours and rate per #hour using raw_input to compute gross pay. #Use 35 hours and a rate of 2.75 per hour to test the program #(the pay should be 96.25). #''' hrs = input("Enter hours:") rate =input("Enter rate:") pay = float(rate)*int(hrs) print(pay)
2f419fa961b1c38b25cf0c68b30e26bb7e9a2ae8
L00169700/OOPR
/List/data_in_series.py
1,212
4.375
4
empty_list = [] # Create an empty list empty_list.append(10) #using an index won’t work until the items are added ages = [19, 21, 20] # A named list with comma separated values student1_details = [20, "Michael Brennan", 77.5] # Lists can hold a variety of data types student2_details = [33, "Mairead Gallagher", 65] cla...
f765b445d3f4d4bb6bbf7b4b10cce90da92ffada
abradfield/data_visualization
/random_walk.py
1,310
4.1875
4
from random import choice class RandomWalk(): """ A class to generate random walks """ def __init__(self, num_points=5000): """ initialize attributes of a walk :param num_points: # of points to be generated """ self.num_points = num_points # All walks ...
95c328a406d3938657a279a81fa1e79f8a787244
OkayAlright/personal-code
/python/formal_languages_python_projects/dfa.py
1,685
3.609375
4
""" dfa.py by Logan Davis A simple (simple in making, not using) collection of functions & a class to simulate DFA's 11/14/16 | Python 3.5 | Editor: Nano """ class node(object): """ A simple class to act as a node in a DFA. branches is a dict that the key would be the character to handle and it's valu...
206585327690b7b2df40c459b9a4217bca1df871
KarlSchaller/python-intro-projects
/file reading/csvnotes.py
977
3.796875
4
if __name__ == "__main__": #Technique 1: open file and read line by line data = open("csvnotes.csv", "r") #print(data) for line in data: print(line.strip()) #Technique 2: open with readlines and store in list lines = open("csvnotes.csv", "r").readlines() for line in lines: ...
3be969d66ca4267d89169578ccc5a55a180d9794
swapnil-sat/helloword
/Python -Acess List Items_14-3-21 .py
2,360
4.71875
5
# ====================================================================================|| # || Python-Access List Items || # || || # || ...
71abcdffed755edca21be685e18c7d823bd5df9b
vidaljose/pruebasPython
/calculos/calculos_generales.py
495
3.625
4
def sumar(op1,op2): print("El resultado de la suma es ",op1 + op2) def restar(op1,op2): print("El resultado de la resta es ",op1 - op2) def multiplicar(op1,op2): print("El resultado de la multiplicacion es ",op1 * op2) def dividir(op1,op2): print("El resultado de la division es ",op1 / op2) def ...
649b9826ed88c857208661c30ee0a5dbf0343f9b
cy0913/pythontest
/code/json数据.py
364
3.90625
4
# json数据 json格式的字符串 # str01 = """{"name":'zhangsan',"age":'14',"gender":'1'}""" import json dict01 = {'name': 'zhangsan', 'age': '14', 'gender': '1'} print(type(dict01)) # 字典转json字符串 str01 = json.dumps(dict01) print(type(str01)) print(str01) # json字符串转字典 dict02 = json.loads(str01) print(type(dict02)) print(dict...
62467531167d14abce8cd0a2d1f6859d7159b0c1
ICC3103-202110/proyecto-01-moore_bedini
/character_action.py
501
3.515625
4
import random import random from players import Player class Character: def __init__(self,cards): self.__cards = cards def tax(): return int(3) def murder(cards, name, cards_players_lost): if len(cards)==2: position=int(input("Which card do you want to turn around (...
42281ee767884ca96ec8f5054e94bebf0cb1a576
SkarletA/ejercicios
/mcm.py
599
3.921875
4
#Ejercicio 16.- Programa que lea dos números N1 y N2 enteros positivos y obtiene su mínimo #común múltiplo. (Se sabe que el mínimo común múltiplo de dos números es igual a su #producto N1 * N2 dividido entre su m.c.d). n1 = int(input("Ingresa un numero: ")) n2 = int(input("Ingresa un segundo numero: ")) if n1 > n2 :...
c19483faf6f28c1495bd0099ee89aeacae594f53
Asunqingwen/LeetCode
/medium/Solve the Equation.py
2,102
4.21875
4
# -*- coding: utf-8 -*- # @Time : 2019/11/11 0011 14:40 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Solve the Equation.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Solve a given equation and return the value of x in the form...
e809fa0befb766eb928d9adc5e3cc5da4ad7407c
Shatilov789/Program_SF
/main.py
489
3.640625
4
print("Программа рассчета уропа пушек!") print() canon_ist6 = int(input("Кол-во пушек Истязатель 6 ур: ")) canon_ist5 = int(input("Кол-во пушек Истязатель 5 ур: ")) canon_destroyer5 = int(input("Кол-во пушек Погибель 5 ур: ")) canon_destroyer4 = int(input("Кол-во пушек Погибель 4 ур: ")) canon_destroyer3 = int(input("К...