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
29d5d901fc4ea681b9c2caa9f2dddf954174da4d
Ardra/Python-Practice-Solutions
/chapter2/pbm38.py
399
4.15625
4
'''Problem 38: Write a function invertdict to interchange keys and values in a dictionary. For simplicity, assume that all values are unique. >>> invertdict({'x': 1, 'y': 2, 'z': 3}) {1: 'x', 2: 'y', 3: 'z'}''' def invertdict(dictionary): new_dict = {} for key, value in a.items(): #print key, value ...
1ff16e76d42ef58418cc6ca716e14427de77cca2
Ardra/Python-Practice-Solutions
/chapter5/pbm8.py
213
3.609375
4
'''Problem 8: Write a function peep, that takes an iterator as argument and returns the first element and an equivalant iterator.''' def peep(item): item=list(item) element=item[0] return element,item
eb2d524d39271c00e5fc18eb35cf1364de851f11
lychlov/LintBrush
/longestWords.py
922
4.0625
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: longestWords Description : Author : Lychlov date: 2018/5/18 ------------------------------------------------- Change Activity: 2018/5/18: ----------------------------------------...
7b8fd1e78f3e3664216ba34416fcc6c49135a269
lychlov/LintBrush
/searchRange.py
785
3.75
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: param root: The root of the binary search tree @param k1: An integer @param k2: An integer @return: return: Return all key...
4deef6cba3ed01fe2540bce4c2091ec858e481be
lychlov/LintBrush
/factorial.py
196
3.640625
4
class Solution: def factorial(self, n): if n == 1: return 1 else: return n * self.factorial(n - 1) sol = Solution() print("5!=%s" % sol.factorial(5))
03c0e644cfcd71d1dbb63646c8fcd42ee0537f68
keshavprashanth/Machine_Learning
/pandas/dataframes.py
1,722
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt s = pd.Series([1,3,5,np.nan,6,8]) print(s) # Creating a DataFrame by passing a NumPy array, with a datetime index and labeled columns: dates = pd.date_range('20130101', periods=6) print(dates) df = pd.DataFrame(np.random.randn(6, 4),...
f3c7641a68dc889f345330436ae46a5e92e3dbdc
alejotalice/tarea-programacion
/alejo talice-5.py
253
3.734375
4
monto = float(input("Cantidad de invercion? ")) interes = float(input("Interés anual? ")) años = int(input("Años?")) for i in range(años): monto *= 1 + interes / 100 print("Capital tras " + str(i+1) + " años: " + str(round(monto, 2)))
874438d788e903d45edc24cc029f3265091130b1
IDCE-MSGIS/sample-lab
/mycode_2.py
572
4.25
4
""" Name: Banana McClane Date created: 24-Jan-2020 Version of Python: 3.4 This script is for randomly selecting restaurants! It takes a list as an input and randomly selects one item from the list, which is output in human readable form on-screen. """ import random # importing 'random' allows us to pick a random elemen...
fc388b902623e910d75ac465f67e23c8fd1d0de6
camilobmoreira/Fatec
/1_Sem/Algoritmos/Lista_08_Capitulo_07_e_08_-_Entrega_29_04/ex805.py
191
3.515625
4
# def pesquise(lista, valor): for x,e in enumerate(lista): if e == valor: return x return None L = [10, 20, 25, 30] print(pesquise(L, 25)) print(pesquise(L, 27))
1d1a11f777a498ee4f788660a5ece2ed3b9884c6
camilobmoreira/Fatec
/1_Sem/Algoritmos/forca_simples.py
1,400
3.71875
4
listaPalavras = ["satelite", "mustang", "guaxinim", "navio", 'doutor'] from random import randint var = randint(0, 4) palavra = str(listaPalavras[var]) palavraList = list(palavra) palavEmBranco = [] while len(palavEmBranco) < len(palavraList): palavEmBranco.append("_") print("A palavra tem %i letras" %len(palav...
5315b7e973760703503bac797bbb6ff14f9e7157
camilobmoreira/Fatec
/1_Sem/Algoritmos/Lista_08_Capitulo_07_e_08_-_Entrega_29_04/ex710_jogo_da_velha.py
3,196
3.65625
4
# tabuleiro = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"] ] print("Use os números para escolher a posição em que jogará: ") jog1 = True jogadasJog1 = "" jog2 = False jogadasJog2 = "" gameOver = False vencedor = "" posibilidades = ["123", "456", "789", "147", "258", "369", "159", "357"] while Tru...
a02906f5707f3f51798e5d93a450317a754191f3
camilobmoreira/Fatec
/1_Sem/Algoritmos/Lista_02_Capitulo_03_-_Entrega_ 16_03/ex314_calc_val_car_alug.py
273
3.796875
4
#Calcula valor do carro alugado km = float(input("Quantos km foram rodados com o carro? \n")) dias = int(input("Quantos dias ficou com o carro? \n")) conta = (km * 0.15) + (dias * 60) #Calcula quanto irá pagar print("Você irá pagar R$%.2f pelo aluguel do carro" %conta)
f8f811d817cea9bc27e663e2299a43e189e75a51
camilobmoreira/Fatec
/1_Sem/Algoritmos/Lista_04_Capitulo_04_-_Entrega_ 23_03/406_calc_preco_viagem.py
494
4.15625
4
#4.6) Escreva um programa que pergunte a distância que um passageiro deseja percorrer em km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de até 200km e R$0,45 para viagens mais longas. dist = -5 while(dist < 0): dist = float(input("Informe a distância da viagem (km): ")) if(dist < 0): print("I...
c5ca012455abdab80f996356b917f7fb6b2bdb93
JesusArias1995/ejercicio_json
/ejercicio.py
2,351
3.578125
4
from funciones import clasificacion, equiposgolesfavor, rangopuntos, competicion, pelea import urllib.request, json with urllib.request.urlopen("http://apiclient.resultados-futbol.com/scripts/api/api.php?key=7171673be04cc06aa2426307d8b42836&tz=Europe/Madrid&format=json&req=tables&league=1&group=1") as url: datos=jso...
bddf714d37214e9e1c9260563c5975fd48f90b01
kkristof93/AoC-2018
/Day-02/day02-part1.py
300
3.5
4
#!/usr/bin/python twos = 0 threes = 0 with open("input.txt") as file: for line in file: letters = {} for c in line: if c == '\n': continue letters[c] = letters.get(c, 0) + 1 if 2 in letters.values(): twos += 1 if 3 in letters.values(): threes += 1 print(twos * threes)
49a2e19d7c56710844872e93644a619cbc1b617a
aflinky/Algos
/CodeSignalPython/Minesweeper.py
1,444
3.9375
4
# Arcade > Intro > 24 # In the popular Minesweeper game you have a board with some mines and # the cells that don't contain a mine have a number in it that indicates the total number of mines in the neighboring cells. # Starting off with some arrangement of mines we want to create a Minesweeper game setup. # Ex # ...
a596b580c2c61bd9671e56a08317590c296e4939
aflinky/Algos
/CodeSignalPython/CircleOfNumbers.py
491
3.765625
4
# Arcade > Intro > 30 # Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighboring numbers is equal (note that 0 and n - 1 are neighboring, too). # Given n and firstNumber, find the number which is written in the radially opposite position to firs...
90a76a461c52a9b44af8f2d7d02958c50f1dba87
akeebismail/py-requests
/index.py
729
4.0625
4
#!/usr/bin/env python3 a = 12.3 age = 12 # print('my age is ' + str(age) + ' years') # print("My age is {0} years".format(age)) print("There are {0} days in {1}, {2}, {3}, {5}, {6} and {7} ".format(31, "Jan", "March", "May", "July", "August", "Octob...
3121447be25e7cedbd8d95dde79392615277edc6
pawel-d/The-Epic-Odyssey
/Interface/menus.py
4,485
3.828125
4
#!/usr/bin/env python # Copyright (c) 2012 8-Bit Corporation. All rights reserved. """This module contains classes for menus to be used in the game.""" __version__ = "0.1" from abc import ABCMeta, abstractmethod import pygame from pygame.locals import * from Main.constants import * class Button(pygame.sprite.Spr...
903ece6917a11dc9fe3371a1dd7a36e302e0e7cc
pawel-d/The-Epic-Odyssey
/Static/weapons.py
791
3.640625
4
#!/usr/bin/env python # Copyright (c) 2012 8-Bit Corporation. All rights reserved. """This module contains classes for weapons to use in the game.""" from abc import ABCMeta, abstractmethod import pygame from pygame.locals import * from Main.constants import * class Weapon(pygame.sprite.Sprite): __metaclass__...
71e7c02b9f03bb3c0504b824be629ca18922e001
baoziwx/leetcode
/121.py
400
3.734375
4
# 121. Best Time to Buy and Sell Stock class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ minPrice = 'inf' maxSoFar = 0 for p in prices: if p < minPrice: minPrice = p else: ...
72a3a695a3d9111fbbc1a767cce7994727d06d85
baoziwx/leetcode
/295.py
1,368
3.703125
4
# 295. Find Median from Data Stream from heapq import heappush, heappop class MedianFinder(object): def __init__(self): """ initialize your data structure here. """ self.lows = [] self.highs = [] def addNum(self, num): """ :type num: int :rtyp...
65026012b1df7edf11eba1c8162b393ce4810736
baoziwx/leetcode
/199.py
912
3.59375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: Lis...
74468af03fc3c0fba06f3e5d525df4df62c2bda6
baoziwx/leetcode
/206.py
711
4
4
# 206. Reverse Linked List # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # iter...
605f7cc9bfe67751cb89fa883285f051aa33626f
PolinaVasilevichh/Udemy
/сomparison_operators1.py
495
4.375
4
"""Создайте 2 переменных, содержащие числовые значения. Сравните их при помощи всех операторов сравнения и выведите результат на экран """ first_value = 5 second_value = 8 print(first_value > second_value) print(first_value < second_value) print(first_value >= second_value) print(first_value <= second_value) print(fi...
b59250f494354805444856c585f6ce7019405f21
cristhoseby/RegularExpressions
/phone_number.py
1,689
4.34375
4
#phone number validtor import re pattern = """\(0 #open bracket followed by a zero #then either: ( 1 #1 #followed by either: ( \d{3} ...
525f47314ede3650b521cb8454a42ffcfe7a4ce7
LucaDorinAnton/Python101
/patterns.py
3,035
4.125
4
# Creating interesting patterns with Turtle Graphics and # simple algorithms in Python3 import turtle from turtle import * import random screen = turtle.Screen() turtle.setup(850,850) turtle.delay(0) t = Turtle() # Triangle def trig(): t.fd(100) t.left(120) t.fd(100) t.left(120...
858f6449d0b1c0a74273ecd2637bf9c46c317319
alexseong/dsy_python_intro_4
/src/assignment_4.1.1.py
139
3.765625
4
# This 5 lines are provided for you fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: print(line.rstrip())
07d362ca94284750b8c61b54ccf224549745e010
michele-brambilla/ADPluginKafkaEmulator
/streaming/hs00/ArrayDesc.py
1,362
3.609375
4
# namespace: import numpy as np class ArrayDesc(object): """Defines the properties of an array detector result. An array type consists of these attributes: * name, a name for the array * shape, a tuple of lengths in 1 to N dimensions arranged as for C order arrays, i.e. (..., t, y, x), which i...
c5a84486c9e216b5507fb076f1c9c64257804232
DaveG-P/Python
/BookCodes/DICTIONARIES.py
2,745
4.59375
5
# Chapter 6 # A simple dictionary person = {'name': 'david', 'eyes': 'brown', 'age': 28} print(person['name']) print(person['eyes']) # Accessing values in a dictionary print(person['name']) # If there is a number in value use str() print(person['age']) # Adding new key-valu pairs person['dominate side'] = 'left' pers...
2692cc19c897c4f562ea9f5ce39b9d379687e124
NinjaOnRails/del-unneeded-files
/delUnneededFiles.py
1,098
3.796875
4
#! /usr/bin/env python3 # delUnneededFiles - Deletes all files AND folders of certain size in KB import shutil, os folder = input("Enter path to the folder: ") size = int(input("Size in KB: ")) def delUnneededFiles(folder, size): filesFound = 0 for foldername, subfolders, filenames in os.walk(folder): ...
7d689f0416e6e803cd5125f0c08abf659d5a902c
tatiagovorova/Exam_3
/Exam_3.py
2,391
3.9375
4
def Palindrome(a): if a[::-1] == a[::]: return 'Палиндром' else: return "Не палиндром" b = str(input('Введите слово: ')) print(Palindrome(b)) def creditcard(a): print(("*" * (len(a[:-4]))) + a[-4:]) a = int(input("Номер карты: ")) a = str(a) creditcard(a) #Класс Tomato #1.Класс Tomato clas...
79090fc0d547f458def8c226d0f1f2433cd94897
imsanjit/Car_Detector_OpenCV
/car_detector_in_image.py
663
3.78125
4
import cv2 # our image img_file = 'car_image_1.jpg' # our pre-trained car classifier cls_file = 'car_detector.xml' # create opencv image img = cv2.imread(img_file) # convert image to grayscale black_n_white = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # create car classifier car_tracker = cv2.CascadeClassifier(cls_file...
c67e727ee1e968c3cabcc314716378e5a84caf73
UUDeCART/decart_boot_camp_2_2018
/quizzes/quizzes.py
4,344
3.671875
4
from nose.tools import assert_equal, assert_true import numbers import random def literal_variables1(arg1=None, arg2=None): """ arg1: arg2: """ try: assert_true(isinstance(arg1, str)) print("arg1 is a string") try: assert_equal(arg1,"327") print("arg...
f9d3211ad9679fdc41f31446f34e62d381f9f402
proTao/leetcode
/9. LinkedList/082.py
833
3.515625
4
from linkedtools import ListNode, prettyPrintLinkedList, stringToListNode class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ headnode = ListNode(None) headnode.next = head delete = False p = headnode # prev...
fe3e06328a5f8d04c8594ab33e19270fbb7d15e0
proTao/leetcode
/8. Tree/865.py
1,721
3.640625
4
from treetools import * class Solution: def subtreeWithAllDeepest(self, root): """ :type root: TreeNode :rtype: TreeNode """ self.depth = 0 self.deep_node_count = 0 def getAllDeepest(root, depth): if depth > self.depth: self.depth...
329d62a5cd5971a963c39de04f28cb9e00d12827
proTao/leetcode
/1. backtracking/216.py
589
3.6875
4
class Solution: def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ res = [] def deeper(path, target, start_element): print(path, target, start_element) if target == 0 and len(path) == k: ...
9773d6abe3781c5c2bc7c083a267a3b84bc30983
proTao/leetcode
/21. Queue/622.py
1,931
4.1875
4
class MyCircularQueue: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the queue to be k. """ self.data = [None] * k self.head = 0 self.tail = 0 self.capacity = k self.size = 0 def enQueue(self, value...
44be9cfe201313f823c03d624c85595776575ffa
proTao/leetcode
/8. Tree/589.py
683
3.609375
4
class Node(object): def __init__(self, val): self.val = val self.children = None class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ if root is None: return [] stack = [root] res = [] ...
d931a7f877d6294f5457b09483e05c9d615293cb
proTao/leetcode
/9. LinkedList/142.py
749
3.546875
4
from linkedtools import ListNode, prettyPrintLinkedList, stringToListNode class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return None fast = head.next.next slo...
5658c65b585356e5eade12097d9df667d54ea0c0
proTao/leetcode
/1. backtracking/046.py
616
3.671875
4
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] if len(nums) == 0: return [] visited = {i:False for i in nums} def deeper(path): if len(path) == len(nums): ...
0487bbbcf6c9d7ee13f2a7885c7ed31594ac4372
proTao/leetcode
/7. Array/605.py
1,567
3.90625
4
# define DFA status STATUS_EXIST_FLOWER = 1 STATUS_LEFT_EMPTY = 2 STATUS_MIDDLE_POSITION = 3 STATUS_STOP_OR_CONTINUE = 4 class Solution(object): def DFAchangeStatus(self, current_status, next_position): if next_position == 1: return STATUS_EXIST_FLOWER else: if current_stat...
4136b4b4e1b991eba21acf77407dde93ef369d71
proTao/leetcode
/7. Array/888.py
873
3.5
4
class Solution: def fairCandySwap(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ sumA = sum(A) sumB = sum(B) swap = False # make A > B if sumB > sumA: A, B = B, A sumA, sumB = sumB, ...
b044143bbc8cc056d57df3fe5e2c28f46c7000b7
proTao/leetcode
/2. DFS/756.py
1,059
3.53125
4
from collections import defaultdict class Solution: def pyramidTransition(self, bottom, allowed): """ :type bottom: str :type allowed: List[str] :rtype: bool """ self.allowed = defaultdict(lambda : []) for i in allowed: self.allowed[i[:2]].append(i...
11bffbfa030d53a7433a25d5fe641d702e482f43
proTao/leetcode
/9. LinkedList/019.py
679
3.84375
4
from linkedtools import stringToListNode, prettyPrintLinkedList class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ length = 0 node = head while node: node = node.next ...
d725d383a4a4d895937ba6e0d839337a99c258a0
proTao/leetcode
/10. TwoPointers/350.py
571
3.5625
4
class Solution: def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ a = sorted(nums1) b = sorted(nums2) i = 0 j = 0 res = [] while i<len(a) and j<len(b): if a[i]...
1f0594feed9a5176d7733fba89730c38a013467f
proTao/leetcode
/8. Tree/404.py
654
3.515625
4
from treetools import * class Solution: def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 self.res = 0 def deeper(root:TreeNode, is_left): if root.left: deeper(root.lef...
2a946bf2d5d0160c53fc1b8a593e6dd6b0cba5cf
proTao/leetcode
/13. BinarySearch/074.py
877
3.71875
4
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ m = len(matrix) if m == 0: return False n = len(matrix[0]) if n == 0: return False leng...
c1ee9a98e24d043289b78457746e5ee7bbcca820
proTao/leetcode
/7. Array/724.py
687
3.734375
4
from itertools import accumulate ''' def accumulate(l): cur_sum = 0 for i in l: cur_sum += i yield cur_sum ''' class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return -1 if...
e6b4ffd647b7150adcf4def9a5b6678f18fd9f0f
proTao/leetcode
/13. BinarySearch/374.py
708
3.78125
4
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): target = 6 def guess(x): if x == target: return 0 elif x < target: return -1 else: return 1 class Solution(object)...
bc420662296d74f168021d6f8c1f2d55f52be4a6
proTao/leetcode
/7. Array/167.py
554
3.53125
4
x class SolutionOther: def twoSum(self, numbers: 'List[int]', target: 'int') -> 'List[int]': if numbers[0] > target: return [] pre = 0 post = len(numbers) - 1 while pre < post: if numbers[pre] + numbers[post] == target: return [pre + 1, post ...
51487b02ebb40da7b2c330e92c10e63fafdb1abd
proTao/leetcode
/mytools/datastructure/Indexheap.py
3,342
3.6875
4
class MinHeap: def __init__(self): self.N = 0 self.pq = [None] def isEmpty(self): return self.N == 0 def size(self): return self.N def insert(self, key): print("IndexMinHeap Insert", key) self.N += 1 self.pq.append(key) self._swim(self.N...
33168ce77e782c833759b0626c2091c28171c414
proTao/leetcode
/25. Recursion/024.py
598
3.625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs1(self, head: ListNode) -> ListNode: if head: if head.next: head.val, head.next.val = head.next.val, head.val self.swapPairs1(head.next.next) ...
d34b0247cbb150de47a6638ecd6f44d3705eda0b
proTao/leetcode
/23. HashTable/205.py
586
3.65625
4
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: chr_map = {} having_mapped = set() assert len(s) == len(t) for c1, c2 in zip(s, t): if c1 in chr_map: if chr_map[c1] != c2: return False else: # c1 not in chr_m...
b9f02b21503c6f89f2c759bbc49f8a3e8d7e5767
linxd5/LeetCode
/338/338_3.py
476
3.65625
4
#!/usr/bin/env python # coding=utf-8 class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ result, temp_list = [0], [0] num1, num2 = 1, 0 for i in range(1, num+1): result.append(result[num2]+1) num...
5612c7e84d82eaed6f243e1c546517028999b639
huanmengmie/python_study
/base_test/property/with_decorator.py
832
4.0625
4
# -*- coding: utf-8 -*- """ 使用@property装饰器 """ class People(object): def __init__(self, name): self.__name = name @property def name(self): return self.__name @name.getter def name(self): if self.__name: return self.__name+"哈哈" else: p...
cd89983a7e369951f456710d34f36b709e71fcc0
huanmengmie/python_study
/third_module/fileio/base.py
1,976
3.5625
4
# -*- coding:UTF-8 -*- """ 文件操作 """ # 文件操作 mode: r 读,w 写,a 添加,(+ 读写,b 二进制访问) 有问题 # ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not 'b' import json import shutil # 文件路径可为:1、相对路径(note.txt) 2、绝对路径 (D:/workspace/python_study/note.txt) # aHandle = open('note.txt', 'a',encoding="utf8") # 在已有内容上追加 #...
a850fb4798cd8ce6654ff5a2631cce79d7fe1028
giuffridajoe/python-course
/exercises/ex33.py
341
4
4
def looper(loopCounter, loopIncrementer): i = 1 numbers = [] while i <= loopCounter: print "At the top i is %d" % i numbers.append(i) i = i + loopIncrementer print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num ...
be7f5249e86caa685f932b2cbd962d11fb9596a5
purusottam234/Python-Class
/Day 17/exercise.py
722
4.125
4
# Create a list called numbers containing 1 through 15, then perform # the following tasks: # a. Use the built in function filter with lambda to select only numbers even elements function. # Create a new list containing the result # b.Use the built in function map with a lambda to square the values of numbers' eleme...
f17143e0d463bdb1352629eb1aecc0fe3a4add34
purusottam234/Python-Class
/Day 2/number.py
208
4.03125
4
myint = 10 print(myint) # python support two types of number variable ie : integer type and floating point. myfloat = 10.0 print(myfloat) # type conversion x = float(12) print(x) a = int("hello") print(a)
2b02f11857513282ceba8de293dba2f2fab6ae94
purusottam234/Python-Class
/Day 21/summinganything.py
198
3.828125
4
def mysum(*items): if not items: return items output = items[0] for item in items[1:]: output += item return output print(mysum(10, 20)) print(mysum(" a", " b"))
131caa5bb43bae2a4e9dad5e1f3114b9fea23e3f
purusottam234/Python-Class
/Day 15/creating tuples.py
612
3.984375
4
# student_tuple = 'Harry', 'green' # print(student_tuple) # print(len(student_tuple)) # singleton tuple singleton_tuple = ('red', 3) print(singleton_tuple) time_tuple = (2, 3, 5, 6) print(time_tuple[0] * 3600 + time_tuple[1] * 60 + time_tuple[2]) # += augmented assignment t1 = (12, 23, 34) t2 = t1 print(t2) t1 +=...
03b3e29c726f1422f5fa7f6ec200af74bad7b678
purusottam234/Python-Class
/Day 17/generatorexperessions.py
530
4.1875
4
from typing import Iterable # Generator Expression is similar to list comprehension but creates an Iterable # generator object that produce on demand,also known as lazy evaluation # importance : reduce memory consumption and improve performance # use parenthesis inplace of square bracket # This method doesnot crea...
c212f377fd1f1bf1b8644a068bbf0a4d48a86fb0
purusottam234/Python-Class
/Day 5/ifelif.py
524
4.28125
4
# pseudo code # if student'grade is greater than or equal to 90 # display "A" # else if student'grade is greater than or equal to 80 # display "B" # else if student'grade is greater than or equal to 70 # display "C" # else if student'grade is greater than or equal to 60 # display "D" # else # display "E" # Python impl...
5673acacb58b843a57e29346231c482bac0d95bc
purusottam234/Python-Class
/Day 15/del.py
252
4.03125
4
# del statement can be used to remove elements from a list # and to delete variables from interactive session numbers = list(range(0, 10)) print(numbers) del numbers[-1] print(numbers) del numbers[0:2] print(numbers) del numbers[:2] print(numbers)
e2aa79b0249aa1a84ce792a7c0e313dd6b42f901
purusottam234/Python-Class
/Day 20/formattingstring.py
839
3.515625
4
from decimal import Decimal print(f'{17.456 : .2f}') print(f'{17 : d}') print(f'{ 118:c}') print(f'{"hello":s} {7} ') print(f'{ Decimal("100000000.0"):.3f}') print(f'{ Decimal("100000000.0"):.3e}') # field width and alignment print(f'[{ 27:10d}]') print(f'[{ 2.7:10f}]') print(f'[{ 27:<10d}]') print(f'[{ 27:>10d}]')...
95cb35e2359804ab9b5d99677aa205f3ad7f7d32
purusottam234/Python-Class
/Day 6/gradepythonImp.py
425
3.6875
4
# initialized total = 0 grade_counter = 0 # list grades = [98, 76, 87, 83, 90, 57, 79, 82, 94, 54, 71] # processing for grade in grades: total += grade grade_counter += 1 # termination phase average = total/grade_counter # print("class average is:", average) # execution phase # initialized phase # processing ...
415a3f4dd9be70d5f66accb8b25db24791996c0b
purusottam234/Python-Class
/Day 14/conc.py
224
4.125
4
# + operator is used to Concatenate lists list1 = [10, 20, 30] list2 = [40, 50] concatenated_list = list2 + list1 print(concatenated_list) for i in range(len(concatenated_list)): print(f'{i}:{concatenated_list[i]}')
198224b9277d0fe3360e25f0f2ed39a64bce12a3
smenon18/GridCreator
/main.py
3,757
3.78125
4
import random def main(): """ @Version 1.0.0 print randomly Generated Axis With Grid Lines """ cols = [str(i) for i in random.sample(list(range(0, 10)), 10)] rows = [str(i) for i in random.sample(list(range(0, 10)), 10)] grid_spots = [] name_set = set() # Collect Grid Spot fill ins...
dd012da4f847a1ac2d8ee942adcad572104fa345
pianowow/projecteuler
/173/173.py
967
4.125
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: CHRISTOPHER_IRWIN # # Created: 05/09/2012 ##We shall define a square lamina to be a square outline with a square "hole" so ##that the shape possesses vertical and horizontal ...
ef986b7367649367df7b31bbc2ce1c4d0a530447
pianowow/projecteuler
/179/179.py
1,534
3.96875
4
#------------------------------------------------------------------------------- # Name: 179 # Purpose: # # Author: CHRISTOPHER_IRWIN # # Created: 27/08/2012 # Copyright: (c) CHRISTOPHER_IRWIN 2012 # Licence: <your licence> #----------------------------------------------------------------...
01f0ebfcac7c9c79cafc3772014eb22eabc8d141
pianowow/projecteuler
/301 - nim/301.py
2,196
4.0625
4
# Name: 301 # Purpose: # # Author: CHRISTOPHER_IRWIN # # Created: 28/08/2012 ##Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. ## ##We'll consider the three-heap normal-play version of Nim, which ...
5511f2238fed8f2a94498c6e253ddcd439e10337
WhatTheFar/practical-ai-bootcamp
/day3/lab-guide/lab2-problem3.py
1,124
3.5625
4
import numpy as np import matplotlib.pyplot as plt import xlrd ''' Step 1: Read in data from the .xls file ''' DATA_FILE = 'data/fire_theft.xls' book = xlrd.open_workbook(DATA_FILE, encoding_override='utf-8') sheet = book.sheet_by_index(0) number_of_rows = len(list(sheet.get_rows())) data = np.asarray([sheet.row_va...
3fe0d8f943ad472a7f1e62b7dd26b2dd6f50bc33
Cherevko88/Cherevko
/HW9.py
3,512
4.1875
4
# from abc import ABC, abstractmethod from math import sqrt class Point: __x = 0 __y = 0 def __init__(self, a, b): if isinstance(a, (int, float)) and isinstance(b, (int, float)): self.__x = a self.__y = b else: raise TypeError @property def x(sel...
f26cc582b27bfe92b8dcacd6d7552076547e327c
AnnaPlatek/Tic-Tac-Toe
/Problems/Find positions/task.py
259
3.515625
4
num_seq = input().split() x_value = input() position = [] i = 0 for num in num_seq: if x_value == num: position.append(str(i)) i += 1 position_str = ' '.join(position) if len(position) > 0: print(position_str) else: print('not found')
f4fe25c504080372e3fd71867c75077a7d8f7269
theurk/Datacamp1
/1 Python 1/Quiz2.py
323
3.78125
4
#!/usr/bin/env python # coding: utf-8 # ข้อ 1 # In[ ]: duck = lambda x: x/3 print(duck(6)) # In[ ]: # ข้อ 2 def dog(w, x, y, z): result = (w+x+y+z)/4 return result mean = dog(1, 2, 3, 4) print(mean) # In[15]: # ข้อ 3 mean = lambda x, y, z: (x+y+z)/3 print(mean(6, 7, 8)) # In[20]:
d3b65596996845abc3698d54668176067fb8e7f2
theurk/Datacamp1
/1 Python 1/Quiz5.py
1,235
3.71875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = map(lambda x:x**3, lst) print(list(result)) # In[9]: # ต่อไปเป็นแบบไม่ได้ตั้งตัวแปร result = map(lambda x:x**3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(list(result)) # In[11]: # ต่อไปเป็นแบบ function ธรรมดา def M...
2e41bdf25f3618d39bb1cd785b9469bb79a8d8b5
theurk/Datacamp1
/1 Python 1/Quiz7.py
284
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: point = 63 if point > 80: print('เกรด A') elif point > 70: print('เกรด B') elif point > 60: print('เกรด C') elif point > 50: print('เกรด D') else: print('เกรด F') # In[3]:
8bdc7bab4ff74fd233212508c927792fcda9c925
kash-if47/3Sum
/test/threesumtest.py
874
3.65625
4
import unittest from src.ThreeSum import ThreeSum class MyTestCase(unittest.TestCase): def test_empty_input(self): threesum = ThreeSum([]) self.assertEqual([], threesum.find()) def test_single_input(self): threesum = ThreeSum([1]) self.assertEqual([], threesum.find()) de...
32af6bd391f31441626f10cf5bc00c2427eb17d2
heatblazer/python-stuff
/ctor-test.py
883
3.546875
4
import sys class integer(): def __init__(self, i) -> int: if not isinstance(i, int): self.i = None else: self.i = i # a C like struct but they are all like static class Test2: var1 = 10 var2 = "hello" var3 = [] class Test3: def __init__(self) -> object: ...
32b631fcabf9263e2483b01c97b47fde85137c75
albrahim/argilytics
/Gateway/sensor/virtual-sensor.py
361
3.71875
4
import random import time def initialTemprature(): return round(random.uniform(0, 35), 2) def adjust(temprature): adjustment = random.choice([-0.03, 0.00, 0.03]) return temprature + adjustment temprature = initialTemprature() while True: temprature = adjust(temprature) output = round(temprature, ...
1da500e042e2e201dd8cf3e1680f8e6ae0b1ca15
suraj60081/training
/Python/Assignment1.py
1,547
3.921875
4
# Grading System Name = [] Physics = [] Chem = [] Maths = [] Passed = [] Fail = [] Reappear = [] Percentage = [] students = int(input("Enter strenth of class: ")) for i in range(0,students): print("Enter details of ",i+1,": student in following format- Name, Physics marks, Chemistry marks, Maths marks") Name...
9ecc61f4d52f236379f2c9ada813efd364e651c0
liradal/Python-520
/aula2/lacos.py
1,641
4.125
4
#!/usr/bin/python3 ###### ## laços de Repetição ###### ###### ## Laço Whiloe ###### # Este laço executa enquanto uma condição for verdadeira # i = 0 # while(i < 10): # enquanto i for menor que 10 # print(i) # mostra valor de i # i += 1 # i = i + 1 # repete # Como fazer controle de um loop while # whi...
66b4199a8bf357c92e78a65c637d07d79627b657
liradal/Python-520
/aula2/manipulacao_arq.py
1,021
4.375
4
#!/usr/bin/python3 ######### ## Manipulando arquivos com python ######### # ### Abrir um arquivo para modificação # #### Método não recomendado #### # ponteiro = open('nomedoarquivo.txt','a') # abre um ponteiro para # # escrita de arquivos, modo utilizado é o read plus (r+) que serve para # # leitura e escrita.Possu...
abf43bf3607171699f444bc8b3d6b8b762ca1b3b
JNAnnis/Reports337
/Report_10_Updated.py
6,885
3.84375
4
# -*- coding: utf-8 -*- """ Report 10: Statistical Language Models A statistical language model assigns some probability, P(s), to a sentance of N words. Using probability theory, the probability of each word, w, given the words that precede it is P(s) = P(w1)P(w2|w1)P(w3|w1w2)...P(wn|w1w2...wn-1) ...
d28564c2c36afa5fe4e96ce763d90bd07b6f2bcd
alok162/Geek_Mission-Python
/count-pair-sum-in-array.py
901
4.125
4
#A algorithm to count pairs with given sum from collections import defaultdict #function to calculate number of paris in an array def countPairSum(d, arr, sum): count = 0 #storing every array element in dictionary and #parallely checking every element of array is previously #seen in dictionary or not ...
72831d27d547c1c29f4703d5811304568626e8f0
weepwood/AlgorithmDemo
/AlgorithmDemoByPython/Search.py
1,237
3.78125
4
# -*- coding: utf-8 -*- """ @author lanqilu @date Created in 2020/12/11 00:30 @file Search.py @description 线性搜索 """ from typing import List class Search(object): @staticmethod def linear_search(nums: List[int], target: int): for i in range(len(nums)): if nums[i] == target: ...
51ecc647f2c6c292f362031d6d4da1f2806bffa3
akhilerm/Google-Foobar
/hall.py
227
3.5625
4
def answer(s): salutes = 0 people = 0 for person in s: if person == '-': continue elif person == '>': people+=1 else: salutes+=people return salutes*2
08eef6ed26648fa4322bea4d040f1e014302d7f5
rongchaoli/python3
/python3/1-3 冒泡排序(优化).py
753
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/4/3 22:34 # @Author : uncleyong # @Blog : http://www.cnblogs.com/UncleYong # @Gitee : https://gitee.com/UncleYong # @QQ交流群 : 66719336 # 冒泡排序 # 如果已经是一个有序序列,则不需要再排序。 data = [1,2,3,4,5] def sort(data): print('排序前:') print(data) for i in ran...
c672672d124611f81ed95888994fa79e2fea98be
rongchaoli/python3
/python3/3-2 注册(文件).py
1,138
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/4/3 22:34 # @Author : uncleyong # @Blog : http://www.cnblogs.com/UncleYong # @Gitee : https://gitee.com/UncleYong # @QQ交流群 : 66719336 # 注册 # 注册信息存放在文件中 infoFile = 'E:/userinfo.txt' # \\或者/ i = 0 for i in range(3): flag = True username = i...
afe3e847f306fc7701aa3aa0e5c1390458fb1ad2
abdul-malik360/Error_Handling
/task.py
1,969
3.578125
4
import tkinter from tkinter import * from tkinter import messagebox root = Tk() root.geometry("500x500") root.title("Authentification") root.config(bg="#1d3557") user_names = StringVar() passwords = StringVar() Label(root, text="Please Enter Login Details", font=60, foreground="#a8dadc", bg="#1d3557").place(x=150, y=...
3c850b62ebbd655f51a28ae3dcd2912533d93682
hiccup49121/Python_Crush_Course
/exercises/guest.py
274
3.859375
4
filename = 'guest.txt' with open(filename, 'a') as file_object: file_object.write(input( "Please input your name, in a 'Last Name, First Name' format: ") + "\n") with open(filename) as file_object: contents = file_object.read() print(contents)
7d82b3fa170616a79a09eadde88bd309fd2ac38c
d33pe8h-j4a/Pycharm_with_Github
/zipdemo.py
167
3.5
4
names = ("Deepesh", "Jagriti", "Hina", "Ajay",) comps = ("Google", "Dell", "Apple", "MS", "Google",) zipped = (zip(names, comps)) for (a, b) in zipped: print(a, b)
702e5237276e319bf81314d4a759b9ac479ec5b6
emosa/DP
/dynamic-site/data.py
6,086
3.640625
4
""" # ELIMARIE MORALES SANTIAGO # FULL SAIL UNIVERSITY # Design Patterns for Web Programming - Online # Dynamic Site """ class GemstoneInfo(object): def __init__(self): # Data attribute for object gemstone opal = Gemstone() opal.name = 'The Opal' opal.bio = 'The Opal is a type of q...
98055300ea623c763dccd8b01a5d69b7846468fe
rshah918/Cracking-the-Coding-Interview
/uniquechar.py
602
3.90625
4
#Implement an algo to determine if a string has all unique chars def uniqueChars(s): #O(n) s = list(s) char_list = list(range(255)) for char in s: if char_list[ord(char)] == True: return False else: char_list[ord(char)] = True return True; print(uniqueCha...
be137b3de5ded40a35de98e6df183c4be3de9d34
Guilhermesav/assessment
/assessment ex9.py
5,268
3.671875
4
#Usando o código anterior, escreva um novo programa que, quando as teclas ‘w’, ‘a’, ‘s’ e ‘d’ forem pressionadas, #ele movimente o círculo com o texto “clique” nas direções corretas. Caso colida com algum retângulo, o retângulo que participou da colisão deve desaparecer import pygame,random pygame.init() preto = ...
8c99061257227c04ecc8ab356e42227259f6967a
jonnytaddesky/python
/Section 2/operation_on_files.py
1,272
3.5
4
file = open('sample.txt') file data = file.read() print(type(data)) print(data) print(data) print(file.read()) file.seek(0) print(file.read()) file.seek(0) lines = file.readlines() print(type(lines)) print(lines) print(len(lines)) sample_file = open(r"C:\Users\Artem\JupyterRoot\sample.txt") # or open w...
96b4310ccf185907dd3da71cd070b85e63cfc3a2
jonnytaddesky/python
/Section 2/function_string.py
1,312
4.03125
4
x = "hello, my name is Artem" print(len(x)) x[len(x)-1] x.count('l') x.capitalize() print(x) x.upper() print(x) upper_cased = x.upper() print(upper_cased) lower_cased = x.lower() print(lower_cased) print(upper_cased.isupper()) print(lower_cased.islower()) print(x.isupper()) print(x.islower()) lower_cased...
ba88a15da2b1f147587eb8af4414e4f304b52f61
jonnytaddesky/python
/Section 3/dict.py
1,070
3.53125
4
players = { 'Carlsen': 2842, 'Caruana': 2822, 'Mamedyarov': 2801, 'Ding': 2797, 'Giri': 2780 } players = dict(Carlsen=2842, Caruana=2822, Mamedyarov=2801, Ding=2797, Giri=2780) print(players) top1 = players['Carlsen'] print(f"Top chees player`s ratting is {top1}") print(players.get...
dfbf63b781505ec2607a4783f8418bde5d98b36e
jonnytaddesky/python
/HW6/HW6_6.py
761
3.8125
4
prices = {"Strawberries": 1.5, "Banana": 0.5, "Mango": 2.5, "Blueberries": 1, "Raspberries": 1, "Apple": 1.75, "Pineapple": 3.5} class Beverage: def __init__(self, ingredients): self.ingredients = ingredients self.cost = sum([prices[fruit] for fruit in self.ingredients]) ...